fork(5) download
  1. program miller_rabin_primilarity_test;
  2. function bigmultiplication(x,y,n:longint):longint;
  3. var
  4. doi:longint;
  5. begin
  6. doi:=0;
  7. while(y>0) do
  8. begin
  9. if(y mod 2 =1) then
  10. begin
  11. doi:=(doi+x)mod n;
  12. end;
  13.  
  14. x:=(2*x)mod n;
  15. y:=y div 2;
  16. end;
  17. bigmultiplication:=doi;
  18. end;
  19.  
  20.  
  21.  
  22.  
  23. function exponents_mod_n(x,y,n:longint):longint;
  24. var
  25. doi,doing:longint;
  26. begin
  27. doing:=x;
  28. doi:=1;
  29. while(y>0) do
  30. begin
  31. if(y mod 2 =1) then
  32. begin
  33. doi:=bigmultiplication(doi,doing,n);
  34. end;
  35. doing:=bigmultiplication(doing,doing,n);
  36. y:=y div 2;
  37. end;
  38. exponents_mod_n:=doi;
  39. end;
  40. function miller_rabin(p1:longint):boolean;
  41. var
  42. a,p,x,prime:Longint;
  43. i,r,s,d:integer;
  44.  
  45. begin
  46. s:=0;
  47. Randomize;
  48.  
  49. if p1 mod 2 = 0 then
  50. begin
  51. miller_rabin:=false;
  52. exit;
  53. end;
  54. prime:=p1;
  55. p:=p1-1;
  56.  
  57. while p mod 2 =0 do
  58. begin
  59. p:= p div 2;
  60. s:=s+1;
  61. end;
  62. d:=p;
  63. for i:=1 to 7 do
  64. begin
  65. a:=random(prime) mod prime + 1 ;
  66. x:=exponents_mod_n(a,d,prime);
  67. r:=0;
  68. while((r<(s-1)) and (x <> 1) and (x<>prime-1) )do
  69. begin
  70.  
  71. x:=exponents_mod_n(x,2,prime);
  72. if x=1 then
  73. begin
  74. miller_rabin:=false;
  75. exit;
  76. end;
  77. r:=r+1;
  78. end;
  79.  
  80.  
  81. end;
  82. miller_rabin:=true;
  83. end;
  84. var
  85. prime:longint;
  86. ans:boolean;
  87. begin
  88. readln(prime);
  89. ans:=miller_rabin(prime);
  90. writeln(ans);
  91. end.
  92.  
stdin
23
compilation info
Free Pascal Compiler version 2.2.0 [2009/11/16] for i386
Copyright (c) 1993-2007 by Florian Klaempfl
Target OS: Linux for i386
Compiling prog.pas
Linking prog
91 lines compiled, 0.0 sec
stdout
TRUE