2015-11-13 64 views
-2

可以請任何人幫我爲什麼我的代碼給出運行時錯誤:我 無法找到任何錯誤。連續運行時錯誤

的程序的目的在於用篩找到素加上找到的最小質因素爲每數量n

其中n是範圍爲1 < = N < = 10^7

#include<iostream> 
#include<vector> 
#include<cmath> 
#include<cstdio> 
#include<cstring> 
typedef long long ll; 
#define MAX 10000000 

using namespace std; 



bool arr[MAX+1]={false}; 
int sp[MAX+1]={0}; 





void Sieve(){ 
for (int i = 2; i <= MAX; i=i+2)  
{sp[i] = 2; 
} 
for (int i = 3; i <= MAX; i=i+2) 
{ 
    if (arr[i]==false) 
    { 
     sp[i] = i; 

     for (int j = i; (j*i) <= MAX; j=j+2) 
     { 
      if (arr[j*i]==false) 
      { 

       arr[j*i] = true; 
       sp[j*i] = i; 

      } 
     } 
    } 
} 
} 




//inline int scan_d() {int ip=getchar_unlocked(),ret=0,flag=1;for(;ip<'0'||ip>'9';ip=getchar_unlocked())if(ip=='-'){flag=-1;ip=getchar_unlocked();break;}for(;ip>='0'&&ip<='9';ip=getchar_unlocked())ret=ret*10+ip-'0';return flag*ret;} 


int main() 
{ 


Sieve(); 

return 0;  

} 
+6

您是否嘗試過使用調試器?它應該幫助你找到崩潰的地方 – Kevin

+0

其實我正在編譯它,它顯示運行時錯誤。 –

+4

編譯不會顯示運行時錯誤。你得到什麼錯誤? – Kevin

回答

2

爲足夠大的i(這裏我得到錯誤i=46349),內部循環導致錯誤:j初始化與i(= 46349),然後條件(j*i) <= MAX行爲意外由於溢出和j*i ga有負面結果。 一個解決這種方式限制i範圍(這也提高了性能):

int sqrtMAX=sqrt(MAX); 
// write it globally or somewhere before the looping. 
// thanks to @Thomas Matthews 
... 
for (int i = 3; i <= sqrtMAX/*instead of MAX*/ ; i=i+2) 
    if (arr[i]==false) 
     { 
... 
+0

非常感謝馬爾 我知道了 我改變了我和j久了 謝謝..乾杯 –

+0

@shooter_buster另一個幫助吸血鬼送達。你怎麼認爲你的問題對未來的研究有用?請詳細說明。 –

+0

在for循環之前計算'sqrt(MAX)'爲一個常量變量可能會加速程序。 –