1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
| #include <iostream> #include <cstdlib> #include <ctime> #include <cmath>
long long power(long long x, unsigned long long y, long long p) { long long res = 1;
x = x % p;
if (x == 0) return 0;
while (y > 0) { if (y % 2 == 1) res = (res * x) % p;
y = y >> 1; x = (x * x) % p; } return res; }
bool isPrime(unsigned long long n, int k) { unsigned long long d = n - 1; int r = 0; while (d % 2 == 0) { d /= 2; r++; }
for (int i = 0; i < k; i++) { unsigned long long a = 2 + rand() % (n - 3);
unsigned long long x = power(a, d, n);
if (x == 1 || x == n - 1) continue;
for (int j = 0; j < r - 1; j++) { x = (x * x) % n; if (x == n - 1) break; }
if (x != n - 1) return false; }
return true; }
int main() { srand(static_cast<unsigned int>(time(nullptr)));
unsigned long long numberToCheck = 1125899906842597; int k = 5;
if (isPrime(numberToCheck, k)) { std::cout << numberToCheck << " 可能是素数。" << std::endl; } else { std::cout << numberToCheck << " 不是素数。" << std::endl; }
return 0; }
|