确定性 Miller-Rabin 实施

Deterministic Miller-Rabin implementation

我正在尝试使用确定性 Miller-Rabin 算法实现素数检查功能,但结果并不总是正确的:检查前 1,000,000 个数字时,它只找到 78,495 而不是 78,498。

这是使用 [2, 7, 61] 作为基础获得的,根据维基百科,对于最大 4,759,123,141 的值应该始终是正确的。
有趣的是,缺少的 3 个素数正是组成基数的素数(2、7 和 61)。

为什么会这样?我使用的代码如下:

T modular_power(T base, T exponent, T modulo) {
    base %= modulo;
    T result = 1;

    while (exponent > 0) {
        if (exponent % 2 == 1)
            result = (result * base) % modulo;
        base = (base * base) % modulo;
        exponent /= 2;
    }

    return result;
}

bool miller_rabin(const T& n, const vector<T>& witnesses) {
    unsigned int s = 0;
    T d = n - 1;
    while (d % 2 == 0) {
        s++;
        d /= 2;
    }

    for (const auto& a : witnesses) {
        if (modular_power<T>(a, d, n) == 1)
            continue;

        bool composite = true;
        for (unsigned int r = 0; r < s; r++) {
            if (modular_power<T>(a, (T) pow(2, r) * d, n) == n - 1) {
                composite = false;
                break;
            }
        }

        if (composite)
            return false;
    }

    return true;
}

bool is_prime(const T& n) {
    if (n < 4759123141)
        return miller_rabin(n, {2, 7, 61});
    return false; // will use different base
}

当基数和输入相同时,Miller-Rabin 确实不起作用。在这种情况下发生的是 ad mod n 为零(因为 a mod n 为零,所以这实际上是将零提高到一些不相关的幂) ,算法的其余部分无法 "escape" 从零开始并得出结论,您正在处理复合材料。

作为一个特例,Miller-Rabin 从不使用输入 2,因为没有可以选择的基数。 2本身没用,1也没用,什么都不剩