Skip to content

Instantly share code, notes, and snippets.

@thorntonrose
Created March 27, 2016 00:16
Show Gist options
  • Save thorntonrose/46043456e1b6a0d949bb to your computer and use it in GitHub Desktop.
Save thorntonrose/46043456e1b6a0d949bb to your computer and use it in GitHub Desktop.
Happy Numbers
// 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