c++ - Miller-Rabin 素性测试给出了错误的答案

标签 c++ primes primality-test

我正在尝试制作 RSA 算法。为此,我需要 rabin-miller+witness+modular exponentiation(至少我需要使用它)。当我生成随机数以检查 rabin miller 是否为素数时,问题就来了,结果是非素数对于 rabin-miller 算法是素数。有人可以帮我看看我失败的地方吗? 提前致谢。

int mod_exp(int a, int b, int n){

    int d = 1,i,j=0;
    int binary[15];
    for(i=0;i<=15;i++){
        binary[i] = -1;
    }
    i=0;
    do{
        binary[i]=(b%2);

            if((b%2)==1)
                b=(b-1)/2;
            else
                b=b/2;
        i++;
    }while(b!=0);

    do{
        d= (d*d)%n;
        if(binary[i]==1)
            d=(d*a)%n;
        i--;
    }while(i!=-1);
    return d;

}

bool wittness(int a, int n){
    int u=n-1,k=0;
    long x, temp;
    while(u%2== 0 ){
        u=u/2;
        k++;
    }
    x=mod_exp(a,u,n);
    for(int i=1;i<=k;i++){
        temp=x;
        cout<< "primera x:"<<x<<endl;
        x=long(x*x)%n;
        cout<< "segunda x:"<<x<<endl;
        if(x==1 && temp!=1 && temp != n-1)
            return true;

    }
    if(x!=1)
        return true;
    return false;

}


bool miller_rabin(int n, int s){

    int a,j;
    srand(time(NULL));

    for(j = 0; j<=s;j++){

       a=rand()%s+1;
       if(!wittness(a,n))
        return false;
    }
    return true;
}

最佳答案

我没有查看所有代码,但您的 mod_exp 函数肯定不正确。 (d*d)%n(d*a)%n 这两个表达式都容易溢出,如果发生溢出,您将得到不正确的结果。

关于c++ - Miller-Rabin 素性测试给出了错误的答案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34256244/

相关文章:

C++ 无法循环指向 vector 的 vector 的指针

c++ - 如何使用 C/C++ 和 Boost Asio 优化客户端/服务器

c++ - 通过外部分配的数据调用 Eigen GEMM

c++ - 生成一个数的所有因数分解

algorithm - 这个筛子真的是 O(n) 吗?

algorithm - 确定给定数字是否是haskell中的素数

c++ - boost 是否有一个 "compact optional",其中存在由类型的特殊值编码?

javascript - 寻找第 10001 个素数 - 欧拉计划

c - 在 3 位数字上使用逻辑或关系运算符进行素数测试

algorithm - 这种素性测试算法的时间复杂度?