DEV Community

Discussion on: Daily Challenge #78 - Number of Proper Fractions with Denominator d

Collapse
 
avalander profile image
Avalander • Edited

Scala

def properFractions (n: Int): Int = {
  val abs_n = Math.abs(n)
  val propers = for {
    x <- 1 until n
    if gcd(Math.abs(x), abs_n) == 1
  } yield x
  propers.length
}

def gcd(x: Int, y: Int): Int =
  if (y == 0) x
  else gcd(y, x % y)

Not much going on. Generate a sequence with all the numbers between 1 and n - 1 which greatest common denominator with n is one and get the length of that sequence.

Tests

class FractionSpec extends FunSuite {
  test("properFractions") {
    assert(properFractions(1) == 0, "No proper fractions with denominator 1")
    assert(properFractions(2) == 1, "1 proper fraction with denominator 2")
    assert(properFractions(5) == 4, "4 proper fractions with denominator 5")
    assert(properFractions(15) == 8, "8 proper fractions with denominator 15")
    assert(properFractions(25) == 20, "20 proper fractions with denominator 25")
  }
}