Miller-Rabin Primality测试FIPS 186-3实施

cal*_*pto 6 c++ math implementation primality-test

我试图根据FIPS 186-3 C.3.1中的描述实施Miller-Rabin素性测试.无论我做什么,我都无法让它发挥作用.说明是非常具体的,我不认为我错过任何东西,但我得到true非素数值.

我做错了什么?

template <typename R, typename S, typename T>
T POW(R base, S exponent, const T mod){
    T result = 1;
    while (exponent){
        if (exponent & 1)
            result = (result * base) % mod;
        exponent >>= 1;
        base = (base * base) % mod;
    }
    return result;
}



// used uint64_t to prevent overflow, but only testing with small numbers for now
bool MillerRabin_FIPS186(uint64_t w, unsigned int iterations = 50){
    srand(time(0));
    unsigned int a = 0;
    uint64_t W = w - 1; // dont want to keep calculating w - 1
    uint64_t m = W;
    while (!(m & 1)){
        m >>= 1;
        a++;
    }

    // skipped getting wlen
    // when i had this function using my custom arbitrary precision integer class,
    // and could get len(w), getting it and using it in an actual RBG 
    // made no difference 

    for(unsigned int i = 0; i < iterations; i++){
        uint64_t b = (rand() % (W - 3)) + 2; // 2 <= b <= w - 2
        uint64_t z = POW(b, m, w);
        if ((z == 1) || (z == W))
            continue;
        else
            for(unsigned int j = 1; j < a; j++){
                z = POW(z, 2, w);
                if (z == W)
                    continue;
                if (z == 1)
                    return 0;// Composite
            }
    }
    return 1;// Probably Prime
}
Run Code Online (Sandbox Code Playgroud)

这个:

std::cout << MillerRabin_FIPS186(33) << std::endl;
std::cout << MillerRabin_FIPS186(35) << std::endl;
std::cout << MillerRabin_FIPS186(37) << std::endl;
std::cout << MillerRabin_FIPS186(39) << std::endl;
std::cout << MillerRabin_FIPS186(45) << std::endl;
std::cout << MillerRabin_FIPS186(49) << std::endl;
Run Code Online (Sandbox Code Playgroud)

给我的是:

0
1
1
1
0
1
Run Code Online (Sandbox Code Playgroud)

Ant*_*ony 5

您的实现与Wikipedia之间的唯一区别是您忘记了第二个返回复合语句.你应该在循环结束时返回0.

编辑:正如丹尼尔指出的,还有第二个区别.继续继续内循环,而不是像它应该的那样外循环.

for(unsigned int i = 0; i < iterations; i++){
    uint64_t b = (rand() % (W - 3)) + 2; // 2 <= b <= w - 2
    uint64_t z = POW(b, m, w);
    if ((z == 1) || (z == W))
        continue;
    else{
        int continueOuter = 0;
        for(unsigned int j = 1; j < a; j++){
            z = POW(z, 2, w);
            if (z == W)
                continueOuter = 1;
                break;
            if (z == 1)
                return 0;// Composite
        }
        if (continueOuter) {continue;}
    }
    return 0; //This is the line you're missing.
}
return 1;// Probably Prime
Run Code Online (Sandbox Code Playgroud)

此外,如果输入是偶数,它将始终返回,因为a为0.您应该在开头添加额外的检查.

  • 人们希望素数测试不会用于偶数.:) (3认同)
  • @calccrypto:你不能只是添加break*和*返回0,因为现在每当你中断返回0时都会被触发.在循环之前将标志(例如contloop)设置为false.而不是只是中断,设置"contloop = 1; break;},然后只有当contloop为false时才返回0.[或者其他东西.] (2认同)