Lucas-Lehmer test: Difference between revisions

m (added M prefix for showing Mersenne numbers)
 
(47 intermediate revisions by 18 users not shown)
Line 16:
{{trans|D}}
 
<langsyntaxhighlight lang="11l">F isPrime(p)
I p < 2 | p % 2 == 0
R p == 2
Line 37:
L(p) 2..2299
I isMersennePrime(p)
print(‘M’p, end' ‘ ’)</langsyntaxhighlight>
 
{{out}}
Line 46:
=={{header|360 Assembly}}==
For maximum compatibility, this program uses only the basic instruction set.
<langsyntaxhighlight lang="360asm">* Lucas-Lehmer test
LUCASLEH CSECT
USING LUCASLEH,R12
Line 118:
LTORG
YREGS
END LUCASLEH</langsyntaxhighlight>
{{out}}
<pre>M002
Line 130:
 
=={{header|Ada}}==
<langsyntaxhighlight lang="ada">with Ada.Text_Io; use Ada.Text_Io;
with Ada.Integer_Text_Io; use Ada.Integer_Text_Io;
 
Line 157:
end if;
end loop;
end Lucas_Lehmer_Test;</langsyntaxhighlight>
{{Out}}
Mersenne primes:
Line 165:
Because of the very large numbers computed,
the mapm binding is used to calculate with arbitrary precision.
<langsyntaxhighlight lang="agena">readlib 'mapm';
 
mapm.xdigits(100);
Line 187:
write('M' & i & ' ')
fi
od;</langsyntaxhighlight>
produces:
<langsyntaxhighlight lang="agena">M3 M5 M7 M13 M17 M19 M31</langsyntaxhighlight>
 
=={{header|ALGOL 68}}==
Line 195:
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-1.18.0/algol68g-1.18.0-9h.tiny.el5.centos.fc11.i386.rpm/download 1.18.0-9h.tiny]}}
{{wont work with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d] - due to extensive use of '''format'''[ted] ''transput''}}
<langsyntaxhighlight lang="algol68">PRAGMAT stack=1M precision=20000 PRAGMAT
 
PROC is prime = ( INT p )BOOL:
Line 233:
count <= upb count
DO SKIP OD
)</langsyntaxhighlight>
{{Out}}
<pre>
Line 243:
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
<lang ARM Assembly>
/* ARM assembly Raspberry PI */
/* program lucaslehmer.s */
Line 459:
iMagicNumber: .int 0xCCCCCCCD
 
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 486:
=={{header|Arturo}}==
 
<langsyntaxhighlight lang="rebol">mersenne?: function [p][
if p=2 -> return true
mp: dec shl 1 p
Line 497:
print "Mersenne primes:"
mersennes: select 2..32 'x -> and? prime? x mersenne? x
print join.with:", " map mersennes 'm -> ~"M|m|"</langsyntaxhighlight>
 
{{out}}
Line 505:
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f LUCAS-LEHMER_TEST.AWK
# converted from Pascal
Line 524:
exit(0)
}
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 530:
</pre>
 
=={{header|BBC BASIC}}==
==={{header|BASIC256}}===
BASIC256 has no large integer support. Calculations are limited to the range of a integer type.
<syntaxhighlight lang="basic256">print "Mersenne Primes :"
for p = 2 to 18
if lucasLehmer(p) then print "M"; p
next p
end
 
function lucasLehmer (p)
mp = (2 ^ p) - 1
sn = 4
for i = 2 to p-1
sn = (sn ^ 2) - 2
sn = sn - (mp * floor(sn / mp))
next
return sn = 0
end function</syntaxhighlight>
 
==={{header|BBC BASIC}}===
{{works with|BBC BASIC for Windows}}
Using its native arithmetic BBC BASIC can only test up to M23.
<langsyntaxhighlight lang="bbcbasic"> *FLOAT 64
PRINT "Mersenne Primes:"
FOR p% = 2 TO 23
Line 550 ⟶ 569:
sn -= (mp * INT(sn / mp))
NEXT
= (sn = 0)</langsyntaxhighlight>
{{Out}}
<pre>
Line 562 ⟶ 581:
M19
</pre>
 
==={{header|Craft Basic}}===
<syntaxhighlight lang="basic">let m = 7
let n = 1
 
for e = 2 to m
 
if e = 2 then
 
let s = 0
 
else
 
let s = 4
 
endif
 
let n = (n + 1) * 2 - 1
 
for i = 1 to e - 2
 
let s = (s * s - 2) % n
 
next i
 
if s = 0 then
print e, " ",
 
endif
 
next e</syntaxhighlight>
{{Out}}
<pre>2 3 5 7 </pre>
 
=={{header|BCPL}}==
{{trans|Zig}}
Uses the 64 bit version
<syntaxhighlight lang="bcpl">
<lang BCPL>
GET "libhdr"
 
Line 595 ⟶ 648:
RESULTIS 0
}
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 612 ⟶ 665:
If a number cannot be factorized, (either because it is prime or because it is to great to fit in a computer word) the root expression doesn't change much.
For example, the expression <code>13^(13^-1)</code> becomes <code>13^1/13</code>, and this matches the pattern <code>13^%</code>.
<langsyntaxhighlight lang="bracmat"> ( clk$:?t0:?now
& ( time
= ( print
Line 657 ⟶ 710:
)
& done
);</langsyntaxhighlight>
{{Out}} (after 4.5 hours):
<pre>0,00 0,00 s: M3 is PRIME!
Line 681 ⟶ 734:
1101,12 10491,08 s: M9941 is PRIME!
5618,45 16109,53 s: M11213 is PRIME!</pre>
 
 
 
=={{header|Burlesque}}==
<syntaxhighlight lang="burlesque">607rz2en{J4{J.*2.-2{th}c!**-..%}#R2.-E!n!it}f[2+]{2\/**-.}m[p^</syntaxhighlight>
 
{{out}}
<pre>3
7
31
127
8191
131071
524287
2147483647
2305843009213693951
618970019642690137449562111
162259276829213363391578010288127
170141183460469231731687303715884105727
6864797660130609714981900799081393217269435300143305409394463459185543183397656052122559640661454554977296311391480858037121987999716643812574028291115057151
531137992816767098689588206552468627329593117727031923199444138200403559860852242739162502265229285668889329486246501015346579337652707239409519978766587351943831270835393219031728127</pre>
 
 
 
=={{header|C}}==
Line 690 ⟶ 766:
 
{{libheader|GMP}}
<langsyntaxhighlight Clang="c">#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
Line 765 ⟶ 841:
printf("\n");
return 0;
}</langsyntaxhighlight>
 
{{out}}
Line 775 ⟶ 851:
{{works with|C99}}
Compiler options: gcc -std=c99 -lm Lucas-Lehmer_test.c -o Lucas-Lehmer_test<br>
<langsyntaxhighlight lang="c">#include <math.h>
#include <stdio.h>
#include <limits.h>
Line 819 ⟶ 895:
}
printf("\n");
}</langsyntaxhighlight>
 
{{Out}}
Line 830 ⟶ 906:
{{works with|Visual Studio|2010}}
{{works with|.NET Framework|4.0}}
<langsyntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
using System.Numerics;
Line 876 ⟶ 952:
}
}
}</langsyntaxhighlight>
 
