求出0~999之间的所有“水仙花数”并输出。“水仙花数”是指一个三位数,其各位数字的立方和确好等于该数本身。

在数论中,水仙花数(Narcissistic number)也称为自恋数、自幂数、阿姆斯壮数或阿姆斯特朗数(Armstrong number),是指一N位数,其各个数之N次方和等于该数。 
例如153、370、371及407就是三位数的水仙花数,其各个数之立方和等于该数: 
153 = 1^3 + 5^3 + 3^3。 
370 = 3^3 + 7^3 + 0^3。 
371 = 3^3 + 7^3 + 1^3。 

407 = 4^3 + 0^3 + 7^3。 

#include<stdio.h>
#include<math.h>
int main()
{
int i = 0;
for(; i <= 999; i++)
{
int tmp = 0;
int sum = 0;
int count = 1;
tmp = i//
i赋值给tmp
while(tmp/10)//用while循环判断有几位数
{
count ++;//满足条件,计数器++
tmp /= 10;
}
tmp = i;//重新赋值
while(tmp)//判断i是否为水仙花数
{
sum += pow((tmp % 10), count);//pow函数,求一个数的次方,如输入参数pow(3,3),即得27
tmp /= 10;
}
if(sum == i)//如果sum等于i,找到了,并且输出
printf("%d ", i);


}
return 0;
}


猜你喜欢

转载自blog.csdn.net/yikaozhudapao/article/details/80083817