Miller-Rabin Primality Test - Problem
The Miller-Rabin primality test is a probabilistic algorithm used to determine whether a given number is prime. Unlike deterministic tests, Miller-Rabin provides a probability of correctness that increases with the number of iterations.
Given a positive integer n and a number of iterations k, implement the Miller-Rabin test that returns true if n is likely prime, and false if n is definitely composite.
Algorithm Overview:
1. Handle special cases: numbers ≤ 1 are not prime, 2 and 3 are prime
2. Write n-1 = 2^r × d where d is odd
3. For k iterations, pick random witness a in range [2, n-2]
4. Compute x = a^d mod n. If x = 1 or x = n-1, continue to next iteration
5. Square x repeatedly r-1 times. If any result equals n-1, continue to next iteration
6. If no n-1 found in step 5, n is composite
7. If all iterations pass, n is probably prime
Input & Output
Constraints
- 1 ≤ n ≤ 1018
- 1 ≤ k ≤ 20
- For practical purposes, k ≥ 3 recommended