标签:思路 std 需要 mat return 范围 strong include 代码
给定一个范围N,你需要处理M个某数字是否为质数的询问(每个数字均在范围1-N内)
费马小定理: n是一个奇素数,a是任何整数(\(1≤ a≤n-1\)) ,则\(a^{p-1}≡1(mod\ p)\)。
推论:如果n是一个奇素数,则方程\(x^2 ≡ 1 (mod\ n)\)只有±1两个解。
#include <cstdio>
using namespace std;
const int t[5] = {0, 2, 7, 61};
int n, m, x;
int ksm(int a, int r, int mod)
{
if (r == 0)
return 1;
if (r == 1)
return a;
int x = ksm(a, r >> 1, mod) % mod;
if (r & 1)
return ((long long) x * x * a) % mod;
else return ((long long) x * x) % mod;
}
bool mr(int x)
{
if (x == 1)
return 0;
int cnt = 0, p1 = x - 1;
while (p1 % 2 == 0)
{
++cnt;
p1 /= 2;
}
for (int i = 1; i <= 3; ++i)
{
if (x == t[i])
return 1;
int xx = ksm(t[i], p1, x);
if (xx % x != 1 && xx % x != x - 1)
{
bool flag = 0;
for (int j = 1; j <= cnt; ++j)
{
xx = (long long) xx * xx % x;
if (xx == x - 1)
{
flag = 1;
break;
}
}
if (!flag)
return 0;
}
}
return 1;
}
int main()
{
scanf("%d%d", &n, &m);
for (int i = 1; i <= m; ++i)
{
scanf("%d", &x);
if (mr(x)) puts("Yes");
else puts("No");
}
}
标签:思路 std 需要 mat return 范围 strong include 代码
原文地址:https://www.cnblogs.com/xuyixuan/p/9425056.html