Miller–Rabin primality test: Difference between revisions

m
syntax highlighting fixup automation
(→‎{{header|C}}: adding a 64-bit deterministic version of the Miller-Rabin primality test.)
m (syntax highlighting fixup automation)
Line 29:
{{trans|D}}
 
<langsyntaxhighlight lang="11l">F isProbablePrime(n, k = 10)
I n < 2 | n % 2 == 0
R n == 2
Line 57:
R 1B
 
print((2..29).filter(x -> isProbablePrime(x)))</langsyntaxhighlight>
 
{{out}}
Line 77:
such as for the [[Carmichael 3 strong pseudoprimes]] the [[Extensible prime generator]], and the [[Emirp primes]].
 
<langsyntaxhighlight Adalang="ada">generic
type Number is range <>;
package Miller_Rabin is
Line 85:
function Is_Prime (N : Number; K : Positive := 10) return Result_Type;
 
end Miller_Rabin;</langsyntaxhighlight>
 
The implementation of that package is as follows:
 
<langsyntaxhighlight Adalang="ada">with Ada.Numerics.Discrete_Random;
 
package body Miller_Rabin is
Line 143:
end Is_Prime;
 
end Miller_Rabin;</langsyntaxhighlight>
 
Finally, the program itself:
 
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO, Miller_Rabin;
 
