Project Euler Problem 34 Digit factorials
2017-03-28 17:48
323 查看
Digit factorials
Problem 34
145 is a curious number, as 1! + 4! + 5! = 1 + 24 + 120 = 145.
Find the sum of all numbers which are equal to the sum of the factorial of their digits.
Note: as 1! = 1 and 2! = 2 are not sums they are not included.
C++:
#include <iostream>
using namespace std;
const int MAX = 2540160;
const int N = 10;
long factorials
= {1, 1};
int main()
{
for(int i=2; i<N; i++)
factorials[i] = factorials[i - 1] * i;
cout << "9! = " << factorials[9] << endl;
cout << "7 * 9! = " << 7 * factorials[9] << endl;
cout << "8 * 9! = " << 8 * factorials[9] << endl;
long total = 0;
for(long i=3; i<=MAX; i++) {
long t = i, sum;
sum = 0;
while(t) {
sum += factorials[t % 10];
t /= 10;
}
if(sum == i)
total += i;
}
cout << total << endl;
return 0;
}
Problem 34
145 is a curious number, as 1! + 4! + 5! = 1 + 24 + 120 = 145.
Find the sum of all numbers which are equal to the sum of the factorial of their digits.
Note: as 1! = 1 and 2! = 2 are not sums they are not included.
C++:
#include <iostream>
using namespace std;
const int MAX = 2540160;
const int N = 10;
long factorials
= {1, 1};
int main()
{
for(int i=2; i<N; i++)
factorials[i] = factorials[i - 1] * i;
cout << "9! = " << factorials[9] << endl;
cout << "7 * 9! = " << 7 * factorials[9] << endl;
cout << "8 * 9! = " << 8 * factorials[9] << endl;
long total = 0;
for(long i=3; i<=MAX; i++) {
long t = i, sum;
sum = 0;
while(t) {
sum += factorials[t % 10];
t /= 10;
}
if(sum == i)
total += i;
}
cout << total << endl;
return 0;
}
相关文章推荐
- http://projecteuler.net/problem=34 [Answer:40730]
- Project Euler problem 34
- project euler Problem 34
- Project Euler problem 66
- Project Euler Problem 59
- Project Euler Problem 4: Largest palindrome product
- Project Euler Problem 15 Lattice paths
- Project Euler Problem 104 Pandigital Fibonacci ends
- Project Euler problem 31
- Project Euler problem 42
- Project Euler problem 52
- Project Euler Problem 21
- project euler Problem 53
- http://projecteuler.net/problem=7 [Answer:104743]
- http://projecteuler.net/problem=16 [Answer:1366]
- Project Euler -> problem 5
- Project Euler problem 61
- Project Euler problem 67
- Project Euler Problem 36
- Project Euler Problem 58