【模板】Miller Rabin

#include<bits/stdc++.h>

#define int long long

const int Prime[10] = {2, 3, 5, 7, 11, 13, 17} ;

int x;

inline int read() {
	int x = 0, k = 1; char c = getchar();
	for (; c < 48 || c > 57; c = getchar()) k ^= (c == '-');
	for (; c >= 48 && c <= 57; c = getchar()) x = x * 10 + (c ^ 48);
	return k ? x : -x;
}

int GCD(int x, int y) {
	return y ? GCD(y, x % y) : x;
}

inline int ksm(int a, int b, int Mo) {
    int ans = 1;
    for (; b; b >>= 1, a = 1LL * a * a % Mo)
        if (b & 1) ans = 1LL * ans * a % Mo;
    return ans;
}

inline bool MillerRabin(int x) {
    if (x == 1) return 0;
    else if (x < 4) return 1;
    int t, k;
    for (t = x - 1, k = 0; !(t & 1); ++k, t >>= 1) ;
    for (int i = 0; i < 7 && Prime[i] <= x; i++) {
        if (Prime[i] == x)
            return 1;
        int a = ksm(Prime[i], t, x), b;
        for (int j = 1; j <= k; j++) {
            b = 1LL * a * a % x;
            if (b == 1 && a != 1 && a != x - 1)
                return 0;
            a = b;
        }
        if (a != 1)
            return 0;
    }
    return 1;
}
signed main() {
    for (int T = read(); T--; ) {
        x = read();
        if (MillerRabin(x))
            puts("Prime");
    }
}   
posted @ 2020-11-26 16:24  Trimsteanima  阅读(83)  评论(0编辑  收藏  举报
Live2D