{{out}} (Run only to 11213)
Line 886 ⟶ 962:
The mod function, (<code>%</code>) has a computation cost equivalent to the divide operation. In this case, a combination of ands, shifts and adds can replace the mod function. Another change is creating the list of candidate Mersenne numbers in descending order, the point being to start the more time consuming calculations first. This avoids a long calculation occurring by itself at the end of the <code>Parallel.For</code> queue. Also added trial division step, translated from the '''Rust''' and '''C''' versions.
 
<langsyntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
using System.Numerics;
Line 922 ⟶ 998:
if (System.Diagnostics.Debugger.IsAttached) Console.ReadLine();
}
}</langsyntaxhighlight>
{{out}}
<pre>M2 M3 M5 M7 M13 M17 M19 M31 M61 M89 M107 M127 M521 M607 M1279 M2203 M2281 M3217 M4253 M4423 M9689 M9941 M11213
Line 932 ⟶ 1,008:
{{libheader|GMP}}
 
<langsyntaxhighlight lang="cpp">#include <iostream>
#include <gmpxx.h>
 
static bool is_mersenne_prime(mpz_class p)
{
if( 2 == p ) {
return true;
else}
 
mpz_class s(4);
mpz_class div( (mpz_class(1) << p.get_ui()) - 1 );
for( mpz_class i(3); i <= p; ++i )
{
mpz_classs = (s * s - mpz_class(42)) % div ;
}
mpz_class div( (mpz_class(1) << p.get_ui()) - 1 );
 
for( mpz_class i(3); i <= p; ++i )
return ( s == mpz_class(0) {);
s = (s * s - mpz_class(2)) % div ;
}
 
return ( s == mpz_class(0) );
}
}
 
int main()
{
Line 968 ⟶ 1,043:
}
}
}</langsyntaxhighlight>
 
{{out}} (Incomplete; It takes a long time.)
Line 976 ⟶ 1,051:
 
=={{header|Clojure}}==
<langsyntaxhighlight lang="lisp">(defn prime? [i]
(cond (< i 4) (>= i 2)
(zero? (rem i 2)) false
Line 988 ⟶ 1,063:
(recur (inc n) (rem (- (* s s) 2) mp)))))))
 
(filter mersenne? (filter prime? (iterate inc 1)))</langsyntaxhighlight>
{{Out}}
<pre>
Line 997 ⟶ 1,072:
=={{header|CoffeeScript}}==
Coffee Script is really hampered by its lack of full syntactic support for JavaScript generators. The loop to collect Mersenne numbers must be done in imperative style, rather than a more functional style, when using the infinite lazy prime generator.
<syntaxhighlight lang="coffeescript">
<lang CoffeeScript>
sorenson = require('sieve').primes # Sorenson's extensible sieve from task: Extensible Prime Number Generator
 
# Test if 2^n-1 is a Mersenne prime.
# assumes that the argument np is prime.
#
isMersennePrime = (p) ->
Line 1,018 ⟶ 1,093:
 
console.log "Some Mersenne primes: #{"M" + String p for p in mersennes}"
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 1,027 ⟶ 1,102:
=={{header|Common Lisp}}==
{{trans|Clojure}}
<langsyntaxhighlight lang="lisp">
(defun or-f (&optional a b) (or a b));necessary for reduce, as 'or' is implemented as a macro
 
Line 1,044 ⟶ 1,119:
 
