3 ms·
CoffeeScript solution: (sorry, couldn't resist trying!) happy = (n) -> sum = 0 while (sum += Math.pow n%10, 2 ; n = 0|n/10) then sum
by nadaviv 11y ago
CoffeeScript solution: (sorry, couldn't resist trying!)
happy = (n) ->
sum = 0
while (sum += Math.pow n%10, 2 ; n = 0|n/10) then
sum
happyness = (n, s=[]) ->
(n is 1) or (n not in s) and (happyness (happy n), [ s..., n ])
console.log n for n in [1..100] when happyness n
Edit: and a JavaScript one:
function happy(n) {
for (var sum = 0; n; sum += Math.pow(n%10,2), n = 0|n/10);
return sum
}
function happyness(n, s){
s || (s=[])
return n==1 || !~s.indexOf(n) && happyness(happy(n), s.concat(n))
}
Edit 2: And the golf version:
function h(n,s){for(s=0;n;s+=Math.pow(n%10,2),n=0|n/10);return s}
function H(n,S){return n==1||!~(S=S||[]).indexOf(n)&&H(h(n),S.concat(n))}