How to find all happy numbers in a specific range with Scala

1 Answer

0 votes
import scala.collection.mutable

// A happy number is a number that eventually reaches 1 
// when repeatedly replaced by the sum of the squares of its digits.
//
// 19 = 1^2 + 9^2 = 82
// 19 -> 82 -> 68 ->100 -> 1 eventually reaches 1 
// 19 = happy numbe

object HappyNumbers {

  // Compute the sum of squares of digits of n
  def sumOfDigitSquares(n: Int): Int = {
    var num = n
    var sum = 0
    while (num > 0) {
      val d = num % 10
      sum += d * d
      num /= 10
    }
    sum
  }

  // Determine whether n is a happy number
  def isHappy(n: Int): Boolean = {
    val seen = mutable.Set[Int]()
    var num = n

    while (num != 1 && !seen.contains(num)) {
      seen += num
      num = sumOfDigitSquares(num)
    }
    num == 1
  }

  def main(args: Array[String]): Unit = {
    var a = 1
    var b = 100

    if (a > b) {
      val temp = a
      a = b
      b = temp
    }

    val happyNumbers = (a to b).filter(isHappy)

    println(s"Happy numbers in range [$a, $b]:")
    println(happyNumbers.mkString(" "))
  }
}



/*
run:

Happy numbers in range [1, 100]:
1 7 10 13 19 23 28 31 32 44 49 68 70 79 82 86 91 94 97 100 

*/

 



answered Feb 25 by avibootz
...