【洛谷】P11169 「CMOI R1」Bismuth / Linear Sieve 的题解
题解
赛时没调出来,血亏。
先把题目里面的伪代码变成 C++ 代码
#include <bits/stdc++.h>
using namespace std;
unsigned long long n;
bool isNotPrime[10000005];
int primes[10000005];
int main() {
cin >> n;
for (int i = 1; i <= n; i++) {
isNotPrime[i] = false;
}
long long cntp = 0;
long long counter = 0;
for (int i = 2; i <= n; i++) {
if (!isNotPrime[i]) {
cntp++;
primes[cntp] = i;
}
for (int j = 1; j <= cntp; j++) {
if (i * primes[j] > n)
break;
isNotPrime[i * primes[j]] = true;
if (i % primes[j] > 0)
break;
counter++;
}
}
cout << cntp << " " << counter;
return 0;
}
第一个数相信大家很快就能看出来,其实就是 n ÷ 2 n \div 2 n÷2 后,向上取整就行了。特别注意的是,当 n = 1 n = 1 n=1 的时候,要输出 0 0 0,就很神奇啊。
第二个数就比较困难了,赛时推不出来,也是赛后看题解,才明白的。
第二个数统计的是被重复筛的个数。如果一个数的“质”因数越多其被重复筛的次数越多。还有要注意的是,实际统计答案是因为伪代码统计的“质数”并非真正的质数,所以能被有些数整除可能已经被满足了。
代码
#include <bits/stdc++.h>
#define lowbit(x) x & (-x)
#define endl "\n"
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
namespace fastIO {
inline int read() {
register int x = 0, f = 1;
register char c = getchar();
while (c < '0' || c > '9') {
if(c == '-') f = -1;
c = getchar();
}
while (c >= '0' && c <= '9') x = x * 10 + c - '0', c = getchar();
return x * f;
}
inline void write(int x) {
if(x < 0) putchar('-'), x = -x;
if(x > 9) write(x / 10);
putchar(x % 10 + '0');
return;
}
}
using namespace fastIO;
ll gcd(ll a, ll b) {
if(b) while((a %= b) && (b %= a));
return a + b;
}
ll cnt, n, ans, a = 2, b = 2;
int main() {
//freopen(".in","r",stdin);
//freopen(".out","w",stdout);
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin >> n;
while(n / a / b) {
ans += n / a / b;
if(a == 2) {
a = 3;
}
else {
a += 2;
}
b = b * a / __gcd(b, a);
}
cout << (n + 1) / 2 - (n == 1) << " " << ans;
return 0;
}