求助 Miller Rabin
查看原帖
求助 Miller Rabin
482728
Engulf楼主2023/1/11 19:59

Miller Rabin 写错了吗,一直 TLE

#include <bits/stdc++.h>
using namespace std;

typedef long long LL;
typedef pair<int, int> PII;

const int inf = 0x3f3f3f3f;
const LL infLL = 0x3f3f3f3f3f3f3f3fLL;

namespace Miller_Rabin
{
#define int __int128
	LL rnd(LL l, LL r)
	{
		static mt19937 rng(time(0));
		uniform_int_distribution<LL> range(l, r);
		return range(rng);
	}
	int qpow(int a, int b, int mod)
	{
		int res = 1;
		while (b)
		{
			if (b & 1) res = res * a % mod;
			a = a * a % mod;
			b >>= 1;
		}
		return res;
	}
	bool isprime(int p)
	{
		if (p <= 2 || (~p & 1)) return p == 2;
		int k = 0, t = p - 1;
		while (~t & 1)
			k ++ , t >>= 1;
		for (int i = 0; i < 5; i ++ )
		{
			int a = qpow(rnd(2, p - 1), t, p), v;
			for (int j = 1; j <= k; j ++ )
			{
				v = a * a % p;
				if (v == 1 && a != 1 && a != p - 1)
					return false;
				a = v;
			}
			if (a != 1)
				return false;
		}
		return true;
	}
#undef int
};
using namespace Miller_Rabin;

int main()
{
	int l, r;
	while (cin >> l >> r)
	{
		int c1 = 0, c2 = inf, d1 = 0, d2 = 0;
		int last = 0;
		for (int i = l; i <= r; i ++ )
		{
			if (!isprime(i)) continue;
			if (!last) last = i;
			else
			{
				if (i - last < c2 - c1) c1 = last, c2 = i;
				if (i - last > d2 - d1) d1 = last, d2 = i;
				last = i;
			}
		}
		if (!c1 && c2 == inf) puts("There are no adjacent primes.");
		else printf("%d,%d are closest, %d,%d are most distant.\n", c1, c2, d1, d2);
	}
	return 0;
}
2023/1/11 19:59
加载中...