Created
February 28, 2012 06:28
-
-
Save Synesso/1930199 to your computer and use it in GitHub Desktop.
Happy Numbers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def isHappy(num: Int): Boolean = isHappy(num, Set()) | |
def isHappy(num: Int, seen: Set[Int]): Boolean = { | |
def inner(sum: Int, num: Int): Int = { | |
val digit = num % 10 | |
val squared = math.pow(digit, 2).toInt | |
if (num < 10) sum + squared | |
else inner(sum + squared, (num - digit) / 10) | |
} | |
val ssd = inner(0, num) | |
if (seen.contains(ssd)) false | |
else if (ssd == 1) true | |
else isHappy(ssd, seen + ssd) | |
} | |
val happys = Set(1, 7, 10, 13, 19, 23, 28, 31, 32, 44, 49, 68, 70, 79, 82, 86, 91, 94, 97, 100, 103, 109, 129, 130, | |
133, 139, 167, 176, 188, 190, 192, 193, 203, 208, 219, 226, 230, 236, 239, 262, 263, 280, 291, 293, 301, 302, 310, | |
313, 319, 320, 326, 329, 331, 338, 356, 362, 365, 367, 368, 376, 379, 383, 386, 391, 392, 397, 404, 409, | |
440, 446, 464, 469, 478, 487, 490, 496) | |
val truths = happys.map(isHappy) | |
println(truths) | |
val falsehoods = ((2 to 500).toSet -- happys).map(isHappy) | |
println(falsehoods) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment