米勒-拉宾检验
维基百科,自由的百科全书
|
|
本条目需要精通或熟悉本主题的專業人士参与及協助编辑。 |
要測試
是否為質數,首先將
分解為
。在每次測試開始時,先隨機選一個 介於
的整數
,之後如果對所有的
,若
且
,則 N 是合數。否則,
有
的機率為質數。
[编辑] 示例代码
下面是根据以上定义而使用 Magma 语言编写的 “米勒-拉宾” 检验程序。
function ModPotenz(a,b,n) erg:=1; while (b ne 0) do b, rest:=Quotrem(b,2); if (rest ne 0) then erg:=((erg*a) mod n); end if; a:= (a^2 mod n); end while; return erg; end function; ; function Miller_rabin(n) if (n mod 2 ne 0) then d:=n-1; s:=0;t:=50; while (d mod 2) eq 0 do d:=d div 2; s:=s+1; end while; k:=0; while(k lt t) do a:=Random(1,n-1); k:=k+1; if GCD(a,n) ne 1 then continue; end if; x:=ModPotenz(a,d,n); if(x ne 1) then for r in [0,s-1] do x:=ModPotenz(a,2^r*d,n); if(x eq (n-1)) then return "probably prime"; end if; end for; elif (x eq 1) then break; end if; end while; end if; return "composite"; end function;