Miller–Rabin primality test: Difference between revisions
Content added Content deleted
(→{{header|Ruby}}: Adapted to handle slightly larger figures) |
(→{{header|Ada}}: -- revised solution using a (generic) package, to be used elsewhere in Rosetta Code) |
||
Line 28:
For Number types >= 2**64 you may have to use an external library -- see below.
<lang Ada>with Ada.Text_IO;▼
with Ada.Numerics.Discrete_Random;▼
First, a package Miller_Rabin is specified. The same package is used else elsewhere in Rosetta Code, such as for the Carmichael 3 strong pseudoprimes [[http://rosettacode.org/wiki/Carmichael_3_strong_pseudoprimes,_or_Miller_Rabin%27s_nemesis]].
procedure Miller_Rabin is▼
type Number is mod 2**48;▼
<lang Ada>generic
package Num_IO is new Ada.Text_IO.Modular_IO (Number);▼
package Pos_IO is new Ada.Text_IO.Integer_IO (Positive);▼
type Result_Type is (Composite, Probably_Prime);
function Is_Prime (N : Number; K : Positive := 10) return Result_Type;
end Miller_Rabin;</lang>▼
The implementation of that package is as follows:
▲<lang Ada>with Ada.Numerics.Discrete_Random;
package body Miller_Rabin is
function Is_Prime (N : Number; K : Positive := 10)
is
subtype Number_Range is Number range 2 .. N - 1;
Line 81 ⟶ 85:
X := Mod_Exp(Random.Random (Generator), D, N);
if X /= 1 and X /= N - 1 then
X := Mod_Exp (X, 2, N);
if X = 1 then return Composite; end if;
Line 93 ⟶ 97:
end Is_Prime;
end Miller_Rabin;</lang>
Finally, the program itself:
▲<lang Ada>with Ada.Text_IO, Miller_Rabin;
procedure Mr_Tst is
type Number is range 0 .. (2**48)-1;
▲ package Pos_IO is new Ada.Text_IO.Integer_IO (Positive);
package MR is new Miller_Rabin(Number); use MR;
N : Number;
K : Positive;
begin▼
▲begin
for I in
if Is_Prime (I) = Probably_Prime then
Ada.Text_IO.Put (
end if;
end loop;
Ada.Text_IO.Put_Line (".");
Ada.Text_IO.Put ("Enter a Number: "); Num_IO.Get (N);
Ada.Text_IO.Put ("Enter the count of loops: "); Pos_IO.Get (K);
Ada.Text_IO.
end MR_Tst;</lang>
▲end Miller_Rabin;</lang>
{{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 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.
|