中国高岭土有限公司:将"四位平方数"按升序排列,求前十个"四位平方数"的和.(C代码)

来源:百度文库 编辑:查人人中国名人网 时间:2024/05/10 17:49:05
由于7396=86^2,且7+3+9+6=25=5^2,则称7396是四位双平方数.
四位数中不能有重复的数.

#include <stdio.h>
#include <math.h>
void main()
{
//分别代表千,百,十,个位
int a, b, c, d;
//result是所求四位数,temp用来提取个,十,百,千四个数 int result, temp;
double s; //s用来判断四个数之和是否为一个平方数开方后如果等于开方后取整,那么就是
int r[50]; //整型数组保存要求的四位数
int i=0, j=32; //四位数在1000~10000之间,即32^2---100^2,循环32到100之间即可

do
{
temp = j * j;
result = temp;

//取得四个数
d = temp % 10;
temp = temp/10;
c = temp % 10;
temp = temp/10;
b = temp % 10;
temp = temp/10;
a = temp % 10;

//判断四个数之和是否为一整数的平方
s = double(a + b + c + d);
s = sqrt(s);
if (s == int(s))
{
r[i] = result;
i++;
}
j++;
}while(i < 10 || j < 100);

//输出
for (j=0; j<i; j++)
{
printf("%d\n",r[j]);
}
}

满足要求的四位数一共有17个^_^

我是用VC编的
#include "stdafx.h"
#include "math.h"
bool isqrt(int x)
{
if(sqrt((float)x)*sqrt((float)x)==x)
return true;
else
return false;
}
int _tmain(int argc, _TCHAR* argv[])
{
char d;
int j=1;
int m[50];
for(int i=1000;i<=9999;i++)
{
if(isqrt(i) && isqrt(i/1000 + (i/100)%10 + (i/10)%10 + i%10))
{
m[j]=i;
j++;
if(j<=10)
continue;
else
break;
}
}
//输出数组内容
for(int i=1;i<=10;i++)
{
printf("第%d个数是:%d\n",i,m[i]);
}
scanf("%c",&d);
return 0;
运行结果:
第1个数是:1521
第2个数是:1681
第3个数是:2025
第4个数是:2304
第5个数是:2601
第6个数是:3364
第7个数是:3481
第8个数是:3600
第9个数是:4489
第10个数是:4624