procedure Mr_Tst is
Line 171:
Ada.Text_IO.Put ("Enter the count of loops: "); Pos_IO.Get (K);
Ada.Text_IO.Put_Line ("What is it? " & Result_Type'Image (Is_Prime(N, K)));
end MR_Tst;</langsyntaxhighlight>
 
{{out}}
Line 183:
Using the big integer implementation from a cryptographic library [https://github.com/cforler/Ada-Crypto-Library/].
 
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO, Crypto.Types.Big_Numbers, Ada.Numerics.Discrete_Random;
 
procedure Miller_Rabin is
Line 268:
Ada.Text_IO.Put_Line("Prime(" & S & ")=" & Boolean'Image(Is_Prime(+S, K)));
Ada.Text_IO.Put_Line("Prime(" & T & ")=" & Boolean'Image(Is_Prime(+T, K)));
end Miller_Rabin;</langsyntaxhighlight>
 
{{out}}
Line 276:
Using the built-in Miller-Rabin test from the same library:
 
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO, Crypto.Types.Big_Numbers, Ada.Numerics.Discrete_Random;
 
procedure Miller_Rabin is
Line 301:
Ada.Text_IO.Put_Line("Prime(" & T & ")="
& Boolean'Image (LN.Mod_Utils.Passed_Miller_Rabin_Test(+T, K)));
end Miller_Rabin;</langsyntaxhighlight>
 
The output is the same.
Line 310:
{{works with|ALGOL 68G|Any - tested with release mk15-0.8b.fc9.i386}}
<!-- {{does not work with|ELLA ALGOL 68|Any (with appropriate job cards AND formatted transput statements removed) - tested with release 1.8.8d.fc9.i386 - ELLA has no FORMATted transput, also it generates a call to undefined C LONG externals }} -->
<langsyntaxhighlight lang="algol68">MODE LINT=LONG INT;
MODE LOOPINT = INT;
 
Line 347:
print((" ",whole(i,0)))
FI
OD</langsyntaxhighlight>
{{out}}
<pre>
Line 355:
=={{header|AutoHotkey}}==
ahk forum: [http://www.autohotkey.com/forum/post-276712.html#276712 discussion]
<langsyntaxhighlight AutoHotkeylang="autohotkey">MsgBox % MillerRabin(999983,10) ; 1
MsgBox % MillerRabin(999809,10) ; 1
MsgBox % MillerRabin(999727,10) ; 1
Line 395:
y := i&1 ? mod(y*z,m) : y, z := mod(z*z,m), i >>= 1
Return y
}</langsyntaxhighlight>
 
=={{header|bc}}==
Line 401:
{{works with|OpenBSD bc}}
(A previous version worked with [[GNU bc]].)
<langsyntaxhighlight lang="bc">seed = 1 /* seed of the random number generator */
scale = 0
 
Line 468:
}
}
quit</langsyntaxhighlight>
 
=={{header|BQN}}==
Line 474:
The function <code>IsPrime</code> in bqn-libs [https://github.com/mlochbaum/bqn-libs/blob/master/primes.bqn primes.bqn] uses deterministic Miller-Rabin to test primality when trial division fails. The following function, derived from that library, selects witnesses at random. The left argument is the number of witnesses to test, with default 10.
 
<langsyntaxhighlight lang="bqn">_modMul ← { n _𝕣: n|× }
MillerRabin ← { 𝕊n: 10𝕊n ; iter 𝕊 n: !2|n
# n = 1 + d×2⋆s
Line 493:
C ← { 𝕊a: s MR a Pow d } # Is composite
{0:1; C •rand.Range⌾(-⟜2) n ? 0; 𝕊𝕩-1} iter
}</langsyntaxhighlight>
 
The simple definition of <code>_modMul</code> is inaccurate when intermediate results fall outside the exact integer range (this can happen for inputs around <code>2⋆26</code>). When replaced with the definition below, <code>MillerRabin</code> remains accurate for all inputs, as floating point can't represent odd numbers outside of integer range.
 
<langsyntaxhighlight lang="bqn"># Compute n|𝕨×𝕩 in high precision
_modMul ← { n _𝕣:
# Split each argument into two 26-bit numbers, with the remaining
Line 506:
Mul ← × (⊣ ⋈ -⊸(+´)) ·⥊×⌜○Split
((n×<⟜0)⊸+ -⟜n+⊢)´ n | Mul
}</langsyntaxhighlight>
 
{{out}}
 
<langsyntaxhighlight lang="bqn"> MillerRabin 15485867
1
MillerRabin¨⊸/ 101+2×↕10
⟨ 101 103 107 109 113 ⟩</langsyntaxhighlight>
 
=={{header|Bracmat}}==
{{trans|bc}}
<langsyntaxhighlight lang="bracmat">( 1:?seed
& ( rand
=
Line 586:
& !primes:? [-11 ?last
& out$!last
);</langsyntaxhighlight>
{{out}}
<pre>937 941 947 953 967 971 977 983 991 997</pre>
Line 593:
{{libheader|GMP}}
'''miller-rabin.h'''
<langsyntaxhighlight lang="c">#ifndef _MILLER_RABIN_H_
#define _MILLER_RABIN_H
#include <gmp.h>
bool miller_rabin_test(mpz_t n, int j);
#endif</langsyntaxhighlight>
'''miller-rabin.c'''
{{trans|Fortran}}
For <code>decompose</code> (and header <tt>primedecompose.h</tt>),
see [[Prime decomposition#C|Prime decomposition]].
<langsyntaxhighlight lang="c">#include <stdbool.h>
#include <gmp.h>
#include "primedecompose.h"
Line 664:
gmp_randclear(rs);
return res;
}</langsyntaxhighlight>
'''Testing'''
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
Line 694:
mpz_clear(num);
return EXIT_SUCCESS;
}</langsyntaxhighlight>
 
 
===Deterministic up to 341,550,071,728,321===
<langsyntaxhighlight lang="c">// calcul a^n%mod
size_t power(size_t a, size_t n, size_t mod)
{
Line 769:
return witness(n, s, d, 2) && witness(n, s, d, 3) && witness(n, s, d, 5) && witness(n, s, d, 7) && witness(n, s, d, 11) && witness(n, s, d, 13);
return witness(n, s, d, 2) && witness(n, s, d, 3) && witness(n, s, d, 5) && witness(n, s, d, 7) && witness(n, s, d, 11) && witness(n, s, d, 13) && witness(n, s, d, 17);
}</langsyntaxhighlight>
Inspiration from http://stackoverflow.com/questions/4424374/determining-if-a-number-is-prime
 
===Other version===
It should be a 64-bit deterministic version of the Miller-Rabin primality test.
<syntaxhighlight lang="c">
<lang c>
typedef unsigned long long int ulong;
 
Line 813:
}
 
</syntaxhighlight>
</lang>
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">public static class RabinMiller
{
public static bool IsPrime(int n, int k)
Line 842:
return true;
}
}</langsyntaxhighlight>
[https://stackoverflow.com/questions/7860802/miller-rabin-primality-test] Corrections made 6/21/2017
<br><br>
<langsyntaxhighlight lang="csharp">// Miller-Rabin primality test as an extension method on the BigInteger type.
// Based on the Ruby implementation on this page.
public static class BigIntegerExtensions
Line 902:
return true;
}
}</langsyntaxhighlight>
 
=={{header|Clojure}}==
===Random Approach===
<langsyntaxhighlight lang="lisp">(ns test-p.core
(:require [clojure.math.numeric-tower :as math])
(:require [clojure.set :as set]))
Line 980:
(println "Is Prime?" 743808006803554439230129854961492699151386107534013432918073439524138264842370630061369715394739134090922937332590384720397133335969549256322620979036686633213903952966175107096769180017646161851573147596390153
(random-test 743808006803554439230129854961492699151386107534013432918073439524138264842370630061369715394739134090922937332590384720397133335969549256322620979036686633213903952966175107096769180017646161851573147596390153))
</syntaxhighlight>
</lang>
{{Output}}
<pre>
Line 991:
</pre>
===Deterministic Approach===
<langsyntaxhighlight lang="lisp">(ns test-p.core
(:require [clojure.math.numeric-tower :as math]))
 
Line 1,073:
(println "Is Prime?" 743808006803554439230129854961492699151386107534013432918073439524138264842370630061369715394739134090922937332590384720397133335969549256322620979036686633213903952966175107096769180017646161851573147596390153
(deterministic-test 743808006803554439230129854961492699151386107534013432918073439524138264842370630061369715394739134090922937332590384720397133335969549256322620979036686633213903952966175107096769180017646161851573147596390153))
</syntaxhighlight>
</lang>
{{Output}}
<pre>
Line 1,089:
=={{header|Commodore BASIC}}==
This displays a minimum probability of primality = 1-1/4<sup>k</sup>, as the fraction of "strong liars" approaches 1/4 in the limit.
<langsyntaxhighlight lang="basic">100 PRINT CHR$(147); CHR$(18); "**** MILLER-RABIN PRIMALITY TEST ****": PRINT
110 INPUT "NUMBER TO TEST"; N$
120 N = VAL(N$): IF N < 2 THEN 110
Line 1,118:
370 P = P * (1 - 1 / (4 * K))
380 IF P THEN PRINT "PROBABLY PRIME ( P >="; P; ")": END
390 PRINT "COMPOSITE."</langsyntaxhighlight>
{{Out}}
Sample runs.
Line 1,142:
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">(defun factor-out (number divisor)
"Return two values R and E such that NUMBER = DIVISOR^E * R,
and R is not divisible by DIVISOR."
Line 1,184:
thereis (= y (- n 1)))))))
(loop repeat k
always (strong-liar? (random-in-range 2 (- n 2)))))))))</langsyntaxhighlight>
<pre>
CL-USER> (last (loop for i from 1 to 1000
Line 1,196:
=== Standard non-deterministic M-R test ===
 
<langsyntaxhighlight lang="ruby">require "big"
 
module Primes
Line 1,235:
 
puts 341521.prime?(20) # => true
puts 341531.prime? # => false</langsyntaxhighlight>
 
=== Deterministic M-R test ===
Line 1,241:
It is a direct translation of the Ruby version for arbitrary sized integers.
It is deterministic for all integers < 3_317_044_064_679_887_385_961_981.
<langsyntaxhighlight lang="ruby"># For crystal >= 0.31.x, compile without overflow check, as either
# crystal build miller-rabin.cr -Ddisable_overflow --release
# crystal build -Ddisable_overflow miller-rabin.cr --release
Line 1,384:
n = "94366396730334173383107353049414959521528815310548187030165936229578960209523421808912459795329035203510284576187160076386643700441216547732914250578934261891510827140267043592007225160798348913639472564715055445201512461359359488795427875530231001298552452230535485049737222714000227878890892901228389026881".to_big_i
print "\n number = #{n} is prime? "; print " in ", tm{ print n.primemr? }, " secs"
puts</langsyntaxhighlight>
 
=={{header|D}}==
{{trans|Ruby}}
<langsyntaxhighlight lang="d">import std.random;
 
bool isProbablePrime(in ulong n, in uint k=10) /*nothrow*/ @safe /*@nogc*/ {
Line 1,437:
 
iota(2, 30).filter!isProbablePrime.writeln;
}</langsyntaxhighlight>
{{out}}
<pre>[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]</pre>
 
=={{header|E}}==
<langsyntaxhighlight lang="e">def millerRabinPrimalityTest(n :(int > 0), k :int, random) :boolean {
if (n <=> 2 || n <=> 3) { return true }
if (n <=> 1 || n %% 2 <=> 0) { return false }
Line 1,464:
}
return true
}</langsyntaxhighlight>
<langsyntaxhighlight lang="e">for i ? (millerRabinPrimalityTest(i, 1, entropy)) in 4..1000 {
print(i, " ")
}
println()</langsyntaxhighlight>
 
=={{header|EchoLisp}}==
EchoLisp natively implement the '''prime?''' function = Miller-Rabin tests for big integers. The definition is as follows :
<langsyntaxhighlight lang="scheme">
(lib 'bigint)
 
Line 1,512:
(prime? (1+ (factorial 100))) ;; native
→ #f
</syntaxhighlight>
</lang>
 
=={{header|Elixir}}==
<langsyntaxhighlight lang="elixir">
defmodule Prime do
use Application
Line 1,565:
end
end
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,582:
</pre>
The following larger examples all produce true:
<langsyntaxhighlight lang="elixir">
miller_rabin?( 94366396730334173383107353049414959521528815310548187030165936229578960209523421808912459795329035203510284576187160076386643700441216547732914250578934261891510827140267043592007225160798348913639472564715055445201512461359359488795427875530231001298552452230535485049737222714000227878890892901228389026881, 1000 )
miller_rabin?( 138028649176899647846076023812164793645371887571371559091892986639999096471811910222267538577825033963552683101137782650479906670021895135954212738694784814783986671046107023185842481502719762055887490765764329237651328922972514308635045190654896041748716218441926626988737664133219271115413563418353821396401, 1000 )
Line 1,590:
miller_rabin?( 153410708946188157980279532372610756837706984448408515364579602515073276538040155990230789600191915021209039203172105094957316552912585741177975853552299222501069267567888742458519569317286299134843250075228359900070009684517875782331709619287588451883575354340318132216817231993558066067063143257425853927599, 1000 )
miller_rabin?( 103130593592068072608023213244858971741946977638988649427937324034014356815504971087381663169829571046157738503075005527471064224791270584831779395959349442093395294980019731027051356344056416276026592333932610954020105156667883269888206386119513058400355612571198438511950152690467372712488391425876725831041, 1000 )
</syntaxhighlight>
</lang>
 
=={{header|Erlang}}==
Line 1,597:
to permit use of integers of arbitrary precision.
 
<langsyntaxhighlight lang="erlang">
-module(miller_rabin).
 
Line 1,687:
Acc;
power(B, E, Acc) ->
power(B, E - 1, B * Acc).</langsyntaxhighlight>
 
The above code optimised as follows:
Line 1,695:
53s to 11s on a quad-core 17 with 16 GB ram. The performance
gain from the improved exponentiation was not evaluated.
<langsyntaxhighlight lang="erlang">
%%% @author Tony Wallace <tony@resurrection>
%%% @copyright (C) 2021, Tony Wallace
Line 1,879:
.
 
</syntaxhighlight>
</lang>
 
=={{header|F_Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">
// Miller primality test for n<3317044064679887385961981. Nigel Galloway: April 1st., 2021
let a=[(2047I,[2I]);(1373653I,[2I;3I]);(9080191I,[31I;73I]);(25326001I,[2I;3I;5I]);(3215031751I,[2I;3I;5I;7I]);(4759123141I,[2I;7I;61I]);(1122004669633I,[2I;13I;23I;1662803I]);
Line 1,894:
 
printfn "%A %A" (mrP 2147483647I)(mrP 844674407370955389I)
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,902:
Forth only supports native ints (e.g. 64 bits on most modern machines), so this version uses a set of bases that is known to be deterministic for 64 bit integers (and possibly greater). Prior to the Miller Rabin check, the "prime?" word checks for divisibility by some small primes.
 
<syntaxhighlight lang="forth">
<lang Forth>
\ modular multiplication and exponentiation
\
Line 1,991:
then
then ;
</syntaxhighlight>
</lang>
{{Out}}
Test on some Fermat numbers and some Mersenne numbers
Line 2,006:
{{works with|Fortran|95}}
For the module ''PrimeDecompose'', see [[Prime decomposition#Fortran|Prime decomposition]].
<langsyntaxhighlight lang="fortran">
module Miller_Rabin
use PrimeDecompose
Line 2,062:
end function miller_rabin_test
 
end module Miller_Rabin</langsyntaxhighlight>
'''Testing'''
<langsyntaxhighlight lang="fortran">program TestMiller
use Miller_Rabin
implicit none
Line 2,087:
end subroutine do_test
end program TestMiller</langsyntaxhighlight>
''Possible improvements'': create bindings to the [[:Category:GMP|GMP library]], change <code>integer(huge)</code> into something like <code>type(huge_integer)</code>, write a lots of interfaces to allow to use big nums naturally (so that the code will be unchanged, except for the changes said above)
 
===With some avoidance of overflow===
Integer overflow is a severe risk, and even 64-bit integers won't get you far when the formulae are translated as <code>MOD(A**D,N)</code> - what is needed is a method for raising to a power that incorporates the modulus along the way. There is no library routine for that, so... <langsyntaxhighlight Fortranlang="fortran"> MODULE MRTEST !Try the Miller-Rabin primality test.
CONTAINS !Working only with in-built integers.
LOGICAL FUNCTION MRPRIME(N,TRIALS) !Could N be a prime number?
Line 2,167:
END DO
 
END</langsyntaxhighlight>
Output:
<pre>
Line 2,285:
Using the task pseudo code
===Up to 2^63-1===
<langsyntaxhighlight lang="freebasic">' version 29-11-2016
' compile with: fbc -s console
 
Line 2,385:
Print : Print "hit any key to end program"
Sleep
End</langsyntaxhighlight>
{{out}}
<pre>9223372036854774893 9223372036854774917 9223372036854774937
Line 2,399:
===Using Big Integer library===
{{libheader|GMP}}
<langsyntaxhighlight lang="freebasic">' version 05-04-2017
' compile with: fbc -s console
 
Line 2,513:
Print : Print "hit any key to end program"
Sleep
End</langsyntaxhighlight>
{{out}}
<pre> 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
Line 2,539:
Direct implementation of the task algorithm.
 
<langsyntaxhighlight lang="funl">import util.rnd
 
def isProbablyPrimeMillerRabin( n, k ) =
Line 2,568:
for i <- 3..100
if isProbablyPrimeMillerRabin( i, 5 )
println( i )</langsyntaxhighlight>
 
{{out}}
Line 2,606:
 
The main difference between this algorithm and the pseudocode in the task description is that k numbers are not chosen randomly, but instead are the three numbers 2, 7, and 61. These numbers provide a deterministic primality test up to 2^32.
<langsyntaxhighlight lang="go">package main
 
import "log"
Line 2,671:
}
return true
}</langsyntaxhighlight>
 
=={{header|Haskell}}==
Line 2,680:
* Original Rosetta code has been simplified to be easier to follow
Another Miller Rabin test can be found in D. Amos's Haskell for Math module [http://www.polyomino.f2s.com/david/haskell/numbertheory.html Primes.hs]
<langsyntaxhighlight Haskelllang="haskell">module Primes where
 
import System.Random
Line 2,724:
g i b y | even i = g (i `quot` 2) (b*b `rem` m) y
| otherwise = f (i-1) b (b*y `rem` m)
</syntaxhighlight>
</lang>
 
{{out|Sample output}}
Line 2,741:
* The code above likely has better complexity.
 
<syntaxhighlight lang="haskell">
<lang Haskell>
import Control.Monad (liftM)
import Data.Bits (Bits, testBit, shiftR)
Line 2,797:
[n,k] <- liftM (map (\x -> read x :: Integer) . words) getLine
print $ isPrime n k
</syntaxhighlight>
</lang>
 
 
Line 2,818:
 
The following runs in both languages:
<langsyntaxhighlight lang="unicon">procedure main(A)
every n := !A do write(n," is ",(mrp(n,5),"probably prime")|"composite")
end
Line 2,850:
}
return [s,d]
end</langsyntaxhighlight>
 
Sample run:
Line 2,870:
=={{header|Java}}==
The Miller-Rabin primality test is part of the standard library (java.math.BigInteger)
<langsyntaxhighlight lang="java">import java.math.BigInteger;
 
public class MillerRabinPrimalityTest {
Line 2,878:
System.out.println(n.toString() + " is " + (n.isProbablePrime(certainty) ? "probably prime" : "composite"));
}
}</langsyntaxhighlight>
{{out|Sample output}}
<pre>java MillerRabinPrimalityTest 123456791234567891234567 1000000
Line 2,884:
 
This is a translation of the [http://rosettacode.org/wiki/Miller-Rabin_primality_test#Python:_Proved_correct_up_to_large_N Python solution] for a deterministic test for n < 341,550,071,728,321:
<langsyntaxhighlight lang="java">import java.math.BigInteger;
 
public class Prime {
Line 2,963:
}
}
</syntaxhighlight>
</lang>
 
=={{header|JavaScript}}==
For the return values of this function, <code>true</code> means "probably prime" and <code>false</code> means "definitely composite."
 
<langsyntaxhighlight JavaScriptlang="javascript">function probablyPrime(n) {
if (n === 2 || n === 3) return true
if (n % 2 === 0 || n < 2) return false
Line 2,991:
}
return false
}</langsyntaxhighlight>
 
=={{header|Julia}}==
The built-in <code>isprime</code> function uses the Miller-Rabin primality test. Here is the implementation of <code>isprime</code> from the Julia standard library (Julia version 0.2):
<langsyntaxhighlight lang="julia">
witnesses(n::Union(Uint8,Int8,Uint16,Int16)) = (2,3)
witnesses(n::Union(Uint32,Int32)) = n < 1373653 ? (2,3) : (2,7,61)
Line 3,023:
return true
end
</syntaxhighlight>
</lang>
 
=={{header|Kotlin}}==
Translating the pseudo-code directly rather than using the Java library method BigInteger.isProbablePrime(certainty):
<langsyntaxhighlight lang="scala">// version 1.1.2
 
import java.math.BigInteger
Line 3,079:
for (bi in bia)
println("$bi is ${if (isProbablyPrime(bi, k)) "probably prime" else "composite"}")
}</langsyntaxhighlight>
 
{{out}}
Line 3,091:
 
=={{header|Liberty BASIC}}==
<syntaxhighlight lang="lb">
<lang lb>
DIM mersenne(11)
mersenne(1)=7
Line 3,382:
 
End Function
</syntaxhighlight>
</lang>
 
=={{header|Lua}}==
Line 3,388:
This implementation of the Miller-Rabin probabilistic primality test is based on the treatment in Chapter 10 of "A Computational Introduction to Number Theory and Algebra" by Victor Shoup.
 
<langsyntaxhighlight lang="lua"> function MRIsPrime(n, k)
-- If n is prime, returns true (without fail).
-- If n is not prime, then returns false with probability ≥ 4^(-k), true otherwise.
Line 3,446:
end
return z
end </langsyntaxhighlight>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">MillerRabin[n_,k_]:=Module[{d=n-1,s=0,test=True},While[Mod[d,2]==0 ,d/=2 ;s++]
Do[
a=RandomInteger[{2,n-1}]; x=PowerMod[a,d,n];
Line 3,457:
];
,{k}];
Print[test] ]</langsyntaxhighlight>
{{out|Example output (not using the PrimeQ builtin)}}
<langsyntaxhighlight lang="mathematica">MillerRabin[17388,10]
->False</langsyntaxhighlight>
 
