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

Example 1 — Small Prime Number
$ Input: n = 97, k = 3
Output: true
💡 Note: 97 is prime. The Miller-Rabin test with 3 iterations will very likely return true, as random witnesses will not be able to prove 97 is composite.
Example 2 — Composite Number
$ Input: n = 15, k = 3
Output: false
💡 Note: 15 = 3 × 5 is composite. Most random witnesses will detect this during the Miller-Rabin test and return false definitively.
Example 3 — Edge Case Small Numbers
$ Input: n = 2, k = 5
Output: true
💡 Note: 2 is the smallest prime number. The algorithm handles this as a special case and returns true immediately.

Constraints

  • 1 ≤ n ≤ 1018
  • 1 ≤ k ≤ 20
  • For practical purposes, k ≥ 3 recommended

Visualization

Tap to expand
INPUTALGORITHMRESULTn = 97k = 3Test 97 for primalitywith 3 random witnesses1Write 96 = 2^5 × 32Pick random witness a3Compute a^d mod n4Square and check for n-1ALL WITNESSESPASSED!TRUE97 is probably primeProbability of error:< (1/4)^3 = 1.6%Key Insight:Miller-Rabin uses random witnesses to probabilistically detect composite numbers.Each witness that passes increases confidence the number is prime.TutorialsPoint - Miller-Rabin Primality Test | Probabilistic Algorithm
Asked in
Google 15 Microsoft 12 Amazon 8 Meta 6
5.7K Views
Medium Frequency
~35 min Avg. Time
234 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen