7-1 水仙花数 (10 分)
水仙花数是指一个N位正整数(N≥3),它的每个位上的数字的N次幂之和等于它本身。例如:153=1
3
+5
3
+3
3
。 本题要求编写程序,计算所有N位水仙花数。
输入格式:
输入在一行中给出一个正整数N(3≤N≤7)。
输出格式:
按递增顺序输出所有N位水仙花数,每个数字占一行。
输入样例:
3
输出样例:
153
370
371
407
坑点:
如果用系统给的pow函数,在n == 7时会超时,过不了最后一个样例。因为系统的pow函数算法很复杂,能实现的功能很多,用在这有点杀鸡用牛刀。
有两种方法:
法1:在编译器里搜出n == 7的答案,直接输出。
#include <iostream>
#include <cmath>
using namespace std;
int n;
int is(int x)
{
int tot = 0, xx = x;
while(x)
{
tot += pow(x%10,n);
x /= 10;
}
if(tot == xx) return 1;
else return 0;
}
int main()
{
cin>>n;
if(n < 7)
{
for(int i = pow(10,n-1);i < pow(10,n);i++)
if(is(i)) cout<<i<<endl;
}
else
{
cout<<1741725<<endl;
cout<<4210818<<endl;
cout<<9800817<<endl;
cout<<9926315<<endl;
}
return 0;
}
法2:手写pow函数
#include <iostream>
#include <cmath>
using namespace std;
int n;
int Pow(int a, int n){
int i,sum;
for (i=0,sum=1; i<n; i++)
sum*=a;
return sum;
}
int is(int x)
{
int tot = 0, xx = x;
while(x)
{
tot += Pow(x%10,n);
x /= 10;
}
if(tot == xx) return 1;
else return 0;
}
int main()
{
cin>>n;
for(int i = Pow(10,n-1);i < Pow(10,n);i++)
if(is(i)) cout<<i<<endl;
return 0;
}