习题4-6 水仙花数 (20分)
水仙花数是指一个N位正整数(N≥3),它的每个位上的数字的N次幂之和等于它本身。例如:153=13+53+33。 本题要求编写程序,计算所有N位水仙花数。
输入在一行中给出一个正整数N(3≤N≤7)。
按递增顺序输出所有N位水仙花数,每个数字占一行。
3
153
370
371
407
//方法一:
#include
int pow(int x, int n);//直接调用#include里面的pow(x,n)函数会运行超时,故自写了一个pow(x,n)
int main()
{
int i, N, ge, shi, bai, qian, wan, shiwan, baiwan;
scanf( "%d", &N );
if( N == 3 )
{
for( i = 100; i <= 999; i++ )
{
ge = i % 10;
shi = i / 10 % 10;
bai = i / 100;
if( pow(ge,3)+pow(shi,3)+pow(bai,3) == i )
{
printf( "%d\n", i );
}
}
}
else if( N == 4 )
{
for( i = 1000;i <= 9999; i++ )
{
ge = i % 10;
shi = i / 10 % 10;
bai = i / 100 % 10;
qian = i / 1000;
if( pow(ge,4)+pow(shi,4)+pow(bai,4)+pow(qian,4) == i )
{
printf( "%d\n", i );
}
}
}
else if( N == 5 )
{
for( i = 10000; i <= 99999; i++ )
{
ge = i % 10;
shi = i / 10 % 10;
bai = i / 100 % 10;
qian = i / 1000 % 10;
wan = i / 10000;
if( pow(ge,5)+pow(shi,5)+pow(bai,5)+pow(qian,5)+pow(wan,5) == i )
{
printf( "%d\n", i );
}
}
}
else if( N == 6 )
{
for( i = 100000; i <= 999999; i++ )
{
ge = i % 10;
shi = i / 10 % 10;
bai = i / 100 % 10;
qian = i / 1000 % 10;
wan = i / 10000 % 10;
shiwan = i / 100000;
if( pow(ge,6)+pow(shi,6)+pow(bai,6)+pow(qian,6)+pow(wan,6)+pow(shiwan,6) == i )
{
printf( "%d\n", i );
}
}
}
else if( N == 7 )
{
for( i = 1000000;i <= 9999999; i++)
{
ge = i % 10;
shi = i / 10 % 10;
bai = i / 100 % 10;
qian = i / 1000 % 10;
wan = i / 10000 % 10;
shiwan = i / 100000 % 10;
baiwan = i / 1000000;
if( pow(ge,7)+pow(shi,7)+pow(bai,7)+pow(qian,7)+pow(wan,7)+pow(shiwan,7)+pow(baiwan,7) == i )
{
printf( "%d\n", i );
}
}
}
return 0;
}
int pow( int x, int n )
{
int result, i;
if ( n == 0 )
{
return 1;
}
else
{
result = 1;
for ( i = 1; i <= n; i++ )
{
result = result * x;
}
return result;
}
}
//方法二:
#include
int pow(int m, int n);
int main()
{
int n, i, temp, number1, number2, digit, sum;
scanf("%d", &n);
number1 = pow(10, (n - 1.0));
number2 = pow(10, n) - 1;
for ( i = number1; i <= number2; i++ )
{
sum = 0;
temp = i;
while ( temp != 0 )
{
digit = temp % 10;
temp = temp / 10;
sum = sum + pow( digit, n );
}
if ( sum == i )
{
printf( "%d\n", i );
}
}
return 0;
}
int pow( int m, int n )
{
int result, i;
if ( n == 0 )
{
return 1;
}
else
{
result = 1;
for ( i = 1; i <= n; i++ )
{
result = result * m;
}
return result;
}
}