程序代码:
#include <stdio.h>
#include <math.h>
int main()
{
int a,b,c,d,sum,m;
int s,total;
sum = 0;
total = 0;
for (m=1000; m<10000; m++)
{
a=m/1000;
b=(m/100)%10;
c=(m/10)%10;
d=m%10;
sum = a+b+c+d;
if(sum == 4 || sum == 9 || sum == 16 ||sum == 25)
{
for(s = sqrt(1000)+1; s < sqrt(10000)+1; s++)
{
if(m == s*s)
{
printf("%d = %d^2 \t %d + %d + %d + %d = %d \n", m, s,
a, b, c, d, sum);
total+=m;
}
}
}
}
printf("Total = %d\n", total);
return 0;
}
if(sum == 4 || sum == 9 || sum == 16 ||sum == 25) 这个判断可以提高效率,因为四个数的和范围为 1~36 (1000~9999)
但是双平方数不可能是 1000 和 9999 所以只会是 4 9 16 和 25 了。
结果显示:
1521 = 39^2 1 + 5 + 2 + 1 = 9
1681 = 41^2 1 + 6 + 8 + 1 = 16
2025 = 45^2 2 + 0 + 2 + 5 = 9
2304 = 48^2 2 + 3 + 0 + 4 = 9
2601 = 51^2 2 + 6 + 0 + 1 = 9
3364 = 58^2 3 + 3 + 6 + 4 = 16
3481 = 59^2 3 + 4 + 8 + 1 = 16
3600 = 60^2 3 + 6 + 0 + 0 = 9
4489 = 67^2 4 + 4 + 8 + 9 = 25
4624 = 68^2 4 + 6 + 2 + 4 = 16
5776 = 76^2 5 + 7 + 7 + 6 = 25
5929 = 77^2 5 + 9 + 2 + 9 = 25
7225 = 85^2 7 + 2 + 2 + 5 = 16
7396 = 86^2 7 + 3 + 9 + 6 = 25
8100 = 90^2 8 + 1 + 0 + 0 = 9
8836 = 94^2 8 + 8 + 3 + 6 = 25
9025 = 95^2 9 + 0 + 2 + 5 = 16
Total = 81977
[
本帖最后由 tisyang 于 2011-5-13 14:17 编辑 ]