EularProject 74:Digit factorial chains

来源:互联网 发布:东华软件金融部 编辑:程序博客网 时间:2024/05/20 06:53

Andrew zhang
Sep 4, 2017

The number 145 is well known for the property that the sum of the factorial of its digits is equal to 145:

1! + 4! + 5! = 1 + 24 + 120 = 145

Perhaps less well known is 169, in that it produces the longest chain of numbers that link back to 169; it turns out that there are only three such loops that exist:

169 → 363601 → 1454 → 169
871 → 45361 → 871
872 → 45362 → 872

It is not difficult to prove that EVERY starting number will eventually get stuck in a loop. For example,

69 → 363600 → 1454 → 169 → 363601 (→ 1454)
78 → 45360 → 871 → 45361 (→ 871)
540 → 145 (→ 145)

Starting with 69 produces a chain of five non-repeating terms, but the longest non-repeating chain with a starting number below one million is sixty terms.

How many chains, with a starting number below one million, contain exactly sixty non-repeating terms?

Answer:
402
Completed on Mon, 4 Sep 2017, 23:15

Code:

#include <iostream>#include <set>#include <vector>using namespace std;#define SIZE 2177281int table[10];vector<set<int>> state(SIZE);int next_num(int current){    int result = 0;    while (current)    {        result += table[current % 10];        current /= 10;    }    return result;}void func(int start){    int next = next_num(start);    if (next == start)    {        state[next].insert(next);    }    if (state[next].size() == 0)    {        func(next);    }    state[start] = state[next];    state[start].insert(start);}int main(){    int result = 0;    table[0] = 1;    for (int i = 1; i < 10; i++)    {        table[i] = table[i - 1] * i;    }    state[145].insert(145);    state[169].insert(169);    state[169].insert(363601);    state[169].insert(1454);    state[871].insert(871);    state[871].insert(45361);    state[872].insert(872);    state[872].insert(45362);    for (int i = 1; i < 1000000; i++)    {        func(i);        if (i % 10000 == 0)            cout << i << endl;    }    for (int i = 1; i < 1000000; i++)    {        if(state[i].size() == 60)            result++;    }    cout << result << endl;    getchar();    return 0;}