=={{header|Maxima}}==
 
<langsyntaxhighlight lang="maxima">/* Miller-Rabin algorithm is builtin, see function primep. Here is another implementation */
 
 
Line 3,510:
)
)
)$</langsyntaxhighlight>
 
=={{header|Mercury}}==
Line 3,531:
found with instructions for use in Github.
 
<syntaxhighlight lang="mercury">
<lang Mercury>
%----------------------------------------------------------------------%
:- module primality.
Line 3,751:
:- end_module test_is_prime.
 
</syntaxhighlight>
</lang>
 
=={{header|Nim}}==
Line 3,757:
===Deterministic approach limited to uint32 values.===
 
<langsyntaxhighlight lang="nim">
## Nim currently doesn't have a BigInt standard library
## so we translate the version from Go which uses a
Line 3,831:
assert isPrime(492366587u32)
assert isPrime(1645333507u32)
</syntaxhighlight>
</lang>
 
=== Correct M-R test implementation for using bases > input, deterministic for all integers < 2^64.===
 
<langsyntaxhighlight lang="nim">
 
# Compile as: $ nim c -d:release mrtest.nim
Line 3,977:
echo("\nnumber of primes < ",num, " are ", primes.len)
echo (epochTime()-te).formatFloat(ffDecimal, 6)
</syntaxhighlight>
</lang>
 
