【洛谷】P11169 「CMOI R1」Bismuth / Linear Sieve 的题解

【洛谷】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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值