How to resolve the algorithm Lucas-Lehmer test step by step in the Wren programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Lucas-Lehmer test step by step in the Wren programming language
Table of Contents
Problem Statement
Lucas-Lehmer Test: for
p
{\displaystyle p}
an odd prime, the Mersenne number
2
p
− 1
{\displaystyle 2^{p}-1}
is prime if and only if
2
p
− 1
{\displaystyle 2^{p}-1}
divides
S ( p − 1 )
{\displaystyle S(p-1)}
where
S ( n + 1 )
( S ( n )
)
2
− 2
{\displaystyle S(n+1)=(S(n))^{2}-2}
, and
S ( 1 )
4
{\displaystyle S(1)=4}
.
Calculate all Mersenne primes up to the implementation's maximum precision, or the 47th Mersenne prime (whichever comes first).
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Lucas-Lehmer test step by step in the Wren programming language
Source code in the wren programming language
import "./big" for BigInt
import "./math" for Int
import "io" for Stdout
var start = System.clock
var max = 19
var count = 0
var table = [521, 607, 1279, 2203, 2281, 3217, 4253, 4423]
var p = 3 // first odd prime
var ix = 0 // index into table for larger primes
var one = BigInt.one
var two = BigInt.two
while (true) {
var m = (BigInt.two << (p - 1)) - one
var s = BigInt.four
for (i in 1..p-2) s = (s.square - two) % m
if (s.bitLength == 0) {
count = count + 1
System.write("M%(p) ")
Stdout.flush()
if (count == max) {
System.print()
break
}
}
// obtain next odd prime or look up in table after 127
if (p < 127) {
while (true) {
p = p + 2
if (Int.isPrime(p)) break
}
} else {
p = table[ix]
ix = ix + 1
}
}
System.print("\nTook %(System.clock - start) seconds.")
import "./gmp" for Mpz
import "./math" for Int
var start = System.clock
var max = 28
var count = 0
var table = [521, 607, 1279, 2203, 2281, 3217, 4253, 4423, 9689, 9941, 11213, 19937, 21701, 23209, 44497, 86243, 110503]
var p = 3 // first odd prime
var ix = 0
var one = Mpz.one
var two = Mpz.two
var m = Mpz.new()
var s = Mpz.new()
while (true) {
m.uiPow(2, p).sub(one)
s.setUi(4)
for (i in 1..p-2) s.square.sub(two).rem(m)
if (s.isZero) {
count = count + 1
System.write("M%(p) ")
if (count == max) {
System.print()
break
}
}
// obtain next odd prime or look up in table after 127
if (p < 127) {
while (true) {
p = p + 2
if (Int.isPrime(p)) break
}
} else {
p = table[ix]
ix = ix + 1
}
}
System.print("\nTook %(System.clock - start) seconds.")
You may also check:How to resolve the algorithm Generic swap step by step in the Icon and Unicon programming language
You may also check:How to resolve the algorithm Arrays step by step in the ACL2 programming language
You may also check:How to resolve the algorithm Superpermutation minimisation step by step in the Go programming language
You may also check:How to resolve the algorithm Compile-time calculation step by step in the AppleScript programming language
You may also check:How to resolve the algorithm Stern-Brocot sequence step by step in the Haskell programming language