关于 Miller-Rabin
  • 板块学术版
  • 楼主Pursuewind
  • 当前回复2
  • 已保存回复2
  • 发布时间2024/1/12 22:50
  • 上次更新2024/1/13 11:17:35
查看原帖
关于 Miller-Rabin
664236
Pursuewind楼主2024/1/12 22:50

为什么有人说这个代码的复杂度是 O((log⁡n)3)O((\log n)^3)?

#include <bits/stdc++.h>
using namespace std;
#define int long long
int m;
int qpow(int a, int b, int mod)
{
	int res = 1, base = (a %= mod);
	while (b)
	{
		if (b & 1) res = res * base % mod;
		base = base * base % mod;
		b >>= 1;
	}
	return res;
}
bool witness(int a, int n) //素性测试,返回真表示 n 为合数
{
	int u = n - 1;
	int t = 0;
	while (u & 1 == 0)
	{
		u >>= 1;
		t ++;
	}
	int x1, x2;
	x1 = qpow(a, u, n);
	for (int i = 1; i <= t; i ++)
	{
		x2 = qpow(x1, 2, n);
		if (x2 == 1 && x1 != n - 1) return 1;
		x1 = x2;
	}
	if (x1 != 1) return 1;
	return 0;
}
int miller_rabin(int n, int s) //对 n 做 s 次测试 
{
	if (n < 2) return 0; 
	if (n == 2) return 1;
	if (n & 1 == 0) return 0;
	for (int i = 0; i < s && i < n; i ++)
	{
		int a = rand() % (n - 1) + 1;
		if (witness(a, n)) return 0;
	}
	return 1;
}
void solve()
{
	int n;
	cin >> n;
	if (miller_rabin(n, 25)) puts("YES");
	else puts("NO");
}
signed main()
{
	int t;
	cin >> t;
	while (t --) solve();
	return 0;
}

这不是 O((log⁡n)2)O((\log n)^2) 吗???

2024/1/12 22:50
加载中...