$tot = 0; $n = 0; %fastmap = (); for ($i = 1; $i < 10000000; $i++) { %found = (); if ($fastmap{$i} > 0) { $k = $fastmap{$i}; } else { $found{$i} = 1; $k = square_nums($i); while ($found{$k} != 1 && $k != 89) { $found{$k} = 1; $k = square_nums($k); } $fastmap{$i} = $k; } if ($k == 89) { $tot++; } if ($i % 1000000 == 0) { print "$i: $tot\n"; } } print "Total: $tot containing 89\n"; exit; sub square_nums { $x = shift; $t = 0; for ($j = 0; $j < length($x); $j++) { $t += (substr($x,$j,1) * substr($x,$j,1)); } return $t; }