=={{Header|OCaml}}==
Line 3,983:
A direct translation of the wikipedia pseudocode (with <tt>get_rd</tt> helper function translated from <tt>split</tt> in the scheme implementation). This code uses the Zarith and Bigint (bignum) libraries.
 
<syntaxhighlight lang="ocaml">
<lang OCaml>
(* Translated from the wikipedia pseudo-code *)
let miller_rabin n ~iter:k =
Line 4,025:
in
loop 0 true
</syntaxhighlight>
</lang>
 
=={{header|Oz}}==
Line 4,032:
the Mercury and Prolog versions on this page.
 
<syntaxhighlight lang="oz">
<lang Oz>
%--------------------------------------------------------------------------%
% module: Primality
Line 4,138:
% end_module Primality
 
</syntaxhighlight>
</lang>
 
=={{header|PARI/GP}}==
===Built-in===
<langsyntaxhighlight lang="parigp">MR(n,k)=ispseudoprime(n,k);</langsyntaxhighlight>
===Custom===
<langsyntaxhighlight lang="parigp">sprp(n,b)={
my(s = valuation(n-1, 2), d = Mod(b, n)^(n >> s));
if (d == 1, return(1));
Line 4,159:
);
1
};</langsyntaxhighlight>
===Deterministic version===
A basic deterministic test can be obtained by an appeal to the ERH (as proposed by Gary Miller) and a result of Eric Bach (improving on Joseph Oesterlé). Calculations of Jan Feitsma can be used to speed calculations below 2<sup>64</sup> (by a factor of about 250).
<langsyntaxhighlight lang="parigp">A006945=[9, 2047, 1373653, 25326001, 3215031751, 2152302898747, 3474749660383, 341550071728321, 341550071728321, 3825123056546413051];
Miller(n)={
if (n%2 == 0, return(n == 2)); \\ Handle even numbers
Line 4,181:
1
)
};</langsyntaxhighlight>
 
