happy number
public static boolean happyNum(int num) { if (num < 0) { return false; } int sum = 0; while (num > 0) { sum += (num % 10) * (num % 10); num /= 10; } if (sum == 1) { return true; } if (sum == 4) { return false; } return happyNum(sum); }
def square(x): return int(x) * int(x) def happy(num): return sum(map(square, list(str(num)))) def is_happy(num): seen_nums = set() while num > 1 and (num not in seen_nums): seen_nums.add(num) num = happy(num) return num == 1 print is_happy(19)
https://en.wikipedia.org/wiki/Happy_number