From 85eb1d4ea88c8adf4ec7029f8fc444e89e730066 Mon Sep 17 00:00:00 2001 From: swayam patil Date: Fri, 21 Apr 2023 22:25:30 +0530 Subject: [PATCH] Create Miller-Rabin_primalityTest.cpp This code checks if a given number is likely to be a prime using the Miller-Rabin primality test, which is a probabilistic algorithm. The algorithm chooses a random number and tests whether it is a witness for the compositeness of the given number. This is repeated a number of times to increase the confidence in the result. If the number passes all tests, it is considered likely to be prime. --- Miller-Rabin_primalityTest.cpp | 48 ++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 Miller-Rabin_primalityTest.cpp diff --git a/Miller-Rabin_primalityTest.cpp b/Miller-Rabin_primalityTest.cpp new file mode 100644 index 0000000..467a7e9 --- /dev/null +++ b/Miller-Rabin_primalityTest.cpp @@ -0,0 +1,48 @@ +#include +#include +#include + +using namespace std; + +bool miller_rabin(long long n, int k=5) { + // Check some basic primality conditions + if (n < 2) { + return false; + } + if (n == 2 || n == 3) { + return true; + } + if (n % 2 == 0) { + return false; + } + + // Write n-1 as d * 2^r, where d is odd + long long d = n - 1; + int r = 0; + while (d % 2 == 0) { + d /= 2; + r++; + } + + // Perform the Miller-Rabin test k times + for (int i = 0; i < k; i++) { + // Choose a random witness a in the range [2, n-2] + long long a = rand() % (n - 3) + 2; + long long x = pow(a, d) % n; + + // Check whether a is a witness for the compositeness of 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; +}