Skip to content

Add Lucas_Lehmer_primality_test #1050

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Jul 30, 2019
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions maths/lucas_lehmer_primality_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
# -*- coding: utf-8 -*-
"""
In mathematics, the Lucas–Lehmer test (LLT) is a primality test for Mersenne numbers.
https://en.wikipedia.org/wiki/Lucas%E2%80%93Lehmer_primality_test

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

The Lucas–Lehmer test is the primality test used by the
Great Internet Mersenne Prime Search (GIMPS) to locate large primes.
"""


# 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

>>> lucas_lehmer_test(p=11)
False

# 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
M = (1 << p) - 1
for i in range(p - 2):
s = ((s * s) - 2) % M
return s == 0


if __name__ == "__main__":
print(lucas_lehmer_test(7))
print(lucas_lehmer_test(11))