【LOJ143】素数判定

题面

https://loj.ac/problem/143

题解

直接$Miller$就好。

#pragma GCC optimize(2)
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#define LLL __int128
#define LL long long
#define ri int
using namespace std;

LL n,c;
const int p[10]={2,3,5,7,11,13,17,19,61,24251};

LL mul(LL a,LL b,LL n) {return ((LLL)a*b)%n;}
LL pow(LL a,LL b,LL n) {
  LL ret=1;
  for (;b;b>>=1,a=mul(a,a,n)) if (b&1) ret=mul(ret,a,n);
  return ret;
}
bool prime(LL n) {
  if (n==1) return 0;
  for (ri i=0;i<10;i++) if (n==p[i]) return 1;
  for (ri i=0;i<10;i++) if (n%p[i]==0) return 0;
  for (ri i=0;i<10;i++) {
    if (pow(p[i],n-1,n)!=1) return 0;
    LL f=n-1;
    while (1) {
      if (f&1) break;
      f>>=1;
      LL t=pow(p[i],f,n);
      if (t!=1 && t!=n-1) return 0;
      if (t==n-1) break;
    }
  }
  return 1;
}

int main() {
  while (scanf("%lld",&n)==1) if (prime(n)) puts("Y"); else puts("N");
  return 0;
}
原文地址:https://www.cnblogs.com/shxnb666/p/11385297.html