求助Miller-Rabin
  • 板块学术版
  • 楼主sjwhsss
  • 当前回复2
  • 已保存回复2
  • 发布时间2025/6/30 18:58
  • 上次更新2025/7/1 14:39:18
查看原帖
求助Miller-Rabin
982518
sjwhsss楼主2025/6/30 18:58

rt,学校OJ上TLE,n100,x1018n\le100,x\le10^{18}。就算没有用龟速乘或者int128也会TLE,可以过LOJ上的。我是不是哪里写假了?

#include <bits/stdc++.h>
#define ll __int128
#define Int __int128
using namespace std;
const int maxn = 1e7+5;
int ans , n , p[13]={2,3,5,7,11,13,17,19,23,29,31,37};
ll qmul(ll a , ll b , ll mod)
{
	return a*b%mod;
}
int cnt;
ll read()
{
	char ch=getchar();ll x=0;
	while(isdigit(ch) ^ 1){if (ch==-1)exit(0);ch=getchar();}
	while(isdigit(ch))x=(x<<1)+(x<<3)+(ch^48),ch=getchar();
	return x;
}
Int qpow(Int a , Int b , Int n)
{
	Int res = 1;
	while(b)
	{
		if (b&1)res=qmul(res , a , n);
		a=qmul(a , a , n);
		b>>=1;
	}
	return res;
}
bool MillerRabin(Int a , Int n)
{
	ll r = 0 , b = n - 1;
	if (qpow(a , b , n) != 1)return 0;
	while(!(b&1))r++,b>>=1;
	Int c = 0;
	if ((c = qpow(a , b , n)) == 1)return 1;
	for (int i = 0; i < r; i++)
	{
		if (c == n - 1)return 1;
		c=qmul(c , c , n);
	}
	return 0;
}
bool isPrime(ll n)
{
	if (n == 2)return 1;
	if (n == 1 || !(n&1))return 0;
	for (int i = 0; i < 12; i++)
	{
		if (n == p[i])return 1;
		if (n % p[i] == 0)return 0;
		if (MillerRabin(p[i] , n)^1)return 0;
	}
	return 1;
}
int main()
{
	scanf("%d" , &n);
	for (int i = 1 , x; i <= n; i++)x=read(),ans+=isPrime(x);
	printf("%d\n" , ans);
	return 0;
}
2025/6/30 18:58
加载中...