Project Euler - problem 092

August 1st, 2007 by Daniel Høyer Iversen

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?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
 
#include <iostream>
#include <ctime>
using namespace std;
 
#define limit 10000000
 
int nextNumberChain(int num);
 
int main ()
{
clock_t start = clock();
int res(0), number(0);
cout << " er her ";
 
for(int i = 2; i < limit; i++){
number = i;
while( !(number == 1 || number == 89)){
number = nextNumberChain(number);
}
if(number == 89){
res++;
}
}
 
cout << "resultatet er ";
cout << res << "n";
cout<< ( ( clock() - start ) / (double)CLOCKS_PER_SEC ) <<'n';
return 0;
}
 
int nextNumberChain(int num){
int res(0), temp(0);
 
while(num != 0){
temp = (num % 10);
res += temp*temp;
num -= temp;
num /= 10;
}
return res;
}
Do you want to use this code?

0 Responses to “Project Euler - problem 092”

  1. No Comments

Leave a Response