首先是6N+1,6N-1法,但這個在zerojudge測資會愈時,不過平常拿來玩玩也是堪用的
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include<iostream> | |
#include<math.h> | |
using namespace std; | |
int main(){ | |
int a; | |
while(cin >> a){ | |
int b = 0; | |
if(a==2 || a==3){ | |
cout << "質數" << endl; | |
} | |
else if (a%2==0 || a%3==0){ | |
cout << "非質數" << endl; | |
b = 1; | |
}else{ | |
int a_sqrt =sqrt(a); | |
for (int i = 5, gap=2; i <= a_sqrt; i+=gap, gap=6-gap){ | |
if (a%i==0){ | |
cout << "非質數" << endl; | |
b = 1; | |
break; | |
} | |
} | |
if(b==0){ | |
cout << "質數" << endl;} | |
} | |
} | |
return 0; | |
} |
第二個方法是用埃拉托斯特尼篩法(sieve)建質數表,測資1.4s過 (雖然不算最快的..XD)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include<iostream> | |
#include<math.h> | |
using namespace std; | |
int prime[5150]={0}; | |
void findPrime(){ | |
char judge[50000]={0}; | |
int m = 0; | |
for (int a = 2; a<=50000; a++){ | |
if (judge[a]==0){ | |
prime[m++]= a; | |
for (int b=2; b*a<=50000; b++){ | |
judge[b*a]=1; | |
} | |
} | |
} | |
} | |
bool is_prime(int num){ | |
int num_sqrt =sqrt(num); | |
for(int i=0; prime[i]<=num_sqrt;i++){ | |
if (num%prime[i]==0&&num/prime[i]!=1){ | |
return false; | |
} | |
}return true; | |
} | |
int main(){ | |
findPrime(); | |
int a; | |
while (cin >> a){ | |
if(is_prime(a)){ | |
cout << "質數" << endl; | |
}else { | |
cout << "非質數" << endl; | |
} | |
} | |
return 0; | |
} |
沒有留言:
張貼留言