【发布时间】:2019-10-31 15:11:39
【问题描述】:
我正在尝试编写 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。当我在此代码中将所有整数更改为 long long 时,它们现在返回 NO。我还根据另一篇文章编写了自己的代码,当我用 11、101、17 甚至 1000000007 之类的小数字测试它时它工作了,但在 252097800623 等更大的数字上崩溃了。我想编写适用于所有整数的程序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;
}
【问题讨论】:
-
在第一个链接中,所有相关内容都已经是
long long。 -
当我全部更改为 long long 时它不会
-
请编辑您的问题并包含您正在运行的代码的确切版本,而不是链接到在文章/博客条目中发布一些代码并粗略描述您的修改的一堆不同网站那是行不通的。
标签: c++ algorithm number-theory