Big primes loop with GMP library C++

冷暖自知 提交于 2021-02-10 15:51:21

问题


It's the first time that I use the gmp library, so I'm really lost, I've found a code implementing the "miller rabin primality test" in c++ but I wanted to be able to apply it to integers with arbitrary precision so I installed the GMP library.

The problem is, I've got no idea of how GMP library actually works (I've read trough a few pages of the manual but I understand very little about it also since I haven't even studied object oriented programming), I want to adapt the primality test to be able to input integers 'num' of about 1000-2000 digits, here's the code:

#include <iostream>
#include <cstring>
#include <cstdlib>
#include <gmpxx.h>
#include <gmp.h>
#define ll long long
using namespace std;
/* 
 * calculates (a * b) % c taking into account that a * b might overflow 
 */
ll mulmod(ll a, ll b, ll mod)
{
    ll 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
 */
ll modulo(ll base, ll exponent, ll mod)
{
    ll x = 1;
    ll y = base;
    while (exponent > 0)
    {
        if (exponent % 2 == 1)
            x = (x * y) % mod;
        y = (y * y) % mod;
        exponent = exponent / 2;
    }
    return x % mod;
}
/*
 * Miller-Rabin primality test, iteration signifies the accuracy
 */
bool Miller(ll p,int iteration)
{
    if (p < 2)
    {
        return false;
    }
    if (p != 2 && p % 2==0)
    {
        return false;
    }
    ll s = p - 1;
    while (s % 2 == 0)
    {
        s /= 2;
    }
    for (int i = 0; i < iteration; i++)
    {
        ll a = rand() % (p - 1) + 1, temp = s;
        ll 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()
{
    int w=0;
    int iteration = 5;
    mpz_t num;
    cout<<"Enter integer to loop: ";
    cin>>num;
    if (num % 2 == 0)
    num=num+1;
    while (w==0) {
    if (Miller(num, iteration)) {
        cout<<num<<" is prime"<<endl;
        w=1;
    }
    else    
        num=num+2;
    }
    system ("PAUSE");
    return 0;
}

(If I define num to be 'long long' the program works just fine, but I have no idea how I should adapt the whole thing to "match" num being defined as 'mpz_t' instead, also I didn't mention it but the program basically takes an initial integer value and loops it by adding 2 if the integer is composite until it becomes a prime number)

来源:https://stackoverflow.com/questions/52767319/big-primes-loop-with-gmp-library-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!