Miller–Rabin primality test: Difference between revisions

Content added Content deleted
(update to use LargeInt)
m (whitespace/{{out}})
Line 25: Line 25:


For Number types >= 2**64 you may have to use an external library.
For Number types >= 2**64 you may have to use an external library.

<lang Ada>with Ada.Text_IO;
<lang Ada>with Ada.Text_IO;
with Ada.Numerics.Discrete_Random;
with Ada.Numerics.Discrete_Random;
Line 109: Line 108:
Ada.Text_IO.Put_Line ("What is it? " & Result_Type'Image (Is_Prime (N, K)));
Ada.Text_IO.Put_Line ("What is it? " & Result_Type'Image (Is_Prime (N, K)));
end Miller_Rabin;</lang>
end Miller_Rabin;</lang>
{{out}}

Output:
<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 101 103 107 109 113 127 131 137 139 149 151 157 163 167 173 179 181 191 193 197 199 211 223 227 229 233 239 241 251 257 263 269 271 277 281 283 293 307 311 313 317 331 337 347 349 353 359 367 373 379 383 389 397 401 409 419 421 431 433 439 443 449 457 461 463 467 479 487 491 499 503 509 521 523 541 547 557 563 569 571 577 587 593 599 601 607 613 617 619 631 641 643 647 653 659 661 673 677 683 691 701 709 719 727 733 739 743 751 757 761 769 773 787 797 809 811 821 823 827 829 839 853 857 859 863 877 881 883 887 907 911 919 929 937 941 947 953 967 971 977 983 991 997.
<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 101 103 107 109 113 127 131 137 139 149 151 157 163 167 173 179 181 191 193 197 199 211 223 227 229 233 239 241 251 257 263 269 271 277 281 283 293 307 311 313 317 331 337 347 349 353 359 367 373 379 383 389 397 401 409 419 421 431 433 439 443 449 457 461 463 467 479 487 491 499 503 509 521 523 541 547 557 563 569 571 577 587 593 599 601 607 613 617 619 631 641 643 647 653 659 661 673 677 683 691 701 709 719 727 733 739 743 751 757 761 769 773 787 797 809 811 821 823 827 829 839 853 857 859 863 877 881 883 887 907 911 919 929 937 941 947 953 967 971 977 983 991 997.
Enter a Number: 1234567
Enter a Number: 1234567
Line 118: Line 116:
=={{header|ALGOL 68}}==
=={{header|ALGOL 68}}==
{{trans|python}}
{{trans|python}}

{{works with|ALGOL 68|Standard - with preludes manually inserted }}
{{works with|ALGOL 68|Standard - with preludes manually inserted }}

{{works with|ALGOL 68G|Any - tested with release mk15-0.8b.fc9.i386}}
{{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 }} -->
<!-- {{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 }} -->
Line 161: Line 157:
FI
FI
OD</lang>
OD</lang>
{{out}}
Sample output:
<pre>
<pre>
937 941 947 953 967 971 977 983 991 997
937 941 947 953 967 971 977 983 991 997
Line 212: Line 208:
=={{header|bc}}==
=={{header|bc}}==
Requires a <tt>bc</tt> with long names.
Requires a <tt>bc</tt> with long names.

{{works with|OpenBSD bc}}
{{works with|OpenBSD bc}}
(A previous version worked with [[GNU bc]].)
(A previous version worked with [[GNU bc]].)
Line 286: Line 281:
=={{header|C}}==
=={{header|C}}==
{{libheader|GMP}}
{{libheader|GMP}}

'''miller-rabin.h'''
'''miller-rabin.h'''

<lang c>#ifndef _MILLER_RABIN_H_
<lang c>#ifndef _MILLER_RABIN_H_
#define _MILLER_RABIN_H
#define _MILLER_RABIN_H
Line 294: Line 287:
bool miller_rabin_test(mpz_t n, int j);
bool miller_rabin_test(mpz_t n, int j);
#endif</lang>
#endif</lang>

'''miller-rabin.c'''
'''miller-rabin.c'''

{{trans|Fortran}}
{{trans|Fortran}}

For <code>decompose</code> (and header <tt>primedecompose.h</tt>), see [[Prime decomposition#C|Prime decomposition]].
For <code>decompose</code> (and header <tt>primedecompose.h</tt>), see [[Prime decomposition#C|Prime decomposition]].

<lang c>#include <stdbool.h>
<lang c>#include <stdbool.h>
#include <gmp.h>
#include <gmp.h>
Line 364: Line 353:
return res;
return res;
}</lang>
}</lang>

'''Testing'''
'''Testing'''

<lang c>#include <stdio.h>
<lang c>#include <stdio.h>
#include <stdlib.h>
#include <stdlib.h>
Line 397: Line 384:
}</lang>
}</lang>


=={{header|C sharp}}==
=={{header|C sharp|C#}}==
<lang csharp>public static class RabinMiller

<lang C sharp|C#>
public static class RabinMiller
{
{
public static bool IsPrime(int n, int k)
public static bool IsPrime(int n, int k)
Line 435: Line 420:
return true;
return true;
}
}
}</lang>
}
<lang csharp>// Miller-Rabin primality test as an extension method on the BigInteger type.
</lang>

<lang C sharp|C#>
// Miller-Rabin primality test as an extension method on the BigInteger type.
// Based on the Ruby implementation on this page.
// Based on the Ruby implementation on this page.
public static class BigIntegerExtensions
public static class BigIntegerExtensions
Line 496: Line 478:
return true;
return true;
}
}
}</lang>
}
</lang>


