水仙花数
来源:互联网 发布:mysql map类型 编辑:程序博客网 时间:2024/04/18 23:49
水仙花数是指一个 n 位数 ( n≥3 ),它的每个位上的数字的 n 次幂之和等于它本身。(例如:1^3 + 5^3 + 3^3 = 153)。
下面是求3位数的水仙花数的C代码:
#include <stdio.h>
int main(void)
{
int a,b,c;
for(a = 1; a < 10; a++)
for(b = 0; b < 10; b++)
for(c = 0; c < 10; c++)
if((100*a+10*b+c) == (a*a*a+b*b*b+c*c*c))
printf("%d%d%d/n",a,b,c);
return 0;
}
// 结果为:
// 153
// 370
// 371
// 407
下面是求7位数的水仙花数的C代码:
#include <math.h>
int main(void)
{
int a, b, c, d, e, f, g;
for(a = 1; a < 10; a++)
for(b = 0; b < 10; b++)
for(c = 0; c < 10; c++)
for(d = 0; d < 10; d++)
for(e = 0; e < 10; e++)
for(f = 0; f < 10; f++)
for(g = 0; g < 10; g++)
{
if((1000000 * a + 100000 * b + 10000 * c + 1000 * d + 100 * e + 10 * f + g) ==
(pow(a, 7) + pow(b, 7) + pow(c, 7) + pow(d, 7) + pow(e, 7) + pow(f, 7) + pow(g, 7)))
{
printf("%d/n", 1000000 * a + 100000 * b + 10000 * c + 1000 * d + 100 * e + 10 * f + g);
}
}
return 0;
}
// 结果:
// 1741725
// 4210818
// 9800817
// 9926315