觉得自己的通过代码耗时太长,查看了一位叫做朱伟滔同学的代码,发现了叫做米勒拉宾素数测试的一种高效率素数测试算法。
查看了一篇热搜文章,包含费马定理,合数判定,快速幂等知识,反复思考,还是觉得记住代码最为简单,以下是nowcoder上的题目通过代码。
(他的码风和我好像)
#include<bits/stdc++.h>
#include<math.h>
using namespace std;
typedef long long ll;
ll t, n;
long long qpow(int a, int b, int r)//快速幂
{
long long ans = 1, buff = a;
while (b)
{
if (b & 1)ans = (ans * buff) % r;
buff = (buff * buff) % r;
b >>= 1;
}
return ans;
}
bool Miller_Rabbin(int n, int a)//米勒拉宾素数测试
{
int r = 0, s = n - 1, j;
if (!(n % a))
return false;
while (!(s & 1)) {
s >>= 1;
r++;
}
long long k = qpow(a, s, n);
if (k == 1)
return true;
for (j = 0; j < r; j++, k = k * k % n)
if (k == n - 1)
return true;
return false;
}
bool IsPrime(int n)//判断是否是素数
{
if (n < 2) {
return false;
}
int tab[] = { 2,3,5,7,11,13,17,19,23,29 }; // 测试素数数组
for (int i = 0; i < 10; i++)
{
if (n == tab[i])
return true;
if (!Miller_Rabbin(n, tab[i]))
return false;
}
return true;
}
int main(){
cin >> t;
while(t--){
cin >> n;
if(n < 6){
cout << n << '\n';
}
else{
while(!IsPrime(n)){
n--;
}
cout << n << '\n';
}
}
return 0;
}