Digit fifth powers
Surprisingly there are only three numbers that can be written as the sum of fourth powers of their digits:
As 1= 1^4is not a sum it is not included.
The sum of these numbers is 1634+8208+9474=19316.
Find the sum of all the numbers that can be written as the sum of fifth powers of their digits.
各位数字的五次幂
令人惊讶的是,只有三个数可以写成其各位数字的四次幂之和:
由于1=1^4并不是求和,所以这里不计入内。
上面这三个数的和是1634+8208+9474=19316。
找出所有可以写成其各位数字的五次幂之和的数,并求这些数的和。
这个题不难,把每位数提出来再通过5的幂次再进行相加起来和这个数本身对比就可以了,但是有个问题就是这个上界去如何得到?
先通过发现每位数最大为9,那么就是每位最大就是,设有n位,那么这个数的每位数的5幂次和最大就为,而有n位的话,这个数就得大于等于,通过这两个条件利用二分法,去得到n最大为6点几
那就取n=7,上界最大就为,最终选择了400000, 然后开始写代码:
#include <stdio.h> #include <math.h> #define MAX_N 400000 int is_perfact_num(int x) { int s = x, num = 0; while (s) { num += pow((s % 10), 5);//将每一位的5幂次加上 s /= 10; } return num == x;//返回数每一位的5幂次和是否与数本身相等 } int main() { int ans = 0; for (int i = 2; i < MAX_N;i++) { if (!is_perfact_num(i)) continue; ans += i; } printf("%d\n", ans); return 0; }
最终答案:443839