#20660: 被TLE了 請問這樣不能過嗎嗚嗚


aaron911229@gmail.com (Aaron lin)


#include <iostream>
using namespace std;
#include <math.h>

int main(){
int num,c;
int i;
while(scanf("%d",&num)){
if(num%2==0){ //判斷是否被2整除
cout<<"非質數"<<endl;
}
else{
c = sqrt(num);
for(i=3;i<=c;i=i+2){ //從3判斷到根號num是否整除
if(num%i == 0){
cout<<"非質數"<<endl;
break;
}
}
if(!(i<=c)){
cout<<"質數"<<endl;
}
}
}
return 0;
}

#20661: Re:被TLE了 請問這樣不能過嗎嗚嗚


fdhs109_GT (GT coding)


基本上 這題不太像新手題 (沒有看起來這個簡單)

必須用有效率的方式判斷質數

可以試試看建表

或著是 google 一下 質數判定法

希望有幫到您~ :)

#20704: Re:被TLE了 請問這樣不能過嗎嗚嗚


happyman940815@gmail.com (【百鬼組】希格瑪 - 一位排球廢物高中生)


恩對不能過

請使用質數去除質數

也就是說

要判斷M是否為質數

要用N去除

(N 屬於 質數 且 小於等於 根號M)

M%2 M%3 M%5 M%7 M%11 M%13 M%17 M%19 M%23 ... ... M%N

 

這樣會省不少時間

測試資料:

165503003

166596887

166596882

測試結果:

Y

Y

N