您好,我最近遇到了一个问题,对于这样的一个题目:
水仙花数是指一个N位正整数(N≥3),它的每个位上的数字的N次幂之和等于它本身。 本题要求编写程序,计算所有N位水仙花数。
输入格式:
输入在一行中给出一个正整数N(3≤N≤7)。
输出格式:
按递增顺序输出所有N位水仙花数,每个数字占一行。
输入样例:
3
输出样例:
153
370
371
407
代码长度限制
16 KB
时间限制
2500 ms
内存限制
64 MB
我写了如下代码:
#include<stdio.h>
#include<math.h>
int main()
{
int n,i,time = 0;
int num;
int s[10000]={0};
scanf("%d",&n);
num = pow(10,n-1);
if(n == 3)
{
for(i=0; num<pow(10,n); i++, num++)
{
int a,b,c;
a = num % 10;
b = num / 10 % 10;
c = num / 100;
if(num == pow(a,3) + pow(b,3) + pow(c,3))
{
s[time]=num;
time++;
}
}
}
else if(n == 4)
{
for(i=0;num<pow(10,n);i++,num++)
{
int a,b,c,d;
a = num % 10;
b = num / 10 % 10;
c = num / 100 % 10;
d = num / 1000;
if(num == pow(a,4) + pow(b,4) + pow(c,4) + pow(d,4))
{
s[time]=num;
time++;
}
}
}
else if(n == 5)
{
for(i=0;num<pow(10,n);i++,num++)
{
int a,b,c,d,e;
a = num % 10;
b = num / 10 % 10;
c = num / 100 % 10;
d = num / 1000 % 10;
e = num / 10000;
if(num == pow(a,5) + pow(b,5) + pow(c,5) + pow(d,5) + pow(e,5))
{
s[time]=num;
time++;
}
}
}
else if(n == 6)
{
for(i=0;num<pow(10,n);i++,num++)
{
int a,b,c,d,e,f;
a = num % 10;
b = num / 10 % 10;
c = num / 100 % 10;
d = num / 1000 % 10;
e = num / 10000 % 10;
f = num / 100000;
if(num == pow(a,6) + pow(b,6) + pow(c,6) + pow(d,6) + pow(e,6) + pow(f,6))
{
s[time]=num;
time++;
}
}
}
else if(n == 7)
{
for(i=0;num<pow(10,n);i++,num++)
{
int a,b,c,d,e,f,g;
a = num % 10;
b = num / 10 % 10;
c = num / 100 % 10;
d = num / 1000 % 10;
e = num / 10000 % 10;
f = num / 100000 % 10;
g = num / 1000000;
if(num == pow(a,7) + pow(b,7) + pow(c,7) + pow(d,7) + pow(e,7) + pow(f,7) + pow(g,7))
{
s[time]=num;
time++;
}
}
}
for(i=0;i<time;i++)
{
printf("%d",s[i]);
if(i<time)
printf("\n");
}
return 0;
}
自我感觉太繁琐了,并且在提交的时候运行时间超出了规定时间,其余均正确。我在想当你等于一共数字的时候,既然运算方法是类似的,那么能不能用一个循环语句来代替冗长的代码呢?于是我就写了如下的循环语句,但是语法和逻辑可能不对。想请教一下您,有没有一种解决方法?
#include<stdio.h>
#include<math.h>
int main()
{
int a[10]={1,2,3,4,5,6,7,8,9,0};
// int b[7]={0};
int s[10000]={0};
int time=0,i,n,t,num;
scanf("%d",&n);
num = pow(10,n-1)+1;
for(i=0;i<10;i++)
{
if(n == a[i])
for(t=0;num<pow(10,n);t++,num++)
{
int j,k,c,d,e,f,g;
j = num % 10;
k = num / 10 % 10;
c = num / 100 % 10;
d = num / 1000 % 10;
e = num / 10000 % 10;
f = num / 100000 % 10;
g = num / 1000000;
if(num == pow(j,7) + pow(k,7) + pow(c,7) + pow(d,7) + pow(e,7) + pow(f,7) + pow(g,7))
{
s[time]=num;
time++;
}
}
}
for(i=0;i<=time;i++)
{
printf("%d",s[i]);
if(i<time)
printf("\n");
}
return 0;
}