Kabelo Victor Sekwadi
Kabelo Victor Sekwadi

Reputation: 11

Lucas-Lehmer Mersenne numbers with Python

Writing a Python code that checks Mersenne numbers using Lucas-Lehmer test.

def lucas_lehmer(p):
 my_list=[4]
 value=2**p-1
 lucas=4
 for val in range(1, p - 1):
    lucas=(lucas*lucas-2)%value
 if lucas== 0:
        my_list.apprend(lucas)
 else: 
  break
 print(my_list)
 print(lucas)

The code shown above only show gives the result for the first iteration, regardless of the p value selected. I want to be able to display all the Lehmer test values within the given value of p, in this case 17.

Upvotes: 1

Views: 845

Answers (1)

mnme
mnme

Reputation: 634

If I understand your question correctly, I think the problem is not doing the append in the loop but only when p is a prime number. Your formatting is somewhat off, so I'm not 100% sure if I'm right. Additionally, you have a typo in append. I added some code to print the actual result of the primality test.

def lucas_lehmer(p):
    my_list=[4]
    value=2**p-1
    lucas=4
    for val in range(1, p - 1):
        lucas = ((lucas*lucas)-2) % value
        my_list.append(lucas)
    if lucas == 0:
        print("prime")
    else:
        print("composite")
    print(my_list)
    print(lucas)

Calling lucas_lehmer(7) leads to the following output:

prime
[4, 14, 67, 42, 111, 0]
0

Upvotes: 1

Related Questions