(princ (remove-if-not #'mersenne-p (remove-if-not #'prime-p (loop for i to 5000 collect i))))
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,052 ⟶ 1,127:
=={{header|Crystal}}==
{{trans|Ruby}}
<langsyntaxhighlight lang="ruby">require "big"
 
def is_prime(n) # P3 Prime Generator primality test
Line 1,087 ⟶ 1,162:
break if count >= upb_count
end
puts</langsyntaxhighlight>
 
{{out}}
Line 1,095 ⟶ 1,170:
=={{header|D}}==
{{trans|Python}}
<langsyntaxhighlight lang="d">import std.stdio, std.math, std.bigint;
 
bool isPrime(in uint p) pure nothrow @safe @nogc {
Line 1,124 ⟶ 1,199:
stdout.flush;
}
}</langsyntaxhighlight>
{{out}}
<pre>M2 M3 M5 M7 M13 M17 M19 M31 M61 M89 M107 M127 M521 M607 M1279 M2203 M2281 </pre>
With p up to 10_000 it prints:
<pre>M2 M3 M5 M7 M13 M17 M19 M31 M61 M89 M107 M127 M521 M607 M1279 M2203 M2281 M3217 M4253 M4423 M9941 </pre>
 
=={{header|Delphi}}==
{{works with|Delphi|6.0}}
{{libheader|SysUtils,StdCtrls}}
 
 
<syntaxhighlight lang="Delphi">
 
function IsMersennePrime(P: int64): boolean;
{Test for Mersenne Prime - P cannot be bigger than 63}
{Because (1 shl 64) would be bigger than in64}
var S,MP: int64;
var I: integer;
begin
if P= 2 then Result:=true
else
begin
MP:=(1 shl P) - 1;
S:=4;
for I:=3 to P do
begin
S:=(S * S - 2) mod MP;
end;
Result:=S = 0;
end;
end;
 
 
procedure ShowMersennePrime(Memo: TMemo);
var Sieve: TPrimeSieve;
var I: integer;
begin
{Create Sieve}
Sieve:=TPrimeSieve.Create;
{Test cannot handle values bigger than 64}
Sieve.Intialize(64);
for I:=0 to Sieve.PrimeCount-1 do
if IsMersennePrime(Sieve.Primes[I]) then
begin
Memo.Lines.Add(IntToStr(Sieve.Primes[I]));
end;
Sieve.Free;
end;
 
 
 
</syntaxhighlight>
{{out}}
<pre>
2
3
5
7
13
17
19
31
 
Elapsed Time: 10.167 ms.
</pre>
 
 
=={{header|DWScript}}==
Using Integer type, which is 64bit, limits the search to M31.
<langsyntaxhighlight lang="delphi">function IsMersennePrime(p : Integer) : Boolean;
var
i, s, m_p : Integer;
Line 1,157 ⟶ 1,293:
Print(' M'+IntToStr(p));
end;
PrintLn('');</langsyntaxhighlight>
{{Out}}
<pre> M2 M3 M5 M7 M13 M17 M19 M31</pre>
 
=={{header|EasyLang}}==
{{trans|BASIC256}}
<syntaxhighlight>
write "Mersenne Primes: "
func lulehm p .
mp = bitshift 1 p - 1
sn = 4
for i = 2 to p - 1
sn = sn * sn - 2
sn = sn - (mp * (sn div mp))
.
return if sn = 0
.
for p = 2 to 23
if lulehm p = 1
write "M" & p & " "
.
.
</syntaxhighlight>
 
{{out}}
<pre>
Mersenne Primes: M3 M5 M7 M13 M17 M19
</pre>
 
=={{header|EchoLisp}}==
<langsyntaxhighlight lang="scheme">
(require 'bigint)
(define (mersenne-prime? odd-prime: p)
Line 1,182 ⟶ 1,343:
 
→ M3 M5 M7 M13 M17 M19 M31 M61 M89 M107 M127 M521 M607 M1279 M2203 M2281
</syntaxhighlight>
</lang>
 
=={{header|Elixir}}==
{{trans|Erlang}}
<langsyntaxhighlight lang="elixir">defmodule LucasLehmer do
use Bitwise
def test do
Line 1,199 ⟶ 1,360:
end
 
LucasLehmer.test</langsyntaxhighlight>
 
{{out}}
Line 1,207 ⟶ 1,368:
 
=={{header|Erlang}}==
<langsyntaxhighlight lang="erlang">-module(mp).
-export([main/0]).
 
Line 1,213 ⟶ 1,374:
 
s(MP,1) -> 4 rem MP;
s(MP,N) -> X=s(MP,N-1), (X*X - 2) rem MP.</langsyntaxhighlight>
 
In 3 seconds will print
Line 1,223 ⟶ 1,384:
=={{header|ERRE}}==
With native arithmetic up to 23: for bigger numbers you must use MULPREC program.
<langsyntaxhighlight ERRElang="erre">PROGRAM LL_TEST
 
!$DOUBLE
Line 1,247 ⟶ 1,408:
END FOR
END PROGRAM
</syntaxhighlight>
</lang>
{{out}}
<pre>Mersenne Primes:
Line 1,261 ⟶ 1,422:
=={{header|F Sharp|F#}}==
Simple arbitrary-precision version:
<langsyntaxhighlight lang="fsharp">let rec s mp n =
if n = 1 then 4I % mp else ((s mp (n - 1)) ** 2 - 2I) % mp
 
[ for p in 2..47 do
if p = 2 || s ((1I <<< p) - 1I) (p - 1) = 0I then
yield p ]</langsyntaxhighlight>
 
Tail-recursive version:
<langsyntaxhighlight lang="fsharp">let IsMersennePrime exponent =
if exponent <= 1 then failwith "Exponent must be >= 2"
let prime = 2I ** exponent - 1I;
Line 1,279 ⟶ 1,440:
LucasLehmer 0 4I = 0I
</syntaxhighlight>
</lang>
 
Version using library folding function (way shorter and faster than the above):
<langsyntaxhighlight lang="fsharp">let IsMersennePrime exponent =
if exponent <= 1 then failwith "Exponent must be >= 2"
let prime = 2I ** exponent - 1I;
Line 1,290 ⟶ 1,451:
LucasLehmer = 0I
</syntaxhighlight>
</lang>
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">USING: io math.primes.lucas-lehmer math.ranges prettyprint
sequences ;
 
47 [1,b] [ lucas-lehmer ] filter
"Mersenne primes:" print
[ "M" write pprint bl ] each nl</langsyntaxhighlight>
{{out}}
<pre>
Line 1,306 ⟶ 1,467:
 
=={{header|Forth}}==
<syntaxhighlight lang="text">: lucas-lehmer
1+ 2 do
4 i 2 <> * abs swap 1+ dup + 1- swap
Line 1,313 ⟶ 1,474:
;
 
1 15 lucas-lehmer</langsyntaxhighlight>
==Alternate version to handle 64 and 128 bit integers.==
Forth supports modular multiplication without overflow by having mixed mode operations that work on 128 bit intermediate results. It's also possible to do do the Lucas-Lehmer test using double-precision (128 bit) integers, though support for that is more limited in the Forth language, so it requires writing more support code. This version contains the code for both 64 bit (mixed mode) and 128 bit (double precision mode)
<syntaxhighlight lang="forth">
<lang Forth>
18 constant π-64 \ count of primes < 64
31 constant π-128 \ count of primes < 128
Line 1,384 ⟶ 1,545:
if 'M emit i c@ . then
loop ;
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 1,398 ⟶ 1,559:
{{works with|Fortran|90 and later}}
Only Mersenne number with prime exponent can be themselves prime but for the small numbers used in this example it was not worth the effort to include this check. As the size of the exponent increases this becomes more important.
<langsyntaxhighlight lang="fortran">PROGRAM LUCAS_LEHMER
IMPLICIT NONE
 
Line 1,418 ⟶ 1,579:
END DO
END PROGRAM LUCAS_LEHMER</langsyntaxhighlight>
===128 Bit Version===
This version can find all Mersenne Primes up to M127. Its based on the Zig code but written in Fortran 77 style (fixed format, unstructured loops.) Works with GNU Fortran which has 128 bit integer support.
 
<syntaxhighlight lang="fortran">
PROGRAM Mersenne Primes
IMPLICIT INTEGER (a-z)
LOGICAL is mersenne prime
 
PARAMETER (sz primes = 31)
INTEGER*1 primes(sz primes)
 
DATA primes
& /2, 3, 5, 7, 11, 13, 17, 19, 23, 29,
& 31, 37, 41, 43, 47, 53, 59, 61, 67, 71,
& 73, 79, 83, 89, 97, 101, 103, 107, 109, 113,
& 127/
 
PRINT *, 'These Mersenne numbers are prime:'
 
DO 10 i = 1, sz primes
p = primes(i)
10 IF (is mersenne prime(p))
& WRITE (*, '(I5)', ADVANCE = 'NO'), p
 
PRINT *
END
 
 
FUNCTION is mersenne prime(p)
IMPLICIT NONE
LOGICAL is mersenne prime
INTEGER*4 p, i
INTEGER*16 n, s, modmul
 
IF (p .LT. 3) THEN
is mersenne prime = p .EQ. 2
ELSE
n = 2_16**p - 1
s = 4
DO 10 i = 1, p - 2
s = modmul(s, s, n) - 2
10 IF (s .LT. 0) s = s + n
is mersenne prime = s .EQ. 0
END IF
END
 
 
FUNCTION modmul(a0, b0, m)
IMPLICIT INTEGER*16 (a-z)
 
modmul = 0
a = MODULO(a0, m)
b = MODULO(b0, m)
 
10 IF (b .EQ. 0) RETURN
IF (MOD(b, 2) .EQ. 1) THEN
IF (a .LT. m - modmul) THEN
modmul = modmul + a
ELSE
modmul = modmul - m + a
END IF
END IF
b = b / 2
IF (a .LT. m - a) THEN
a = a * 2
ELSE
a = a - m + a
END IF
GO TO 10
END
</syntaxhighlight>
{{Out}}
<pre>
These Mersenne numbers are prime:
2 3 5 7 13 17 19 31 61 89 107 127
</pre>
 
=={{header|FreeBASIC}}==
===Native types for Mersenne primes <= M63===
<langsyntaxhighlight lang="freebasic">' version 18-09-2015
' compile with: fbc -s console
 
Line 1,474 ⟶ 1,711:
Print : Print "hit any key to end program"
Sleep
End</langsyntaxhighlight>
{{out}}
<pre> M3 M5 M7 M13 M17 M19 M31 M61</pre>
==={{libheader|GMP}}===
Uses the trick from the '''C''' entry to avoid the slow Mod
<langsyntaxhighlight lang="freebasic">' version 18-09-2015
' compile with: fbc -s console
 
Line 1,560 ⟶ 1,797:
Print : Print "hit any key to end program"
Sleep
End</langsyntaxhighlight>
{{out}}
<pre>M3 M5 M7 M13 M17
Line 1,571 ⟶ 1,808:
Frink's <CODE>isPrime</CODE> function automatically detects numbers of the form 2<sup>n</sup>-1 and performs a Lucas-Lehmer test on them, including testing if n is prime, which is sufficient to prove primality for this form.
 
<langsyntaxhighlight lang="frink">
for n = primes[]
if isPrime[2^n-1]
println[n]
</syntaxhighlight>
</lang>
 
=={{header|FunL}}==
<langsyntaxhighlight lang="funl">def mersenne( p ) =
if p == 2 then return true
Line 1,592 ⟶ 1,829:
 
for p <- primes().filter( mersenne ).take( 20 )
println( 'M' + p )</langsyntaxhighlight>
 
{{out}}
Line 1,620 ⟶ 1,857:
 
=={{header|GAP}}==
<langsyntaxhighlight lang="gap">LucasLehmer := function(n)
local i, m, s;
if n = 2 then
Line 1,637 ⟶ 1,874:
 
Filtered([1 .. 2000], LucasLehmer);
[2, 3, 5, 7, 13, 17, 19, 31, 61, 89, 107, 127, 521, 607, 1279]</langsyntaxhighlight>
 
=={{header|Go}}==
Processing the first list indicates that the test works. Processing the second shows it working on some larger numbers.
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,676 ⟶ 1,913:
}
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,687 ⟶ 1,924:
{{works with|GHC|6.8.2}}
 
<langsyntaxhighlight lang="haskell">module Main
where
 
Line 1,698 ⟶ 1,935:
lucasLehmer p = s (2^p-1) (p-1) == 0
 
printMersennes = mapM_ (\x -> putStrLn $ "M" ++ show x)</langsyntaxhighlight>
It is pointed out on the [[Sieve of Eratosthenes]] page that the following "sieve" is inefficient. Nonetheless it takes very little time compared to the Lucas-Lehmer test itself.
<langsyntaxhighlight lang="haskell">sieve (p:xs) = p : sieve [x | x <- xs, x `mod` p > 0]</langsyntaxhighlight>
It takes about 30 minutes to get up to:
<pre>
Line 1,707 ⟶ 1,944:
 
=={{header|HicEst}}==
<langsyntaxhighlight HicEstlang="hicest">s = 0
DO exponent = 2, 31
IF(exponent > 2) s = 4
Line 1,717 ⟶ 1,954:
ENDDO
 
END</langsyntaxhighlight>
 
=={{header|J}}==
Line 1,726 ⟶ 1,963:
We use arbitrary-precision integers in order to be able to test any arbitrary prime.
 
<langsyntaxhighlight lang="java">import java.math.BigInteger;
public class Mersenne
{
Line 1,770 ⟶ 2,007:
System.out.println();
}
}</langsyntaxhighlight>
{{Out}} (after about eight hours):
<pre>
Line 1,780 ⟶ 2,017:
In JavaScript we using BigInt ( numbers with 'n' suffix ) - so we can use really big numbers
 
<syntaxhighlight lang="javascript">
<lang Javascript>
////////// In JavaScript we don't have sqrt for BigInt - so here is implementation
function newtonIteration(n, x0) {
Line 1,840 ⟶ 2,077:
}
console.log(`... Took: ${Date.now()-tm} ms`);
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 1,879 ⟶ 2,116:
Output includes the length of the decimal representation of the Mersenne prime.
 
<langsyntaxhighlight lang="jq"># To take advantage of gojq's arbitrary-precision integer arithmetic:
def power($b): . as $in | reduce range(0;$b) as $i (1; . * $in);
 
Line 1,911 ⟶ 2,148:
| "M\($i):\($mp|tostring|length)" );
 
mersenne_primes</langsyntaxhighlight>
{{out}}
<pre>
Line 1,939 ⟶ 2,176:
</pre>
=={{header|Julia}}==
<syntaxhighlight lang="julia">
<lang Julia>
using Primes
 
Line 1,956 ⟶ 2,193:
 
getmersenneprimes(50)
</syntaxhighlight>
</lang>
{{output}}<pre>
M2, cumulative time elapsed: 0.019999980926513672 seconds
Line 1,989 ⟶ 2,226:
=={{header|Kotlin}}==
In view of the Java result, I've set the program to stop at M4423 so it will run in a reasonable time (about 85 seconds) on a typical laptop:
<langsyntaxhighlight lang="scala">// version 1.0.6
 
import java.math.BigInteger
Line 2,035 ⟶ 2,272:
}
}
}</langsyntaxhighlight>
 
