'commit'
This commit is contained in:
52
C++专题课程/质数相关/三种方法.cpp
Normal file
52
C++专题课程/质数相关/三种方法.cpp
Normal file
@@ -0,0 +1,52 @@
|
||||
#include<bits/stdc++.h>
|
||||
using namespace std;
|
||||
|
||||
//<2F><><EFBFBD>淨
|
||||
bool isPrime(int n) {
|
||||
if (n <= 3) {
|
||||
return n > 1;
|
||||
}
|
||||
for(int i = 2; i < n; i++) {
|
||||
if (n % i == 0) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
// ƽ<><C6BD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ż<EFBFBD>
|
||||
bool isPrimeSqrt(int n) {
|
||||
if (n <= 3) {
|
||||
return n > 1;
|
||||
}
|
||||
int s = sqrt(n);
|
||||
for (int i = 2; i <= s; i++) {
|
||||
if(n % i == 0) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
//6x<36>Ż<EFBFBD><C5BB><EFBFBD>
|
||||
bool isPrime6x(int n) {
|
||||
if (n <= 3) {
|
||||
return n > 1;
|
||||
}
|
||||
if (n % 6 != 1 && n % 6 != 5) {
|
||||
return false;
|
||||
}
|
||||
int s= sqrt(n);
|
||||
for (int i = 5; i <= s; i += 6) {
|
||||
if (n % i == 0 || n % (i + 2) == 0) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
int main() {
|
||||
cout<<isPrime(131)<<endl;
|
||||
cout<<isPrimeSqrt(131)<<endl;
|
||||
cout<<isPrime6x(131)<<endl;
|
||||
|
||||
return 0;
|
||||
}
|
||||
Reference in New Issue
Block a user