gpt4 book ai didi

c++ - 确定性 Miller-Rabin 实现

转载 作者:搜寻专家 更新时间:2023-10-31 01:30:16 28 4
gpt4 key购买 nike

我正在尝试使用确定性 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 为零,所以这实际上是将零提高到一些不相关的幂),并且算法的其余部分无法“从零开始“逃逸”,并得出结论,您正在处理复合 Material 。

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

关于c++ - 确定性 Miller-Rabin 实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48242447/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com