zoukankan      html  css  js  c++  java
  • C++实现的Miller-Rabin素性测试程序

    Miller-Rabin素性测试算法是概率算法,不是确定算法。然而测试的计算速度快,比较有效,被广泛使用。

    另外一个值得介绍的算法是AKS算法,是三位印度人发明的,AKS是他们的姓氏首字母。ASK算法是确定算法,其时间复杂度相当于多项式的,属于可计算的算法。

    代码来自Sanfoundry的C++ Program to Implement Miller Rabin Primality Test

    源程序如下:

    /* 
     * C++ Program to Implement Miller Rabin Primality Test
     */
    
    #include <iostream>
    #include <cstring>
    #include <cstdlib>
    #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 iteration = 5;
        ll num;
    
        cout<<"Enter integer to test primality: ";
        cin>>num;
    
        if (Miller(num, iteration))
            cout<<num<<" is prime"<<endl;
        else
            cout<<num<<" is not prime"<<endl;
    
        return 0;
    }

  • 相关阅读:
    jvm理论-运行时数据区
    java nio-理解同步、异步,阻塞和非阻塞
    真正的mybatis_redis二级缓存
    扩展 DbUtility (1)
    DbUtility v3 背后的故事
    DbUtility v3
    Jumony Core 3,真正的HTML引擎,正式版发布
    新项目,WebTest
    面试经验总结,每个求职者应该具有的职业素养
    mkdir()提示No such file or directory错误的解决方法
  • 原文地址:https://www.cnblogs.com/tigerisland/p/7564853.html
Copyright © 2011-2022 走看看