Created
March 27, 2016 00:16
-
-
Save thorntonrose/46043456e1b6a0d949bb 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
// See: https://en.wikipedia.org/wiki/Happy_number | |
(1 .. 100).each { n -> | |
println "$n:" | |
def sums = [] | |
while (true) { | |
def squares = (n as String).collect { (it as int) ** 2 } | |
n = squares.sum() | |
println " $squares => $n" + (n == 1 ? " (happy)" : "") | |
// Could check that n is in [ 0, 1, 4, 16, 20, 37, 42, 58, 89, or 145 ]. | |
if ((n == 1) || sums.contains(n)) { | |
break | |
} | |
sums << n | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment