我编写了一段代码来查找第 n 个丑数(至少有一个素因数大于 5 的数),其中 n 是给定的输入。如果用户输入小于 240 的值,我的程序运行良好。但是如果输入大于该值,程序就会崩溃!我的问题是,如果这是一个耗时的问题,那么它应该需要时间,但为什么程序崩溃?我到处都使用了 double,所以这可能不是可变容量的问题! 我的代码如下:
#include<stdio.h>
#include<math.h>
double primes[1000]={2,3,5};
int serial=3;
double next_prime()
{
double f=primes[serial-1]+2;
int count;
for(count=1;primes[count]<=(sqrt(f)+1) && count<serial;count++){
if(fmod(f,primes[count])==0){
f+=2;
count=1;
}
}
return primes[serial++]=f;
}
int main()
{
double ugly_serial=12,ugly_number=16,j;
int c,count,loop,input;
scanf("%d",&input);
while(ugly_serial<input)
{
loop=0;
for(c=3;primes[c-1]<=sqrt(ugly_number);c++){
j=next_prime();
}
for(count=3;count<c;count++){
if(fmod(ugly_number,primes[count])==0){
loop=1;
break;
}
}
if(loop==0){ugly_serial++;}
ugly_number++;
}
printf("%.0lf",ugly_number);
return 0;
}
最佳答案
我已经编译并运行了你的代码。该程序适用于我尝试过的所有输入,包括 56565。
您确定正在运行程序的最新编译版本吗?
关于c - 不知道为什么程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11952822/