<?php function nextNumber($n) { $len = strlen($n); $sum = 0; for ($i = 0; $i < $len; $i++) { $sum += $n[$i] * $n[$i]; } return $sum . ""; } function isHappy($n) { $soFar = array(); while ($n != 1 && !in_array($n, $soFar)) { $soFar[] = $n; $n = nextNumber($n); } return $n == 1; } foreach (file($argv[1]) as $line) { $number = trim($line); echo isHappy($number) ? 1 : 0; echo "\n"; }
<?php function isHappy($n) { while (1) { $total = 0; while ($n > 0) { $total += pow($n % 10, 2); $n /= 10; } if ($total == 1) { return true; } if (array_key_exists($total, $past)) { return false; } $n = $total; $past[$total] = 0; } } $i = $cnt = 0; while ($cnt < 8) { if (isHappy($i)) { echo "{$i} "; $cnt++; } $i++; }