=={{header|Perl}}==
 
===Custom===
<langsyntaxhighlight lang="perl">use bigint try => 'GMP';
 
sub is_prime {
Line 4,217:
}
 
print join ", ", grep { is_prime $_, 10 } (1 .. 1000);</langsyntaxhighlight>
 
===Modules===
{{libheader|ntheory}}
While normally one would use <tt>is_prob_prime</tt>, <tt>is_prime</tt>, or <tt>is_provable_prime</tt>, which will do a [[wp:Baillie--PSW_primality_test|BPSW test]] and possibly more, we can use just the Miller-Rabin test if desired. For large values we can use an object (e.g. bigint, Math::GMP, Math::Pari, etc.) or just a numeric string.
<langsyntaxhighlight lang="perl">use ntheory qw/is_strong_pseudoprime miller_rabin_random/;
sub is_prime_mr {
my $n = shift;
Line 4,231:
# Otherwise, perform a number of random base tests, and the result is a probable prime test.
return miller_rabin_random($n, 20);
}</langsyntaxhighlight>
Math::Primality also has this functionality, though its function takes only one base and requires the input number to be less than the base.
<langsyntaxhighlight lang="perl">use Math::Primality qw/is_strong_pseudoprime/;
sub is_prime_mr {
my $n = shift;
Line 4,242:
1;
}
for (1..100) { say if is_prime_mr($_) }</langsyntaxhighlight>
Math::Pari can be used in a fashion similar to the Pari/GP custom function. The builtin accessed using a second argument to <tt>ispseudoprime</tt> was added to a later version of Pari (the Perl module uses version 2.1.7) so is not accessible directly from Perl.
 
