水仙花数是指一个N位正整数(N≥3),它的每个位上的数字的N次幂之和等于它本身。例如:153=13+53+33。 本题要求编写程序,计算所有N位水仙花数。
输入格式:
输入在一行中给出一个正整数N(3≤N≤7)。
输出格式:
按递增顺序输出所有N位水仙花数,每个数字占一行。
输入样例:
3
输出样例:
153
370
371
407
只实现了三位数的水仙花数,用for嵌套的方法不知道怎么改成自定义几位数的水仙花数有大神可以指点下吗?
#include <stdio.h>
#include <math.h>
int main()
{
int n,j,k;
int a, b, c;
scanf("%d", &n);
for ( a = 1; a <= 9; a++ ) {
for ( b = 0; b <= 9; b++ ) {
for ( c = 0; c <= 9; c++ ) {
j=pow(a,n) + pow(b,n) + pow(c,n);
k=a*pow(10,n-1)+b*pow(10,n-2)+c*pow(10,n-3);
if ( j == k ) {
printf("%d\n",k);
}
}
}
}
return 0;
}
后来又写了一个程序,借鉴了其它大神的方法实现了这个功能。while语句用的非常的好!
#include <stdio.h>
#include <math.h>
int main()
{
int n,j,i,sum=0,first,end;
scanf("%d", &n);
first=pow(10,n-1);
end=pow(10,n);
for(i=first;i<end;i++){
j=i;
while(j){
sum+=pow(j%10,n);
j/=10;
}
if(i==sum){
printf("%d\n",i);
}
sum=0;//key
}
return 0;
}