{{out}}
Line 2,044 ⟶ 2,281:
=={{header|langur}}==
{{trans|D}}
It is theoretically possible to test to the 47th Mersenne prime, as stated in the task description, but it could take a while. As for the limit, it would be extremely high.
{{works with|langur|0.8.1}}
With slight syntactic differences, this would also work with earlier versions of langur if you limit it to smaller numbers. 0.8 uses arbitrary precision.
 
<syntaxhighlight lang ="langur">val .isPrime = f fn(.i) == 2 or{
.i >== 2 and not any f(.x)or .i div .x, pseries> 2 to .i ^/ 2and
not any(fn .x: .i div .x, pseries 2 .. .i ^/ 2)
}
 
val .isMersennePrime = ffn(.p) {
if .p == 2: return true
if not .isPrime(.p): return false
 
val .mp = 2 ^ .p - 1
for[.s=4] of 3 to.. .p {
.s = (.s ^ 2 - 2) rem .mp
} == 0
}
 
writeln join " ", map ffn .x: $"M\{{.x;}}", wherefilter .isMersennePrime, series 2300</lang>
</syntaxhighlight>
 
{{out}}
<pre>M2 M3 M5 M7 M13 M17 M19 M31 M61 M89 M107 M127 M521 M607 M1279 M2203 M2281
</pre>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
This version is very speedy and is bounded.
<langsyntaxhighlight Mathematicalang="mathematica">Select[Table[M = 2^p - 1;
For[i = 1; s = 4, i <= p - 2, i++, s = Mod[s^2 - 2, M]];
If[s == 0, "M" <> ToString@p, p], {p,
Prime /@ Range[300]}], StringQ]
 
=> {M3, M5, M7, M13, M17, M19, M31, M61, M89, M107, M127, M521, M607, M1279}</langsyntaxhighlight>
 
This version is unbounded (and timed):
<langsyntaxhighlight Mathematicalang="mathematica">t = SessionTime[];
For[p = 2, True, p = NextPrime[p], M = 2^p - 1;
For[i = 1; s = 4, i <= p - 2, i++, s = Mod[s^2 - 2, M]];
If[s == 0, Print["M" <> ToString@p]]]
(SessionTime[] - t) {Seconds, Minutes/60, Hours/3600, Days/86400}</langsyntaxhighlight>
 
I'll see what this gets.
Line 2,084 ⟶ 2,327:
MATLAB suffers from a lack of an arbitrary precision math (bignums) library.
It also doesn't have great support for 64-bit integer arithmetic...or at least MATLAB 2007 doesn't. So, the best precision we have is doubles; therefore, this script can only find up to M19 and no greater.
<langsyntaxhighlight MATLABlang="matlab">function [mNumber,mersennesPrime] = mersennePrimes()
 
function isPrime = lucasLehmerTest(thePrime)
Line 2,118 ⟶ 2,361:
mersennesPrime = (2.^mNumber) - 1;
end</langsyntaxhighlight>
 
{{Out}}
<langsyntaxhighlight MATLABlang="matlab">[mNumber,mersennesPrime] = mersennePrimes
 
mNumber =
Line 2,130 ⟶ 2,373:
mersennesPrime =
 
3 7 31 127 8191 131071 524287</langsyntaxhighlight>
 
