zoukankan      html  css  js  c++  java
  • [模板] Miller-Rabin 素数测试

    细节挺多的。。

    #include<iostream>
    #include<cstdlib>
    #include<cstdio>
    #include<ctime>
    
    using namespace std;
    
    typedef long long ll;
    
    ll mul(ll a,ll b,ll mod) {
        ll ret = 0ll;
        a %= mod;
        while( b ) {
            if ( b & 1ll ) ret = ( ret + a ) % mod, b--;
            b >>= 1ll;
            a = ( a + a ) % mod;
        }
        return ret;
    }
    
    ll qpow(ll a,ll b,ll mod) {
        ll ret = 1ll;
        a %= mod;
        while( b ) {
            if ( b & 1ll ) ret = mul(ret,a,mod),b--;
            b >>= 1ll;
            a = mul(a,a,mod);
        }
        return ret;
    }
    
    ll ter[15]= {0,2,3,5,7,11,13,17,19,23,29};
    const int TOP=10;
    bool Miller_Rabin(ll n) {
        if ( n==2ll||n==3ll ) return true;
        if ( !( n & 1ll ) ) return false;
        ll d = n - 1ll;
        int s = 0;
        while( !( d & 1ll ) ) ++s, d>>=1ll;
        for(int i=1; i<=TOP; i++) {
            ll a = ter[i];
            if(a>=n) return true;
            ll x = qpow(a,d,n);
            ll y = 0ll;
            for(int j=0; j<s; j++) {
                y = mul(x,x,n);
                if ( 1ll == y && 1ll != x && n-1ll != x ) return false;
                x = y;
            }
            if ( 1ll != y ) return false;
        }
        return true;
    }
    
    int main() {
        ll x;
        while(cin>>x) {
            Miller_Rabin(x)?cout<<"YES
    ":cout<<"NO
    ";
        }
        return 0;
    }

    本文来自博客园,作者:GhostCai,转载请注明原文链接:https://www.cnblogs.com/ghostcai/p/9253181.html

  • 相关阅读:
    C#进阶-Linq-join
    C#进阶-Linq
    C#-string-stringBuilder
    C#-继承-多态
    Spring基础
    JQuery基本操作
    Oracle数据库基础操作
    AJAX前端后端
    AJAX异步提交(前端)
    js基本操作
  • 原文地址:https://www.cnblogs.com/ghostcai/p/9253181.html
Copyright © 2011-2022 走看看