How to check if a number is a happy number in Scala

1 Answer

0 votes
import scala.collection.mutable

// 8^2 + 2^2 = 68
// 6^2 + 8^2 = 100
// 1^2 + 0^2 + 0^2 = 1 = happy number

object HappyNumber extends App {

  def sumOfSquares(n: Int): Int =
    n.toString.map(c => {
      val d = c.asDigit
      d * d
    }).sum

  def isHappy(n: Int): Boolean = {
    val seen = mutable.Set[Int]()
    var x = n

    while (x != 1 && !seen.contains(x)) {
      seen += x
      x = sumOfSquares(x)
    }

    x == 1
  }

  val num = 82

  if (isHappy(num))
    println(s"$num is a happy number")
  else
    println(s"$num is NOT a happy number")
}

  
  
  
/*
run:
  
82 is a happy number
  
*/

 

 



answered Feb 24 by avibootz
edited Feb 24 by avibootz
...