您的位置:首页 > 其它

project euler 34 Digit factorials

2018-01-16 12:09 363 查看

题目:

https://projecteuler.net/problem=34

题意:

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.

求所有满足以下条件的数字的和:一个数等于其数位上数字阶乘的和

思路:

可以简单分析一下确定满足条件的数字的上界,当数字为7位时,比如最大的9999999的数位上数字阶乘的和只有2540160,这意味着7位数字中有解的话,也会小于2540160,大于7位的数字则不可能有解,所有只需要判断小于2540160的数字即可,然后累加满足条件的数字

代码:

#include <bits/stdc++.h>
using namespace std;

const int N = 10 + 10;

int fact
;

void fact_table(int n)
{
fact[0] = 1;
for(int i = 1; i <= n; ++i)
fact[i] = fact[i-1] * i;
}
int main()
{
fact_table(9);
//cout << fact[9] << endl;
//cout << 7*fact[9] << endl;
int n = 3000000;
int ans = 0;
for(int i = 10; i <= n; ++i)
{
int temp = 0, val = i;
while(val)
{
temp += fact[val%10];
val /= 10;
}
if(temp == i) ans += i;
}
printf("%d\n", ans);

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: