米勒-拉宾测试不适用于252097800623

miller-rabin test don't work for 252097800623

本文关键字:适用于 252097800623 不适用 测试 -拉 米勒      更新时间:2023-10-16

我正在尝试编写miller-rabin测试。我发现了一些代码,例如:

https://www.sanfoundry.com/cpp-program-implement-miller-rabin-primality-test/https://www.geeksforgeeks.org/primality-test-set-3-miller-rabin/

当然,所有这些代码都适用于252097800623(这是素数(,但这是因为他们正在将其解析为int。当我在这些代码中将所有int改为long-long时,他们现在返回NO。我还根据另一篇文章编写了自己的代码,当我用11、101、17甚至1000000007这样的小数字测试它时,它也起了作用,但对2520978006 23这样的大数字进行了测试。我想写一个适用于从1到10^18的所有整数的程序

编辑

这是修改后的代码表第一个链接:

/* 
* C++ Program to Implement Milong longer Rabin Primality Test
*/
#include <iostream>
#include <cstring>
#include <cstdlib>
using namespace std;

/* 
* calculates (a * b) % c taking long longo account that a * b might overflow 
*/
long long mulmod(long long a, long long b, long long mod)
{
long long x = 0,y = a % mod;
while (b > 0)
{
if (b % 2 == 1)
{    
x = (x + y) % mod;
}
y = (y * 2) % mod;
b /= 2;
}
return x % mod;
}
/* 
* modular exponentiation
*/
long long modulo(long long base, long long exponent, long long mod)
{
long long x = 1;
long long y = base;
while (exponent > 0)
{
if (exponent % 2 == 1)
x = (x * y) % mod;
y = (y * y) % mod;
exponent = exponent / 2;
}
return x % mod;
}

/*
* Milong longer-Rabin primality test, iteration signifies the accuracy
*/
bool Miller(long long p,long long iteration)
{
if (p < 2)
{
return false;
}
if (p != 2 && p % 2==0)
{
return false;
}
long long s = p - 1;
while (s % 2 == 0)
{
s /= 2;
}
for (long long i = 0; i < iteration; i++)
{
long long a = rand() % (p - 1) + 1, temp = s;
long long mod = modulo(a, temp, p);
while (temp != p - 1 && mod != 1 && mod != p - 1)
{
mod = mulmod(mod, mod, p);
temp *= 2;
}
if (mod != p - 1 && temp % 2 == 0)
{
return false;
}
}
return true;
}
//Main
int main()
{
long long iteration = 5;
long long num;
cout<<"Enter long longeger to test primality: ";
cin>>num;
if (Miller(num, iteration))
cout<<num<<" is prime"<<endl;
else
cout<<num<<" is not prime"<<endl;
return 0;
}

您在问题中复制的第一个链接中的代码,将(坏的(宏ll替换为long long(尽管这会产生完全相同的预处理代码(,并将所有int替换为long long,已经因大值而中断,请参阅此处的编译器资源管理器。我强迫编译器在编译时为252097800623计算Miller函数,用一个随机数123456代替对rand()的调用。

正如你所看到的,编译器告诉我它不能这样做,因为程序中存在整数溢出。特别是:

<source>:133:17: error: static_assert expression is not an integral constant expression
static_assert(Miller(num, iteration));
^~~~~~~~~~~~~~~~~~~~~~
<source>:62:12: note: value 232307310937188460801 is outside the range of representable values of type 'long long'
y = (y * y) % mod;
^
<source>:104:14: note: in call to 'modulo(123457, 63024450155, 252097800623)'
ll mod = modulo(a, temp, p);
^
<source>:133:17: note: in call to 'Miller(252097800623, 5)'
static_assert(Miller(num, iteration));

正如您所看到的,long long太小了,无法处理该算法如此大的输入。