原理参见《离散数学》P201
#include
#include
#include
#include
using namespace std;
bool Miller_Rabin(long long n)
{
if(n < 2)
return false;
else if(n == 2)
return true;
long long q = 0, m = n - 1;
while(m % 2 == 0) {
m /= 2;
++q;
}
long long a = rand()%(n-2)+2;
long long x1 = (long long)pow(a, m) % n, x2;
for(int i = 1; i <= q; ++i) {
x2 = (x1*x1) % n;
if(x2 == 1 && x1 != 1 && x1 != n-1)
return false;
x1 = x2;
}
if(x2 != 1)
return false;
else
return true;
}
int main(void)
{
srand((unsigned)time(NULL));
long long num;
while(cin >> num) {
if(num > 1) {
if(Miller_Rabin(num))
cout << "true" << endl;
else
cout << "false" << endl;
}
}
return 0;
}