Line 4,250:
Native-types deterministic version, fails (false negative) at 94,910,107 on 32-bit [fully tested, ie from 1],
and at 4,295,041,217 on 64-bit [only tested from 4,290,000,000] - those limits have now been hard-coded below.
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">powermod</span><span style="color: #0000FF;">(</span><span style="color: #004080;">atom</span> <span style="color: #000000;">a</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">atom</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">atom</span> <span style="color: #000000;">m</span><span style="color: #0000FF;">)</span>
Line 4,318:
<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;">"%d is %s\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">tests</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">],{</span><span style="color: #008000;">"composite"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"prime"</span><span style="color: #0000FF;">}[</span><span style="color: #000000;">is_prime_mr</span><span style="color: #0000FF;">(</span><span style="color: #000000;">tests</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">])+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]})</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 4,335:
{{trans|Ruby}}
While desktop/Phix uses a thin wrapper to the builtin gmp routine, the following is also available and is used (after transpilation) in mpfr.js, renamed as mpz_prime:
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #000080;font-style:italic;">-- this is transpiled (then manually copied) to mpz_prime() in mpfr.js:</span>
<span style="color: #004080;">mpz</span> <span style="color: #000000;">modp47</span> <span style="color: #0000FF;">=</span> <span style="color: #004600;">NULL</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">w</span>
Line 4,438:
<span style="color: #008080;">return</span> <span style="color: #004600;">true</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<!--</langsyntaxhighlight>-->
Either the standard shim or the above can be used as follows
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">include</span> <span style="color: #004080;">mpfr</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
Line 4,469:
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 4,501:
 
=={{header|PHP}}==
<langsyntaxhighlight lang="php"><?php
function is_prime($n, $k) {
if ($n == 2)
Line 4,539:
echo "$i, ";
echo "\n";
?></langsyntaxhighlight>
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(de longRand (N)
(use (R D)
(while (=0 (setq R (abs (rand)))))
Line 4,588:
(do K
(NIL (_prim? N D S))
T ) ) ) )</langsyntaxhighlight>
{{out}}
<pre>: (filter '((I) (prime? I)) (range 937 1000))
Line 4,600:
 
=={{header|Pike}}==
<syntaxhighlight lang="pike">
<lang Pike>
 
 
Line 4,692:
36261430139487433507414165833468680972181038593593271409697364115931523786727274410257181186996611100786935727 PRIME
15579763548573297857414066649875054392128789371879472432457450095645164702139048181789700140949438093329334293 PRIME
</syntaxhighlight>
</lang>
 
=={{header|Prolog}}==
Line 4,699:
from the Erlang version on this page.
 
<langsyntaxhighlight lang="prolog">:- module(primality, [is_prime/2]).
 
% is_prime/2 returns false if N is composite, true if N probably prime
Line 4,781:
; Next_Loop =:= S -> Result = false
; inner_loop(Next_Base, N, Next_Loop, S, Result)
).</langsyntaxhighlight>
 
=={{header|PureBasic}}==
<langsyntaxhighlight PureBasiclang="purebasic">Enumeration
#Composite
#Probably_prime
Line 4,812:
Wend
ProcedureReturn #Probably_prime
EndProcedure</langsyntaxhighlight>
 
=={{header|Python}}==
Line 4,820:
This versions will give answers with a very small probability of being false. That probability being dependent number of trials (automatically set to 8).
 
<langsyntaxhighlight lang="python">
 
import random
Line 4,860:
return False
return True </langsyntaxhighlight>
 
===Python: Proved correct up to large N===
Line 4,866:
<br>For 341550071728321 and beyond, I have followed the pattern in choosing <code>a</code> from the set of prime numbers.<br>While this uses the best sets known in 1993, there are [http://miller-rabin.appspot.com/ better sets known], and at most 7 are needed for 64-bit numbers.
 
<langsyntaxhighlight lang="python">def _try_composite(a, d, n, s):
if pow(a, d, n) == 1:
return False
Line 4,902:
 
_known_primes = [2, 3]
_known_primes += [x for x in range(5, 1000, 2) if is_prime(x)]</langsyntaxhighlight>
 
;Testing:
Line 4,919:
 
=={{header|Racket}}==
<langsyntaxhighlight Racketlang="racket">#lang racket
(define (miller-rabin-expmod base exp m)
(define (squaremod-with-check x)
Line 4,951:
 
(prime? 4547337172376300111955330758342147474062293202868155909489) ;-> outputs true
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
(formerly Perl 6)
{{works with|Rakudo|2015-09-22}}
<syntaxhighlight lang="raku" perl6line># the expmod-function from: http://rosettacode.org/wiki/Modular_exponentiation
sub expmod(Int $a is copy, Int $b is copy, $n) {
my $c = 1;
Line 4,997:
}
 
say (1..1000).grep({ is_prime($_, 10) }).join(", "); </langsyntaxhighlight>
 
=={{header|REXX}}==
Line 5,010:
 
<br>To make the program small, the &nbsp; ''true prime generator'' &nbsp; ('''GenP''') &nbsp; was coded to be small, but not particularly fast.
<langsyntaxhighlight lang="rexx">/*REXX program puts the Miller─Rabin primality test through its paces. */
parse arg limit times seed . /*obtain optional arguments from the CL*/
if limit=='' | limit=="," then limit= 1000 /*Not specified? Then use the default.*/
Line 5,057:
if x\==nL then return 0 /*nope, it ain't prime nohows, noway. */
end /*k*/ /*maybe it's prime, maybe it ain't ··· */
return 1 /*coulda/woulda/shoulda be prime; yup.*/</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the input of: &nbsp; &nbsp; <tt> 10000 &nbsp; 10 </tt>}}
<pre>
Line 5,084:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
# Project : Miller–Rabin primality test
 
Line 5,133:
ok
end
</syntaxhighlight>
</lang>
Output:
<pre>
Line 5,144:
===Standard Probabilistic===
From 2.5 Ruby has fast modular exponentiation built in. For alternatives prior to 2.5 please see [[Modular_exponentiation#Ruby]]
<langsyntaxhighlight lang="ruby">def miller_rabin_prime?(n, g)
d = n - 1
s = 0
Line 5,165:
end
 
p primes = (3..1000).step(2).find_all {|i| miller_rabin_prime?(i,10)}</langsyntaxhighlight>
{{out}}
<pre>[3, 5, 7, 11, 13, 17, ..., 971, 977, 983, 991, 997]</pre>
The following larger examples all produce true:
<langsyntaxhighlight lang="ruby">puts miller_rabin_prime?(94366396730334173383107353049414959521528815310548187030165936229578960209523421808912459795329035203510284576187160076386643700441216547732914250578934261891510827140267043592007225160798348913639472564715055445201512461359359488795427875530231001298552452230535485049737222714000227878890892901228389026881,1000)
puts miller_rabin_prime?(138028649176899647846076023812164793645371887571371559091892986639999096471811910222267538577825033963552683101137782650479906670021895135954212738694784814783986671046107023185842481502719762055887490765764329237651328922972514308635045190654896041748716218441926626988737664133219271115413563418353821396401,1000)
puts miller_rabin_prime?(123301261697053560451930527879636974557474268923771832437126939266601921428796348203611050423256894847735769138870460373141723679005090549101566289920247264982095246187318303659027201708559916949810035265951104246512008259674244307851578647894027803356820480862664695522389066327012330793517771435385653616841,1000)
Line 5,175:
puts miller_rabin_prime?(132082885240291678440073580124226578272473600569147812319294626601995619845059779715619475871419551319029519794232989255381829366374647864619189704922722431776563860747714706040922215308646535910589305924065089149684429555813953571007126408164577035854428632242206880193165045777949624510896312005014225526731,1000)
puts miller_rabin_prime?(153410708946188157980279532372610756837706984448408515364579602515073276538040155990230789600191915021209039203172105094957316552912585741177975853552299222501069267567888742458519569317286299134843250075228359900070009684517875782331709619287588451883575354340318132216817231993558066067063143257425853927599,1000)
puts miller_rabin_prime?(103130593592068072608023213244858971741946977638988649427937324034014356815504971087381663169829571046157738503075005527471064224791270584831779395959349442093395294980019731027051356344056416276026592333932610954020105156667883269888206386119513058400355612571198438511950152690467372712488391425876725831041,1000)</langsyntaxhighlight>
 
===Deterministic for integers < 3,317,044,064,679,887,385,961,981===
It extends '''class Integer''' to make it simpler to use.
<langsyntaxhighlight lang="ruby">class Integer
# Returns true if +self+ is a prime number, else returns false.
def primemr?(k = 10)
Line 5,302:
n = 94366396730334173383107353049414959521528815310548187030165936229578960209523421808912459795329035203510284576187160076386643700441216547732914250578934261891510827140267043592007225160798348913639472564715055445201512461359359488795427875530231001298552452230535485049737222714000227878890892901228389026881
print "\n number = #{n} is prime? "; print " in ", tm{ print n.primemr? }, " secs"
puts</langsyntaxhighlight>
 
=={{header|Run BASIC}}==
Line 5,308:
''This code has not been fully tested. Remove this comment after review.''
 
<langsyntaxhighlight lang="runbasic">input "Input a number:";n
input "Input test:";k
 
Line 5,362:
wend
[funEnd]
END FUNCTION</langsyntaxhighlight>
 
=={{header|Rust}}==
 
<langsyntaxhighlight lang="rust">/* Add these lines to the [dependencies] section of your Cargo.toml file:
num = "0.2.0"
rand = "0.6.5"
Line 5,528:
// that n really is a prime number, so return true:
true
}</langsyntaxhighlight>
 
'''Test code:'''
 
<langsyntaxhighlight lang="rust">fn main() {
let n = 1234687;
let result = is_prime(&n);
Line 5,556:
let result = is_prime(&n);
println!("Q: Is {} prime? A: {}", n, result);
}</langsyntaxhighlight>
{{out}}
<pre>Q: Is 1234687 prime? A: true
Line 5,566:
 
=={{header|Scala}}==
{{libheader|Scala}}<langsyntaxhighlight lang="scala">import scala.math.BigInt
 
object MillerRabinPrimalityTest extends App {
val (n, certainty )= (BigInt(args(0)), args(1).toInt)
println(s"$n is ${if (n.isProbablePrime(certainty)) "probably prime" else "composite"}")
}</langsyntaxhighlight>
 
Direct implementation of algorithm:
 
<langsyntaxhighlight lang="scala">
import scala.annotation.tailrec
import scala.language.{implicitConversions, postfixOps}
Line 5,613:
}) != 1
}
}</langsyntaxhighlight>
 
=={{header|Scheme}}==
<langsyntaxhighlight lang="scheme">#!r6rs
(import (rnrs base (6))
(srfi :27 random-bits))
Line 5,658:
(and (> n 1)
(or (= n 2)
(pseudoprime? n 50))))</langsyntaxhighlight>
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
include "bigint.s7i";
Line 5,706:
end if;
end for;
end func;</langsyntaxhighlight>Original source: [http://seed7.sourceforge.net/algorith/math.htm#millerRabin]
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">func miller_rabin(n, k=10) {
 
return false if (n <= 1)
Line 5,736:
}
 
say miller_rabin.grep(^1000).join(', ')</langsyntaxhighlight>
 
=={{header|Smalltalk}}==
{{works with|GNU Smalltalk}}
Smalltalk handles big numbers naturally and trasparently (the parent class <tt>Integer</tt> has many subclasses, and <cite>a subclass is picked according to the size</cite> of the integer that must be handled)
<langsyntaxhighlight lang="smalltalk">Integer extend [
millerRabinTest: kl [ |k| k := kl.
self <= 3
Line 5,774:
]
]
].</langsyntaxhighlight>
<langsyntaxhighlight lang="smalltalk">1 to: 1000 do: [ :n |
(n millerRabinTest: 10) ifTrue: [ n printNl ]
].</langsyntaxhighlight>
 
=={{header|Standard ML}}==
<langsyntaxhighlight lang="sml">open LargeInt;
 
val mr_iterations = Int.toLarge 20;
Line 5,828:
then (n,t)
else findPrime t end
in List.tabulate (10, fn e => findPrime 0) end;</langsyntaxhighlight>
{{out|Sample run}}
<pre>
Line 5,855:
{{libheader|Attaswift BigInt}}
 
<langsyntaxhighlight lang="swift">import BigInt
 
private let numTrails = 5
Line 5,891:
 
return true
}</langsyntaxhighlight>
 
=={{header|Tcl}}==
Use Tcl 8.5 for large integer support
<langsyntaxhighlight lang="tcl">package require Tcl 8.5
 
proc miller_rabin {n k} {
Line 5,928:
puts $i
}
}</langsyntaxhighlight>
{{out}}
<pre>1
Line 5,947:
 
I've therefore used this method to check the same numbers as in my Kotlin entry.
<langsyntaxhighlight lang="ecmascript">import "/big" for BigInt
 
var iters = 10
Line 5,963:
for (bi in bia) {
System.print("%(bi) is %(bi.isProbablePrime(iters) ? "probably prime" : "composite")")
}</langsyntaxhighlight>
 
{{out}}
Line 5,976:
=={{header|zkl}}==
Using the Miller-Rabin primality test in GMP:
<langsyntaxhighlight lang="zkl">zkl: var BN=Import("zklBigNum");
zkl: BN("4547337172376300111955330758342147474062293202868155909489").probablyPrime()
True
zkl: BN("4547337172376300111955330758342147474062293202868155909393").probablyPrime()
False</langsyntaxhighlight>
10,327

edits