哪位帅哥美女帮我看看12.23小白赛的质数王国,谢谢了
189查看
#笔经面经
| 关注
代码没注释看着脑壳有点晕,判素数加查询可以做。在想筛法能不能优化算法

回复
以下是我的代码,可以参考一下:
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
// 判断一个数是否为质数
bool is_prime(LL n) {
if (n <= 1) return false;
if (n == 2) return true;
for (LL i = 2; i <= n / i; i++) {
if (n % i == 0)
return false;
}
return true;
}
// 计算给定数字到最近的质数的距离
LL add(LL x) {
// 如果是素数返回 0
if(is_prime(x)) {
return 0;
}else {
LL left = x - 1, right = x + 1;
while (!is_prime(left)) left--; // 找到比x小的最大质数
while (!is_prime(right)) right++; // 找到比x大的最小质数
return min(x - left, right - x); // 返回距离较小的值
}
}
int main() {
LL n;
cin >> n;
LL a[n];
// 结果答案
LL res = 0;
for(int i = 0; i < n; i++) {
cin >> a[i];
// 以下特判是为了优化算法
if (a[i] == 0) {
res += 2;
} else if (a[i] == 1) {
res += 1;
} else {
res += add(a[i]);
}
}
cout << res << endl;
return 0;
}
/* 话说如果用筛法能不能优化算法??? */
copy

回复
你的回复
请
登录
后回复