|
| 1 | +# Miller-Rabin Primality Test |
| 2 | + |
| 3 | +In 1976, Gray Miller introduced an algorithm, through his ph.d thesis[1], which determines a primality of the given number. The original algorithm was deterministic under the Extended Reimann Hypothesis, which is yet to be proven. After four years, Michael O. Rabin improved the algorithm[2] by using probabilistic approach and it no longer assumes the unproven hypothesis. |
| 4 | + |
| 5 | +## Probabilistic |
| 6 | + |
| 7 | +The result of the test is simply a boolean. However, `true` does not implicate *the number is prime*. In fact, it means *the number is **probably** prime*. But `false` does mean *the number is composite*. |
| 8 | + |
| 9 | +In order to increase the accuracy of the test, it needs to be iterated few times. If it returns `true` in every single iteration, than we can say with confidence that *the number is pro......bably prime*. |
| 10 | + |
| 11 | +## Algorithm |
| 12 | + |
| 13 | +Let `n` be the given number, and write `n-1` as `2^s·d`, where d is odd. And choose a random number `a` within the range from `2` to `n - 1`. |
| 14 | + |
| 15 | +Now make a sequence, in modulo `n`, as following: |
| 16 | + |
| 17 | +> a^d, a^(2·d), a^(4·d), ... , a^((2^(s-1))·d), a^((2^s)·d) = a^(n-1) |
| 18 | +
|
| 19 | +And we say the number `n` passes the test, *probably prime*, if 1) `a^d` is congruence to `1` in modulo `n`, or 2) `a^((2^k)·d)` is congruence to `-1` for some `k = 1, 2, ..., s-1`. |
| 20 | + |
| 21 | +### Pseudo Code |
| 22 | + |
| 23 | +The following pseudo code is excerpted from Wikipedia[3]: |
| 24 | + |
| 25 | + |
| 26 | + |
| 27 | +## Usage |
| 28 | + |
| 29 | +```swift |
| 30 | +mrPrimalityTest(7) // test if 7 is prime. (default iteration = 1) |
| 31 | +mrPrimalityTest(7, iteration: 10) // test if 7 is prime & iterate 10 times. |
| 32 | +``` |
| 33 | + |
| 34 | +## Reference |
| 35 | +1. G. L. Miller, "Riemann's Hypothesis and Tests for Primality". *J. Comput. System Sci.* 13 (1976), 300-317. |
| 36 | +2. M. O. Rabin, "Probabilistic algorithm for testing primality". *Journal of Number Theory.* 12 (1980), 128-138. |
| 37 | +3. Miller–Rabin primality test - Wikipedia, the free encyclopedia |
| 38 | + |
| 39 | +*Written for Swift Algorithm Club by **Sahn Cha**, @scha00* |
| 40 | + |
| 41 | +[1]: https://cs.uwaterloo.ca/research/tr/1975/CS-75-27.pdf |
| 42 | +[2]: http://www.sciencedirect.com/science/article/pii/0022314X80900840 |
| 43 | +[3]: https://en.wikipedia.org/wiki/Miller–Rabin_primality_test |
0 commit comments