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

时间:2012-06-28 00:54:10

标签: 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
}

这样:

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;

正在给我:

0
1
1
1
0
1

2 个答案:

答案 0 :(得分: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

另外,如果输入是偶数,它总是会返回素数,因为a是0.你应该在开头添加一个额外的检查。

答案 1 :(得分:4)

在内循环中,

        for(unsigned int j = 1; j < a; j++){
            z = POW(z, 2, w);
            if (z == W)
                continue;
            if (z == 1)
                return 0;// Composite
        }

break;时,您应continue;而不是z == W。通过continue,在该循环的下一次迭代中,如果有一个,z将变为1并且候选者可能被错误地声明为复合。在这里,在小于100的素数中,这种情况发生在17,41,73,89和97中。