C++實現費馬小定理素數測試
阿新 • • 發佈:2019-01-22
#include<iostream> #include<iomanip> #include<cstdlib> #include<ctime> #include<cmath> using namespace std; long long qmod(int a, int b, int p) { long long res = 1; long long term = a%p; while(b) { if(b&1){ res = (res*term)%p; } term = (term*term)%p; b >>= 1; } return res; } bool is_prime(long long n) { int i; for(i = 0; i < 100; ++i) { if(qmod(1+rand()%(n-1),n-1, n) != 1) break; } if(i < 100) return false; else return true; } int main(void) { int n; while(cin >> n) { if(is_prime(n)) cout << "yes" << endl; else cout << "no" << endl; } return 0; }