米勒-罗宾素性检测算法模板

欢迎访问我的主页!http://godweiyang.com edited 7 年,2 月前

#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
#include <map>
#include <vector>
#include <list>
#include <set>
#include <stack>
#include <queue>
#include <deque>
#include <algorithm>
#include <functional>
#include <numeric>
#include <iomanip>
#include <limits>
#include <new>
#include <utility>
#include <iterator>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cctype>
#include <cmath>
#include <ctime>
using namespace std;

typedef long long ll;

ll prime[5] = {2, 3, 5, 233, 331};

ll pow_mod(ll a, ll n, ll mod)
{
    ll ret = 1;
    while (n)
    {
        if (n&1)
            ret = ret * a % mod;
        a = a * a % mod;
        n >>= 1;
    }
    return ret;
}

int isPrime(ll n)
{
    if (n < 2 || (n != 2 && !(n&1)))
        return 0;
    ll s = n - 1;
    while (!(s&1))
        s >>= 1;
    for (int i = 0; i < 5; ++i) 
    {
        if (n == prime[i])
            return 1;
        ll t = s, m = pow_mod(prime[i], s, n);
        while (t != n-1 && m != 1 && m != n-1)
        {
            m = m * m % n;
            t <<= 1;
        }
        if (m != n-1 && !(t&1))
            return 0;
    }
    return 1;
}

int main()
{
    ll n;
    while (cin >> n)
        printf("%s\n", isPrime(n)?"yes":"no");
    return 0;
}

Comments