我在C sharp中編寫了一個Miller Rabin素數測試,但它在每個輸入上都返回false。Miller Rabin Primality test
下面的代碼:
static Boolean MilRab(UInt64 n)
{
UInt64[] ar = new UInt64[] { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 };
for (int i = 0; i < 10; i++)
{
if (Tanu(ar[i], n) == true) return false;
}
return true;
}//MilRab
static Boolean Tanu(UInt64 a, UInt64 n)
{
UInt64 b = n - 1;
UInt64 d = 1;
UInt64 x;
Int16 i;
for (i = 63; i >= 0; i--) if (((b >> i) & 1) == 1) break;
for (;i>=0;i--)
{
x = d;
d = ((d * d) % n);
if (d == 1 && x != 1 && x != n - 1) return true;
if (b>>i == 1) d = (d * a) % n;
}
if (d != 1) return true;
return false;
}//Tanu
你覺得有什麼問題,可以嗎?我花了一天的時間進行調試,讓我瘋狂。謝謝。
在'(d * d)%N'和'(d * A)%N',乘法能(並且經常會)在模數減少之前對模2^64進行換行,這是不正確的(對於幾乎所有的'n')。 – harold
我推薦使用'BigInteger'結構。 – CodesInChaos
這不應該工作.. – harold