/* A number chain is created by continuously adding the square of the digits in a number to form a new number until it has been seen before. For example, 44→32→13→10→1→1 85→89→145→42→20→4→16→37→58→89 Therefore any chain that arrives at 1 or 89 will become stuck in an endless loop. What is most amazing is that EVERY starting number will eventually arrive at 1 or 89. How many starting numbers below ten million will arrive at 89? 各桁の2乗を足し合わせて新たな数を作ることを、同じ数が現れるまで繰り返す。 例えば 44 → 32 → 13 → 10 → 1 → 1 85 → 89 → 145 → 42 → 20 → 4 → 16 → 37 → 58 → 89 のような列である。どちらも1か89で無限ループに陥っている。 驚くことに、どの数から始めても最終的に1か89に到達する。 では、10,000,000より小さい数で89に到達する数はいくつあるか。 */ #include <Windows.h> #include<iostream> using namespace std; int Loop(int n) { if (n==1) return 1; if (n==89) return 89; int next = 0; while (n!=0) { int x = n%10; if (x!=0) next += x*x; n /= 10; } return Loop(next); } int main() { DWORD st = ::GetTickCount(); int counter = 0; for (int i=1; i<10000000; ++i) if (Loop(i)==89) counter++; cout << counter <<endl; DWORD ft = ::GetTickCount(); cout << "run time " << ft-st; return 1; }