=={{header|Common Lisp}}==
=={{header|Common Lisp}}==

<lang lisp>(defun factor-out (number divisor)
<lang lisp>(defun factor-out (number divisor)
"Return two values R and E such that NUMBER = DIVISOR^E * R,
"Return two values R and E such that NUMBER = DIVISOR^E * R,
Line 598: Line 578:


=={{header|E}}==
=={{header|E}}==

<lang e>def millerRabinPrimalityTest(n :(int > 0), k :int, random) :boolean {
<lang e>def millerRabinPrimalityTest(n :(int > 0), k :int, random) :boolean {
if (n <=> 2 || n <=> 3) { return true }
if (n <=> 2 || n <=> 3) { return true }
Line 622: Line 601:
return true
return true
}</lang>
}</lang>

<lang e>for i ? (millerRabinPrimalityTest(i, 1, entropy)) in 4..1000 {
<lang e>for i ? (millerRabinPrimalityTest(i, 1, entropy)) in 4..1000 {
print(i, " ")
print(i, " ")
Line 629: Line 607:


=={{header|Erlang}}==
=={{header|Erlang}}==
<lang erlang>-module(miller_rabin).

<lang erlang>
-module(miller_rabin).


-compile([export_all]).
-compile([export_all]).
Line 708: Line 684:
end,
end,
L),
L),
ok.
ok.</lang>
{{out}}
</lang>

<pre>
<pre>
42> miller_rabin:first_1000().
42> miller_rabin:first_1000().
Line 731: Line 706:
=={{header|Fortran}}==
=={{header|Fortran}}==
{{works with|Fortran|95}}
{{works with|Fortran|95}}

For the module ''PrimeDecompose'', see [[Prime decomposition#Fortran|Prime decomposition]].
For the module ''PrimeDecompose'', see [[Prime decomposition#Fortran|Prime decomposition]].

<lang fortran>module Miller_Rabin
<lang fortran>module Miller_Rabin
use PrimeDecompose
use PrimeDecompose
Line 790: Line 763:


end module Miller_Rabin</lang>
end module Miller_Rabin</lang>

'''Testing'''
'''Testing'''

<lang fortran>program TestMiller
<lang fortran>program TestMiller
use Miller_Rabin
use Miller_Rabin
Line 817: Line 788:
end program TestMiller</lang>
end program TestMiller</lang>
''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)


''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)
=={{header|Go}}==
=={{header|Go}}==
Go has it in the standard library. [http://golang.org/pkg/big/#ProbablyPrime ProbablyPrime]
Go has it in the standard library. [http://golang.org/pkg/big/#ProbablyPrime ProbablyPrime]
Line 824: Line 795:
=={{header|Haskell}}==
=={{header|Haskell}}==
{{works with|Haskell|6.10.4}}
{{works with|Haskell|6.10.4}}

* Ideas taken from [http://primes.utm.edu/prove/prove2_3.html Primality proving]
* Ideas taken from [http://primes.utm.edu/prove/prove2_3.html Primality proving]
* Functions witns and isMillerRabinPrime follow closely the code outlined in [http://www.jsoftware.com/jwiki/Essays/Primality%20Tests#Miller-Rabin J/Essays]
* Functions witns and isMillerRabinPrime follow closely the code outlined in [http://www.jsoftware.com/jwiki/Essays/Primality%20Tests#Miller-Rabin J/Essays]
* A useful powerMod function is taken from [http://rosettacode.org/wiki/Multiplicative_order#Haskell]
* A useful powerMod function is taken from [http://rosettacode.org/wiki/Multiplicative_order#Haskell]

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]
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]

<lang Haskell>import System.Random
<lang Haskell>import System.Random
import Data.List
import Data.List
Line 875: Line 843:


=={{header|Icon}} and {{header|Unicon}}==
=={{header|Icon}} and {{header|Unicon}}==

The following code works in both languages:
The following code works in both languages:
<lang unicon>procedure main()
<lang unicon>procedure main()
Line 899: Line 866:
return n
return n
end</lang>
end</lang>
{{out|Sample run}}

Sample run:
<pre>->mrpt
<pre>->mrpt
907 911 919 929 937 941 947 953 967 971 977 983 991 997
907 911 919 929 937 941 947 953 967 971 977 983 991 997
Line 909: Line 875:


=={{header|Java}}==
=={{header|Java}}==

The Miller-Rabin primality test is part of the standard library (java.math.BigInteger)
The Miller-Rabin primality test is part of the standard library (java.math.BigInteger)

<lang java>import java.math.BigInteger;
<lang java>import java.math.BigInteger;


public class MillerRabinPrimalityTest
public class MillerRabinPrimalityTest {
public static void main(String[] args) {
{
public static void main(String[] args)
{
BigInteger n = new BigInteger(args[0]);
BigInteger n = new BigInteger(args[0]);
int certainty = Integer.parseInt(args[1]);
int certainty = Integer.parseInt(args[1]);
Line 923: Line 885:
}
}
}</lang>
}</lang>
{{out|Sample output}}

Sample output:

<pre>java MillerRabinPrimalityTest 123456791234567891234567 1000000
<pre>java MillerRabinPrimalityTest 123456791234567891234567 1000000
123456791234567891234567 is probably prime</pre>
123456791234567891234567 is probably prime</pre>
Line 938: Line 898:
];
];
,{k}];
,{k}];
Print[test] ]
Print[test] ]</lang>
{{out|Example output (not using the PrimeQ builtin)}}

<lang mathematica>MillerRabin[17388,10]
Example output (not using the PrimeQ builtin):
MillerRabin[17388,10]
->False</lang>
->False</lang>


Line 947: Line 906:
===Built-in===
===Built-in===
<lang parigp>MR(n,k)=ispseudoprime(n,k);</lang>
<lang parigp>MR(n,k)=ispseudoprime(n,k);</lang>

===Custom===
===Custom===
<lang parigp>sprp(n,b)={
<lang parigp>sprp(n,b)={
Line 965: Line 923:
1
1
};</lang>
};</lang>

===Deterministic version===
===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).
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).
Line 1,162: Line 1,119:
(NIL (_prim? N D S))
(NIL (_prim? N D S))
T ) ) ) )</lang>
T ) ) ) )</lang>
{{out}}
Output:
<pre>: (filter '((I) (prime? I)) (range 937 1000))
<pre>: (filter '((I) (prime? I)) (range 937 1000))
-> (937 941 947 953 967 971 977 983 991 997)
-> (937 941 947 953 967 971 977 983 991 997)
Line 1,171: Line 1,128:
: (prime? 4547337172376300111955330758342147474062293202868155909393)
: (prime? 4547337172376300111955330758342147474062293202868155909393)
-> NIL</pre>
-> NIL</pre>

=={{header|PureBasic}}==
=={{header|PureBasic}}==
<lang PureBasic>Enumeration
<lang PureBasic>Enumeration
Line 1,203: Line 1,161:


=={{header|Python}}==
=={{header|Python}}==
<lang python>
<lang python>import random
import random


_mrpt_num_trials = 5 # number of bases to test
_mrpt_num_trials = 5 # number of bases to test
Line 1,281: Line 1,238:
return False
return False


return True # no base tested showed n as composite
return True # no base tested showed n as composite</lang>
</lang>


=={{header|REXX}}==
=={{header|REXX}}==
With a K of 1, there seems to be a not uncommon number of failures, but
With a K of 1, there seems to be a not uncommon number of failures, but
<br>with a K ≥ 2, the failures are rare,
:with a K ≥ 2, the failures are rare,
<br>with a K ≥ 3, rare as hen's teeth.
:with a K ≥ 3, rare as hen's teeth.

<br><br>
This would be in the same vein as: 3 is prime, 5 is prime, 7 is prime, all odd numbers are prime.
This would be in the same vein as: 3 is prime, 5 is prime, 7 is prime, all odd numbers are prime.
<lang rexx>/*REXX program puts Miller-Rabin primality test through its paces. */
<lang rexx>
/*REXX program puts Miller-Rabin primality test through its paces. */


arg limit accur . /*get some arguments (if any). */
arg limit accur . /*get some arguments (if any). */
Line 1,366: Line 1,321:
!.j=1 /*and keep filling the water jar.*/
!.j=1 /*and keep filling the water jar.*/
end /*j*/ /*this comment not left blank. */
end /*j*/ /*this comment not left blank. */
return /*whew! All done with the primes*/
return /*whew! All done with the primes*/</lang>
{{out|Output when using the input of <tt>10000 10</tt>}}
</lang>
Output when using the input of:
<br><br>
10000 10
<pre style="height:30ex;overflow:scroll">
<pre style="height:30ex;overflow:scroll">
They're 1229 primes <= 10000
They're 1229 primes <= 10000
Line 1,422: Line 1,374:


p primes = (1..100).find_all {|i| miller_rabin_prime?(i,10)}</lang>
p primes = (1..100).find_all {|i| miller_rabin_prime?(i,10)}</lang>
{{out}}
<pre>[2, 3, 5, 7, 11, 13, 17, ..., 971, 977, 983, 991, 997]</pre>
<pre>[2, 3, 5, 7, 11, 13, 17, ..., 971, 977, 983, 991, 997]</pre>


=={{header|Smalltalk}}==
=={{header|Smalltalk}}==
{{works with|GNU 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)
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)
<lang smalltalk>Integer extend [
<lang smalltalk>Integer extend [
Line 1,462: Line 1,414:
]
]
].</lang>
].</lang>

<lang smalltalk>1 to: 1000 do: [ :n |
<lang smalltalk>1 to: 1000 do: [ :n |
(n millerRabinTest: 10) ifTrue: [ n printNl ]
(n millerRabinTest: 10) ifTrue: [ n printNl ]
Line 1,468: Line 1,419:


=={{header|Standard ML}}==
=={{header|Standard ML}}==
<lang sml>open LargeInt;

<lang sml>
open LargeInt;


val mr_iterations = Int.toLarge 20;
val mr_iterations = Int.toLarge 20;
Line 1,518: Line 1,467:
then (n,t)
then (n,t)
else findPrime t end
else findPrime t end
in List.tabulate (10, fn e => findPrime 0) end;
in List.tabulate (10, fn e => findPrime 0) end;</lang>
{{out|Sample run}}



</lang>

Sample run:

<pre>
<pre>
...
...
Line 1,545: Line 1,488:
(349239056313926786302179212509,7),(565349019043144709861293116613,126)]
(349239056313926786302179212509,7),(565349019043144709861293116613,126)]
: (int * int) list
: (int * int) list

</pre>
</pre>


Line 1,584: Line 1,526:
}
}
}</lang>
}</lang>
{{out}}
produces
<pre>1
<pre>1
2
2