>>> lucas_lehmer_test(p=7) True >>> lucas_lehmer_test(p=11) False # M_11 = 2^11 - 1 = 2047 = 23 * 89
(p: int)
| 14 | # Primality test 2^p - 1 |
| 15 | # Return true if 2^p - 1 is prime |
| 16 | def lucas_lehmer_test(p: int) -> bool: |
| 17 | """ |
| 18 | >>> lucas_lehmer_test(p=7) |
| 19 | True |
| 20 | |
| 21 | >>> lucas_lehmer_test(p=11) |
| 22 | False |
| 23 | |
| 24 | # M_11 = 2^11 - 1 = 2047 = 23 * 89 |
| 25 | """ |
| 26 | |
| 27 | if p < 2: |
| 28 | raise ValueError("p should not be less than 2!") |
| 29 | elif p == 2: |
| 30 | return True |
| 31 | |
| 32 | s = 4 |
| 33 | m = (1 << p) - 1 |
| 34 | for _ in range(p - 2): |
| 35 | s = ((s * s) - 2) % m |
| 36 | return s == 0 |
| 37 | |
| 38 | |
| 39 | if __name__ == "__main__": |
no outgoing calls
no test coverage detected