=={{header|Maxima}}==
<langsyntaxhighlight lang="maxima">lucas_lehmer(p) := block([s, n, i],
if not primep(p) then false elseif p = 2 then true else
(s: 4,
Line 2,142 ⟶ 2,385:
 
sublist(makelist(i, i, 1, 200), lucas_lehmer);
/* [2, 3, 5, 7, 13, 17, 19, 31, 61, 89, 107, 127] */</langsyntaxhighlight>
 
=={{header|Modula-3}}==
Modula-3 uses L as the literal for <tt>LONGINT</tt>.
<langsyntaxhighlight lang="modula3">MODULE LucasLehmer EXPORTS Main;
 
IMPORT IO, Fmt, Long;
Line 2,172 ⟶ 2,415:
END;
IO.Put("\n");
END LucasLehmer.</langsyntaxhighlight>
{{Out}}
<pre>M2 M3 M5 M7 M13 M17 M19 M31 </pre>
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">import math
 
proc isPrime(a: int): bool =
Line 2,200 ⟶ 2,443:
if isPrime(p) and isMersennePrime(p):
stdout.write " M",p
echo ""</langsyntaxhighlight>
{{Out}}
<pre> Mersenne primes:
Line 2,207 ⟶ 2,450:
=={{header|Oz}}==
Oz's multiple precision number system use GMP core.
<langsyntaxhighlight lang="oz">%% compile : ozc -x <file.oz>
functor
import
Line 2,270 ⟶ 2,513:
{Application.exit 0}
end</langsyntaxhighlight>
 
=={{header|PARI/GP}}==
===Standard version===
<lang parigp>LL(p)={
<syntaxhighlight lang="parigp">LL(p)={
my(m=Mod(4,1<<p-1));
for(i=3,p,m=m^2-2);
Line 2,284 ⟶ 2,528:
if(LL(p), print("2^"p"-1"))
)
};</langsyntaxhighlight>
 
===Version with trial division and fast modular reduction===
 
ll.gp
<syntaxhighlight lang="c">
/* ll(p): input odd prime 'p'. */
/* returns '1' if 2^p-1 is a Mersenne prime. */
ll(p) = {
/* trial division up to a reasonable depth (time ratio tdiv/llt approx. 0.2) */
my(l=log(p), ld=log(l));
forprimestep(q = 1, sqr(ld)^(l/log(2))\4, p+p,
if(Mod(2,q)^p == 1, return)
);
/* Lucas-Lehmer test with fast modular reduction. */
my(s=4, m=2^p-1, n=m+2);
for(i = 3, p,
s = sqr(s);
s = bitand(s,m)+ s>>p;
if(s >= m, s -= n, s -= 2)
);
!s
}; /* end ll */
 
 
/* get Mersenne primes in range [a,b] */
llrun(a, b) = {
my(t=0, c=0, p=2, thr=default(nbthreads));
if(a <= 2,
c++;
printf("#%d\tM%d\t%3dh, %2dmin, %2d,%03d ms\n", c, p, t\3600000, t\60000%60, t\1000%60, t%1000);
a = 3;
);
gettime();
parforprime(p= a, b, ll(p), d, /* ll(p) -> d copy from parallel world into real world. */
if(d,
t += gettime()\thr;
c++;
printf("#%d\tM%d\t%3dh, %2dmin, %2d,%03d ms\n", c, p, t\3600000, t\60000%60, t\1000%60, t%1000)
)
)
}; /* end llrun */
 
 
\\ export(ll); /* if running ll as script */
</syntaxhighlight>
Compiled with gp2c option: gp2c-run -g ll.gp.
 
<syntaxhighlight lang="c">llrun(2, 132049)</syntaxhighlight>
{{out}}
 
Done on Intel(R) Core(TM) i5-8250U CPU @ 1.60GHz, 4 hyperthreaded cores.
<pre>#1 M2 0h, 0min, 0,000 ms
#2 M3 0h, 0min, 0,000 ms
#3 M5 0h, 0min, 0,000 ms
#4 M7 0h, 0min, 0,000 ms
#5 M13 0h, 0min, 0,000 ms
#6 M17 0h, 0min, 0,000 ms
#7 M19 0h, 0min, 0,000 ms
#8 M31 0h, 0min, 0,000 ms
#9 M61 0h, 0min, 0,000 ms
#10 M89 0h, 0min, 0,000 ms
#11 M107 0h, 0min, 0,000 ms
#12 M127 0h, 0min, 0,000 ms
#13 M521 0h, 0min, 0,001 ms
#14 M607 0h, 0min, 0,001 ms
#15 M1279 0h, 0min, 0,007 ms
#16 M2203 0h, 0min, 0,030 ms
#17 M2281 0h, 0min, 0,033 ms
#18 M3217 0h, 0min, 0,079 ms
#19 M4253 0h, 0min, 0,163 ms
#20 M4423 0h, 0min, 0,186 ms
#21 M9689 0h, 0min, 1,789 ms
#22 M9941 0h, 0min, 2,022 ms
#23 M11213 0h, 0min, 2,835 ms
#24 M19937 0h, 0min, 23,858 ms
#25 M21701 0h, 0min, 35,268 ms
#26 M23209 0h, 0min, 45,233 ms
#27 M44497 0h, 6min, 53,051 ms
#28 M86243 1h, 3min, 41,811 ms
#29 M110503 2h, 29min, 14,055 ms
#30 M132049 4h, 42min, 27,694 ms
? ##
*** last result: cpu time 37h, 31min, 41,619 ms, real time 4h, 42min, 46,515 ms.</pre>
 
=={{header|Pascal}}==
int64 is good enough up to M31:
<langsyntaxhighlight lang="pascal">Program LucasLehmer(output);
var
s, n: int64;
Line 2,306 ⟶ 2,633:
writeln('M', exponent, ' is PRIME!');
end;
end.</langsyntaxhighlight>
{{Out}}
<pre>:> ./LucasLehmer
Line 2,321 ⟶ 2,648:
=={{header|Perl}}==
Using [https://metacpan.org/pod/Math::GMP Math::GMP]:
<langsyntaxhighlight lang="perl">use Math::GMP qw/:constant/;
 
sub is_prime { Math::GMP->new(shift)->probab_prime(12); }
Line 2,336 ⟶ 2,663:
foreach my $p (2 .. 43_112_609) {
print "M$p\n" if is_prime($p) && is_mersenne_prime($p);
}</langsyntaxhighlight>
 
The ntheory module offers a couple options. This is direct:
{{libheader|ntheory}}
<langsyntaxhighlight lang="perl">use ntheory qw/:all/;
$|=1; # flush output on every print
my $n = 0;
Line 2,347 ⟶ 2,674:
print "M$n ";
}
print "\n";</langsyntaxhighlight>
However it uses knowledge from the thousands of CPU years spent by GIMPS to accelerate results for known values, so doesn't actually run the L-L test until after the 44th value, although code is included for C, Perl, and C+GMP. If we substitute <tt>Math::Prime::Util::GMP::is_mersenne_prime</tt> we can force the test to run.
 
A less opaque method uses the modular Lucas sequence, though it has no pretesting other than primality and calculates both <math>U_k</math> and <math>V_k</math> so won't be as fast:
<langsyntaxhighlight lang="perl">use ntheory qw/:all/;
use bigint try=>"GMP,Pari";
forprimes {
Line 2,357 ⟶ 2,684:
my $mp1 = 2**$p;
print "M$p\n" if $p == 2 || 0 == (lucas_sequence($mp1-1, 4, 1, $mp1))[0];
} 43_112_609;</langsyntaxhighlight>
 
We can also use the core module <code>Math::BigInt</code>:
{{trans|Python}}
<langsyntaxhighlight lang="perl">sub is_prime {
my $p = shift;
if ($p == 2) {
Line 2,406 ⟶ 2,733:
}
last if $count >= $upb_count;
}</langsyntaxhighlight>
 
=={{header|Phix}}==
{{libheader|Phix/mpfr}}
Native types work up to M31, after which inaccuracies mean that we need to wheel out gmp. Uses the mod replacement trick from C/FreeBASIC(gmp)
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #004080;">bool</span> <span style="color: #000000;">full</span> <span style="color: #0000FF;">=</span> <span style="color: #004600;">true</span> <span style="color: #000080;font-style:italic;">-- (see extended output below)</span>
Line 2,466 ⟶ 2,793:
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"completed in %s\n"</span><span style="color: #0000FF;">,{</span><span style="color: #7060A8;">elapsed</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">time</span><span style="color: #0000FF;">()-</span><span style="color: #000000;">t0</span><span style="color: #0000FF;">)})</span>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 2,521 ⟶ 2,848:
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(de prime? (N)
(or
(= N 2)
Line 2,538 ⟶ 2,865:
(do (- P 2)
(setq S (% (- (* S S) 2) MP)) )
(=0 S) ) ) )</langsyntaxhighlight>
{{Out}}
<pre>: (for N 10000
Line 2,570 ⟶ 2,897:
be smaller than 1000.
 
<langsyntaxhighlight lang="pop11">define Lucas_Lehmer_Test(p);
lvars mp = 2**p - 1, sn = 4, i;
for i from 2 to p - 1 do
Line 2,586 ⟶ 2,913:
endif;
p + 2 -> p;
endwhile;</langsyntaxhighlight>
 
{{Out}} (obtained in few seconds)
<langsyntaxhighlight lang="pop11">M2
M3
M5
Line 2,602 ⟶ 2,929:
M127
M521
M607</langsyntaxhighlight>
 
=={{header|PowerShell}}==
This is just a translation of VBScript using [bigint], it could be optimized.
Flirt with the girl in the cubicle next door while it runs:
<syntaxhighlight lang="powershell">
<lang PowerShell>
function Get-MersennePrime ([bigint]$Maximum = 4800)
{
Line 2,636 ⟶ 2,963:
}
}
</syntaxhighlight>
</lang>
<syntaxhighlight lang="powershell">
<lang PowerShell>
Get-MersennePrime | Format-Wide {"{0,4}" -f $_} -Column 4 -Force
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 2,650 ⟶ 2,977:
 
=={{header|Prolog}}==
<langsyntaxhighlight lang="prolog">
show(Count) :-
findall(N, limit(Count, (between(2, infinite, N), mersenne_prime(N))), S),
Line 2,688 ⟶ 3,015:
N mod D =\= 0,
D2 is D + A, prime(N, D2, As).
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 2,698 ⟶ 3,025:
=={{header|PureBasic}}==
PureBasic has no large integer support. Calculations are limited to the range of a signed quad integer type.
<langsyntaxhighlight PureBasiclang="purebasic">Procedure Lucas_Lehmer_Test(p)
Protected mp.q = (1 << p) - 1, sn.q = 4, i
For i = 3 To p
Line 2,722 ⟶ 3,049:
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf</langsyntaxhighlight>
{{Out}}
<pre>M2
Line 2,734 ⟶ 3,061:
 
=={{header|Python}}==
<langsyntaxhighlight lang="python">
from sys import stdout
from math import sqrt, log
Line 2,771 ⟶ 3,098:
if count >= upb_count: break
print
</syntaxhighlight>
</lang>
 
{{Out}}
Line 2,778 ⟶ 3,105:
 
=== Faster loop without division ===
<langsyntaxhighlight lang="python">
def isqrt(n):
if n < 0:
Line 2,844 ⟶ 3,171:
if count >= upb_count: break
print
</syntaxhighlight>
</lang>
 
The main loop may be run much faster using [https://pypi.python.org/pypi/gmpy2 gmpy2] :
 
<langsyntaxhighlight lang="python">import gmpy2 as mp
 
def lucas_lehmer(n):
Line 2,864 ⟶ 3,191:
s -= m
s -= two
return mp.is_zero(s)</langsyntaxhighlight>
 
With this, one can test all primes below 10^5 in around 24 hours on a Core i5 processor, with only one running thread.
Line 2,873 ⟶ 3,200:
 
Of course, they agree with [[oeis:A000043|OEIS A000043]].
 
=={{header|Quackery}}==
 
<code>eratosthenes</code> and <code>isprime</code> are defined at [[Sieve of Eratosthenes#Quackery]].
 
<syntaxhighlight lang="Quackery"> [ dup temp put
dup bit 1 -
4
rot 2 - times
[ dup *
dup temp share >>
dip [ over & ] +
2dup > not if
[ over - ]
2 - ]
0 =
nip temp release ] is l-l ( n --> b )
 
25000 eratosthenes
[] 25000 times [ i^ isprime if [ i^ join ] ]
1 split
witheach
[ dup l-l iff join else drop ]
echo</syntaxhighlight>
 
{{out}}
 
<pre>[ 2 3 5 7 13 17 19 31 61 89 107 127 521 607 1279 2203 2281 3217 4253 4423 9689 9941 11213 19937 21701 23209 ]</pre>
 
=={{header|R}}==
<syntaxhighlight lang="r">
<lang r>
# vectorized approach based on scalar code from primeSieve and mersenne in CRAN package `numbers`
require(gmp)
Line 2,909 ⟶ 3,264:
}
}
</syntaxhighlight>
</lang>
 
=={{header|Racket}}==
<langsyntaxhighlight lang="racket">
#lang racket
(require math)
Line 2,928 ⟶ 3,283:
 
(loop 3)
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku" perl6line>multi is_mersenne_prime(2) { True }
multi is_mersenne_prime(Int $p) {
my $m_p = 2 ** $p - 1;
Line 2,940 ⟶ 3,295:
}
 
.say for (2,3,5,7 … *).hyper(:8degree).grep( *.is-prime ).map: { next unless .&is_mersenne_prime; "M$_" };</langsyntaxhighlight>
{{out|On my system}}
Letting it run for about a minute...
Line 2,975 ⟶ 3,330:
REXX won't have a problem with the large number of digits involved, but since it's an interpreted language,
<br>such massive number crunching isn't conducive in searching for large primes.
<langsyntaxhighlight lang="rexx">/*REXX pgm uses the Lucas─Lehmer primality test for prime powers of 2 (Mersenne primes)*/
@.=0; @.2=1; @.3=1; @.5=1; @.7=1; @.11=1; @.13=1 /*a partial list of some low primes. */
!.=@.; !.0=1; !.2=1; !.4=1; !.5=1; !.6=1; !.8=1 /*#'s with these last digs aren't prime*/
Line 3,031 ⟶ 3,386:
return 'M'? /*return "modified" # (Mersenne index).*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
s: if arg(1)==1 then return arg(3); return word(arg(2) 's', 1) /*simple pluralizer*/</langsyntaxhighlight>
{{out|output|text=&nbsp; when the following is used for input: &nbsp; &nbsp; <tt> 10000 </tt>}}
<pre>
Line 3,060 ⟶ 3,415:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
see "Mersenne Primes :" + nl
for p = 2 to 18
Line 3,077 ⟶ 3,432:
next
return (sn=0)
</syntaxhighlight>
</lang>
 
=={{header|RPL}}==
===RPL HP-50 series===
<lang RPL>
<syntaxhighlight lang="rpl">
%%HP: T(3)A(R)F(.); ; ASCII transfer header
\<< DUP LN DUP \pi * 4 SWAP / 1 + UNROT / * IP 2 { 2 } ROT 2 SWAP ; input n; n := Int(n/ln(n)*(1 + 4/(pi*ln(n)))), p:=2; (n ~ number of primes less then n, pi used here only as a convenience), 2 is assumed to be the 1st elemente in the list
Line 3,088 ⟶ 3,444:
NEXT NIP ; next i;
\>>
</syntaxhighlight>
</lang>
{{out}}
<pre>Outputs for arguments 130, 607 and 2281, respectively:
Line 3,098 ⟶ 3,454:
These take respectively 1m 22s on the real HP 50g, 4m 29s and 10h 29m 23s on the emulator (Debug4 running on PC under WinXP, Intel(R) Core(TM) Duo CPU T2350 @ 1.86GHz).
</pre>
===RPL HP-28 series===
Unlike RPL implemented on HP-50 series, the first version of the language does not feature big integers, modular arithmetic operators, prime number test functions, nor even modulo operator for unsigned integers.
Let's build them all...
{{works with|Halcyon Calc|4.2.7}}
{| class="wikitable"
! RPL code
! Comment
|-
|
'''IF''' { #1 #2 #3 #5 } OVER POS '''THEN''' #1 ≠
'''ELSE IF''' # 1d DUP2 AND ≠ OVER 3 DUP2 / * == OR
'''THEN''' DROP 0
'''ELSE''' DUP B→R √ → divm
≪ 1 SF 4
5 divm '''FOR''' n
'''IF''' OVER n DUP2 / * ==
'''THEN''' 1 CF divm 'n' STO '''END'''
6 SWAP - DUP '''STEP'''
DROP2 1 FS?
≫ '''END END'''
≫ '<span style="color:blue">bPRIM?</span>' STO
≪ → m
≪ #1
'''WHILE''' OVER #0 > '''REPEAT'''
IF OVER #1 AND #1 == '''THEN'''
3 PICK * m / LAST ROT * - '''END'''
SWAP SR SWAP
ROT DUP * m / LAST ROT * - ROT ROT
'''END'''
ROT ROT DROP2
≫ ≫ '<span style="color:blue">MODXP</span>' STO
≪ 2 OVER ^ R→B 1 - → mp
≪ #4
3 ROT '''FOR''' n
#2 mp <span style="color:blue">MODXP</span>
'''IF''' DUP #2 < '''THEN''' mp + '''END''' #2 -
'''NEXT'''
#0 ==
≫ ≫ '<span style="color:blue">MSNP?</span>' STO
≪ { 2 } 3 32 '''FOR''' j
'''IF''' j R→B <span style="color:blue">bPRIM?</span>
'''THEN IF''' j <span style="color:blue">MNSP?</span> '''THEN''' j + '''END END'''
'''NEXT'''
≫ '<span style="color:blue">TASK</span>' STO
|
<span style="color:blue">bPRIM?</span> ''( #a → boolean )''
return 1 if a is 2, 3 or 5 and 0 if a is 1
if 2 or 3 divides a
return 0
else store sqrt(a)
d = 4 ; flag 1 set while presumed prime
for n=5 to sqrt(a)
if d divides a
prepare loop exit
d = 6-d ; n += d
clean stack, return result
<span style="color:blue">MODXP</span> ''( #base #exp #m → #mod(base^exp,m) )''
result = 1;
while (exp > 0) {
if ((exp & 1) > 0)
result = (result * base) % m;
exp >>= 1;
base = (base * base) % m;
}
clean stack, return result
<span style="color:blue">MNSP?</span> ''( p → boolean )''
s0 = 4
loop p-2 times
r = mod(s(n-1)^2 mod Mp
s(n) = (r - 2) mod Mp
return 1 if s(p-2)=0 mod Mp
|}
{{out}}
<pre>
1: { 2 3 5 7 13 17 19 31 }
</pre>
Runs in 48 seconds on a standard HP-28S.
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">def is_prime ( p )
return true if p == 2
return false if p <= 1 || p.even?
Line 3,132 ⟶ 3,582:
break if count >= upb_count
end
puts</langsyntaxhighlight>
 
{{out}}
Line 3,139 ⟶ 3,589:
 
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">
 
extern crate rug;
Line 3,194 ⟶ 3,644:
}
}
</syntaxhighlight>
</lang>
with Intel(R) Core(TM) i7-5500U CPU @ 2.40GHz :
Less than 8,6 seconds to get the Mersenne primes up to 11213
Line 3,231 ⟶ 3,681:
{{libheader|Scala}}
In accordance with definition of Mersenne primes it could only be a Mersenne number with prime exponent.
<langsyntaxhighlight Scalalang="scala">object LLT extends App {
import Stream._
 
Line 3,251 ⟶ 3,701:
}
println("That's All Folks!")
}</langsyntaxhighlight>
{{out}} After approx 20 minutes (2.10 GHz dual core)
<pre style="height: 30ex; overflow: scroll">Finding Mersenne primes in M[2..9999]
Line 3,279 ⟶ 3,729:
 
=={{header|Scheme}}==
<langsyntaxhighlight lang="scheme">;;;The heart of the algorithm
(define (S n)
(let ((m (- (expt 2 n) 1)))
Line 3,311 ⟶ 3,761:
(display "M") (display p) (display " ")
(loop (- i 1) (next-prime p)))
(loop i (next-prime p)))))</langsyntaxhighlight>
 
M2 M3 M5 M7 M13...
 
=={{header|Scilab}}==
<syntaxhighlight lang="text"> iexpmax=30
n=1
for iexp=2:iexpmax
Line 3,325 ⟶ 3,775:
end
if s==0 then printf("M%d ",iexp); end
end</langsyntaxhighlight>
{{out}}
<pre>M2 M3 M5 M7 M13 M17 M19</pre>
Line 3,332 ⟶ 3,782:
To get maximum speed the program should be [http://seed7.sourceforge.net/scrshots/comp.htm compiled] with -O2.
 
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
include "bigint.s7i";
Line 3,385 ⟶ 3,835:
end while;
writeln;
end func;</langsyntaxhighlight>
 
Original source: [http://seed7.sourceforge.net/algorith/math.htm#lucasLehmerTest lucasLehmerTest],
Line 3,398 ⟶ 3,848:
=={{header|Sidef}}==
{{trans|Raku}}
<langsyntaxhighlight lang="ruby">func is_mersenne_prime(p) {
return true if (p == 2)
var s = 4
Line 3,410 ⟶ 3,860:
say "M#{n}"
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 3,439 ⟶ 3,889:
Uses a sieve of Eratosthenes.
 
<syntaxhighlight lang="swift">import BigInt // add package attaswift/BigInt from Github
<lang swift>func lucasLehmer(_ p: Int) -> Bool {
import Darwin
let m = BigInt(2).power(p) - 1
var s = BigInt(4)
 
func Eratosthenes(upTo: Int) -> [Int] {
for _ in 0..<p-2 {
s = ((s * s) - 2) % m
let maxroot = Int(sqrt(Double(upTo)))
}
 
var isprime = [Bool](repeating: true, count: upTo+1 )
return s == 0
for i in 2...maxroot {
if isprime[i] {
for k in stride(from: upTo/i, through: i, by: -1) {
if isprime[k] {
isprime[i*k] = false }
}
}
}
var result = [Int]()
for i in 2...upTo {
if isprime[i] {
result.append( i)
}
}
return result
}
 
func lucasLehmer(_ p: Int) -> Bool {
for prime in Eratosthenes(upTo: 70) where lucasLehmer(prime) {
let m = Int(powBigInt(2, Double).power(prime))p) - 1
var s = BigInt(4)
for _ in 0..<p-2 {
s = ((s * s) - 2) % m
}
return s == 0
}
 
for print("2^\(prime) -in 1Eratosthenes(upTo: = \(m128) iswhere lucasLehmer(prime") {
let mprime = BigInt(2).power(prime) - 1
}</lang>
print("2^\(prime) - 1 = \(mprime) is prime")
}</syntaxhighlight>
 
{{out}}
Line 3,464 ⟶ 3,938:
2^19 - 1 = 524287 is prime
2^31 - 1 = 2147483647 is prime
2^61 - 1 = 2305843009213693951 is prime</pre>
2^89 - 1 = 618970019642690137449562111 is prime
2^107 - 1 = 162259276829213363391578010288127 is prime
2^127 - 1 = 170141183460469231731687303715884105727 is prime</pre>
 
=={{header|Tcl}}==
{{trans|Pop11}}
<langsyntaxhighlight Tcllang="tcl">proc main argv {
set n 0
set t [clock seconds]
Line 3,502 ⟶ 3,979:
}
 
main 33218</langsyntaxhighlight>
{{Out}}
The program was still running, but as the next Mersenne prime is 19937
Line 3,531 ⟶ 4,008:
 
=={{header|TI-83 BASIC}}==
<langsyntaxhighlight lang="ti83b">19→M
1→N
For(E,2,M)
Line 3,545 ⟶ 4,022:
Then:Disp E
End
End</langsyntaxhighlight>
{{out}}
<pre>2
Line 3,557 ⟶ 4,034:
=={{header|uBasic/4tH}}==
{{Trans|VBScript}}
<syntaxhighlight lang="text">m = 15
n = 1
For j = 2 To m
Line 3,570 ⟶ 4,047:
Next i
If s = 0 Then Print "M";j
Next</langsyntaxhighlight>
 
=={{header|VBScript}}==
<langsyntaxhighlight lang="vb">iexpmax = 15
n=1
out=""
Line 3,590 ⟶ 4,067:
End If
Next
Wscript.echo out</langsyntaxhighlight>
{{Out}}
<pre>M2 M3 M5 M7 M13 </pre>
Line 3,596 ⟶ 4,073:
=={{header|Visual Basic .NET}}==
{{works with|Visual Basic .NET|2011}}
<langsyntaxhighlight lang="vbnet">Public Class LucasLehmer
Private Sub btnGo_Click(sender As Object, e As EventArgs) Handles btnGo.Click
Const iexpmax = 31
Line 3,618 ⟶ 4,095:
Next iexp
End Sub
End Class</langsyntaxhighlight>
{{Out}}
<pre>
M2 M3 M5 M7 M13 M17 M19 M31 </pre>
 
=={{header|V (Vlang)}}==
{{incomplete|Vlang|This seems to hang, something is wrong in the algo.}}
{{trans|go}}
<syntaxhighlight lang="go">import math.big
const (
primes = [u32(3), 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47,
53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127]
mersennes = [u32(521), 607, 1279, 2203, 2281, 3217, 4253, 4423, 9689,
9941, 11213, 19937, 21701, 23209, 44497, 86243, 110503, 132049, 216091,
756839, 859433, 1257787, 1398269, 2976221, 3021377, 6972593, 13466917,
20996011, 24036583]
)
fn main() {
ll_test(primes)
println('')
ll_test(mersennes)
}
fn ll_test(ps []u32) {
mut s, mut m := big.zero_int, big.zero_int
one := big.one_int
two := big.two_int
for p in ps {
m = one.lshift(p) - one
s= big.integer_from_int(4)
for i := u32(2); i < p; i++ {
s = (s*s - two)%m
}
if s.bit_len() == 0 {
print("M$p ")
}
}
}</syntaxhighlight>
{{out}}
<pre>
M3 M5 M7 M13 M17 M19 M31 ...
</pre>
 
=={{header|Wren}}==
===Wren-CLI (BigInt)===
{{libheader|Wren-big}}
{{libheader|wren-math}}
This follows the lines of my Kotlin entry but uses a table to quicken up the checking of the larger numbers. Despite this, it still takes just over 3 minutes to reach M4423. Surprisingly, using ''modPow'' rather than the simple ''%'' operator is even slower.
<langsyntaxhighlight ecmascriptlang="wren">1importimport "./big" for BigInt
import "./math" for Int
import "io" for Stdout
 
Line 3,663 ⟶ 4,181:
}
}
System.print("\nTook %(System.clock - start) seconds.")</langsyntaxhighlight>
 
{{out}}
Line 3,671 ⟶ 4,189:
Took 181.271083 seconds.
</pre>
===Embedded (GMP)===
{{libheader|Wren-gmp}}
Same approach as the CLI version but now uses GMP. Far quicker, of course, as we can now check up to M110503 in less time than before.
<syntaxhighlight lang="wren">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.")</syntaxhighlight>
 
{{out}}
<pre>
M3 M5 M7 M13 M17 M19 M31 M61 M89 M107 M127 M521 M607 M1279 M2203 M2281 M3217 M4253 M4423 M9689 M9941 M11213 M19937 M21701 M23209 M44497 M86243 M110503
 
Took 127.317323 seconds.
</pre>
 
=={{header|Yabasic}}==
<syntaxhighlight lang="yabasic">print "Mersenne Primes :"
for p = 2 to 20
if lucasLehmer(p) print "M",p
next p
end
 
sub lucasLehmer (p)
mp = (2 ^ p) - 1
sn = 4
for i = 2 to p-1
sn = (sn ^ 2) - 2
sn = sn - (mp * floor(sn / mp))
next
return sn = 0
end sub</syntaxhighlight>
 
=={{header|Zig}}==
Zig supports 128 bit integer types natively, which means it's possible to find all Mersenne primes up to M127. (requires writing a modmul() routine to compute (a * b) % m for 128 bit integers without overflow.)
<syntaxhighlight lang="zig">
<lang Zig>
const std = @import("std");
const stdout = std.io.getStdOut().outStream();
Line 3,725 ⟶ 4,307:
return r;
}
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 3,733 ⟶ 4,315:
=={{header|zkl}}==
Using [[Extensible prime generator#zkl]] and the GMP library.
<langsyntaxhighlight lang="zkl">var [const] BN=Import.lib("zklBigNum"); // lib GMP
primes:=Utils.Generator(Import("sieve").postponed_sieve);
fcn isMersennePrime(p){
Line 3,740 ⟶ 4,322:
s:=BN(4); do(p-2){ s.mul(s).sub(2).mod(mp) } // the % REALLY cuts down on mem usage
return(s==0);
}</langsyntaxhighlight>
Calculating S(n) is done in place (overwriting the value in the BigInt with the result); this really cuts down on memory usage.
<langsyntaxhighlight lang="zkl">mersennePrimes:=primes.tweak(fcn(p){ isMersennePrime(p) and p or Void.Skip });
println("Mersenne primes:");
foreach mp in (mersennePrimes) { print(" M",mp); }</langsyntaxhighlight>
This will "continuously" spew out Mersenne Primes.
 
Line 3,757 ⟶ 4,339:
 
Using five threads:
<langsyntaxhighlight lang="zkl">ps,mpOut := Thread.Pipe(),Thread.Pipe(); // how the threads will communicate
fcn(ps){ // a thread to generate primes, sleeps most of the time
Utils.Generator(Import("sieve").postponed_sieve).pump(ps)
Line 3,766 ⟶ 4,348:
}
println("Mersenne primes:");
foreach mp in (mpOut) { print(" M",mp); }</langsyntaxhighlight>
 
 
885

edits