Definition of Happy numbers taken from Wikipedia.
A happy number is defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits in base-ten, and repeat the process until the number either equals 1 (where it will stay), or it loops endlessly in a cycle that does not include 1. Those numbers for which this process ends in 1 are happy numbers, while those that do not end in 1 are unhappy numbers (or sad numbers)
Example: 19 is happy, as the associated sequence is
1*1 + 9*9 = 82,
8*8 + 2*2 = 68,
6*6 + 8*8 = 100,
1*1 + 0*0 + 0*0 = 1.
import scala.collection.mutable.Set
object HappyNumber extends App {
def findSquareSum(n: Int): Int =
n.toString.foldLeft(0) { (product, num) => product + num.asDigit * num.asDigit }
val visited = Set[Int]()
def isHappyNumber(n: Int): Boolean = {
n match {
case 1 => true
case _ =>
if (visited contains n) false
else {
visited += n
if (isHappyNumber(findSquareSum(n))) { visited -= n; true} else false
}
}
}
(1 to 247) foreach { num => if(isHappyNumber(num)) println(num) }
}