How to check whether a number is a perfect number in Scala

1 Answer

0 votes
// If the sum of all factors of a number is equal to the number, then the number is perfect
 
// Factors of a number are numbers that divide the number evenly
    
// 6
// factors = 1, 2, 3
// 1 + 2 + 3 = 6

object PerfectNumberApp {

  def isPerfect(n: Int): Boolean = {
    if (n < 2) return false

    val limit = math.sqrt(n).toInt

    val sum = (1 to limit).foldLeft(0) { (acc, i) =>
      if (n % i == 0) {
        val pair = n / i
        if (i == pair) acc + i
        else acc + i + pair
      } else acc
    }

    sum - n == n
  }

  def main(args: Array[String]): Unit = {
    println("Perfect numbers up to 10,000:")
    (1 to 10000).foreach { num =>
      if (isPerfect(num)) println(num)
    }
  }
}


/*
run:

Perfect numbers up to 10,000:
6
28
496
8128

*/

 



answered 6 days ago by avibootz
...