2012-08-14 117 views
-3

我已經寫了一個代碼來找到第n個醜數(一個數字,其中至少有一個素數因子大於5),其中n是給定的輸入。我的程序運行良好,如果用戶輸入的東西少於240.但是如果輸入比這個大,程序崩潰!我的問題是如果這是一個耗時的問題,那麼它應該需要時間,但爲什麼程序崩潰?我到處都使用過雙倍數據,因此它可能不是可變容量的問題! 我的代碼如下:不知道爲什麼程序崩潰

#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; 
} 
+10

gdb是你的朋友。 – tbert 2012-08-14 13:02:09

+1

http://www.cprogramming.com/gdbtutorial.html – 2012-08-14 13:04:09

+0

在'main'的第一個''for'循環中,你確定'c'不會超過'1000'嗎?使用一個調試器來查明它是否存在崩潰,如果是,那麼'c'的值是多少。否則,好吧,仍然使用調試器!它應該是你在碰撞時做的第一件事。它會幫助你找到崩潰的地點,並且讓你檢查變量以幫助你理解_why_崩潰的原因。 – 2012-08-14 13:09:41

回答

0

我已編譯並運行您的代碼。該程序正常工作,所有的輸入,我已經嘗試,包括56565.

你確定你正在運行程序的最近編譯版本?

+0

我使用的是代碼塊10.05。你在用什麼? – 2012-08-14 13:59:13