簡體   English   中英

通過檢查 n 是否可整除 2^n-2 對 n 進行素性測試

[英]Primality test for n by checking whether n divides 2^n-2

所以我的問題是如何實現這個公式:當且僅當 n 除以 2^n-2 時,正整數 n(大於 1)是素數。 到目前為止,我想出了這個代碼,但我被卡住了。 我是新手,剛開始學習java,任何幫助都會很棒,謝謝!

public boolean isPrime(int x){
     if(x==1) 
        return false; 
     if(x==2) 
        return true;
     if(x % 2 == 0)
        return false;

     for(int i=3; i<Math.sqrt(x); i++)

這是我感到困惑的地方。

直接的方法,計算 2 n -2 然后測試可分性,顯然是完全不可擴展的。 幸運的是我們可以只工作模n整個方式,這種方式不會有大的數字。 無論如何,這個概念證明使用BigInteger ,只是因為它有一個方便的modPow實現,它可以在沒有它的情況下被重寫。

static boolean isProbablyPrime(int n) {
    BigInteger bigN = BigInteger.valueOf(n);
    BigInteger two = BigInteger.valueOf(2);
    BigInteger t = two.modPow(bigN, bigN);
    return t.longValue() == 2;
}

我重命名了該函數,因為它傳遞了一些非素數,例如評論中提到的 561。

ideone試試

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM