2019-07-30 16:00:24 +00:00
|
|
|
"""
|
2024-04-22 19:51:47 +00:00
|
|
|
In mathematics, the Lucas-Lehmer test (LLT) is a primality test for Mersenne
|
2024-03-13 06:52:41 +00:00
|
|
|
numbers. https://en.wikipedia.org/wiki/Lucas%E2%80%93Lehmer_primality_test
|
2020-05-22 06:10:11 +00:00
|
|
|
|
2024-03-13 06:52:41 +00:00
|
|
|
A Mersenne number is a number that is one less than a power of two.
|
|
|
|
That is M_p = 2^p - 1
|
|
|
|
https://en.wikipedia.org/wiki/Mersenne_prime
|
2020-05-22 06:10:11 +00:00
|
|
|
|
2024-04-22 19:51:47 +00:00
|
|
|
The Lucas-Lehmer test is the primality test used by the
|
2024-03-13 06:52:41 +00:00
|
|
|
Great Internet Mersenne Prime Search (GIMPS) to locate large primes.
|
2019-07-30 16:00:24 +00:00
|
|
|
"""
|
|
|
|
|
|
|
|
|
|
|
|
# Primality test 2^p - 1
|
|
|
|
# Return true if 2^p - 1 is prime
|
|
|
|
def lucas_lehmer_test(p: int) -> bool:
|
|
|
|
"""
|
|
|
|
>>> lucas_lehmer_test(p=7)
|
|
|
|
True
|
2020-05-22 06:10:11 +00:00
|
|
|
|
2019-07-30 16:00:24 +00:00
|
|
|
>>> lucas_lehmer_test(p=11)
|
|
|
|
False
|
2020-05-22 06:10:11 +00:00
|
|
|
|
2019-07-30 16:00:24 +00:00
|
|
|
# M_11 = 2^11 - 1 = 2047 = 23 * 89
|
|
|
|
"""
|
|
|
|
|
|
|
|
if p < 2:
|
|
|
|
raise ValueError("p should not be less than 2!")
|
|
|
|
elif p == 2:
|
|
|
|
return True
|
|
|
|
|
|
|
|
s = 4
|
2022-10-12 22:54:20 +00:00
|
|
|
m = (1 << p) - 1
|
2022-10-13 16:03:06 +00:00
|
|
|
for _ in range(p - 2):
|
2022-10-12 22:54:20 +00:00
|
|
|
s = ((s * s) - 2) % m
|
2019-07-30 16:00:24 +00:00
|
|
|
return s == 0
|
|
|
|
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
|
|
print(lucas_lehmer_test(7))
|
|
|
|
print(lucas_lehmer_test(11))
|