关于1到n所有数的lcm、

版权声明:吸猫大法、 https://blog.csdn.net/sasuke__/article/details/79876429

首先我们来求一个简单的n的范围是1 <= n <= 1e5,答案去模一个数

一个很简单的思想就是对1到n内直接做一次lcm,但答案会超过long long,取模条件下是不对的

所以我们考虑分解一下,对于x、y两个数求lcm 等于 x / gcd(x,y) * y,当我们将x、y进行素数分解后,我们可以知道gcd(x, y)实际就是 x的素数 并 y的素数,我们可以假设某个素数在x中有a个 y中有b个, 那么在gcd(a, b)中有 min(a, b)个,从而我们可以知道 这个素数在 x / gcd(x,y) * y 中有 max(a, b)个,所以我们可以通过这种方法来求

ct[i]是统计素数i有多少个,num[i]记录素数分解后的素数是谁,p[i]记录num[i]这个素数出现的次数

#include <cstdio>
#include <cstring>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <iostream>
#include <algorithm>
#include <sstream>
#include <string>
#include <vector>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <utility>
#include <bitset>
#include <unistd.h>

using namespace std;

#define LL long long
#define pb push_back
#define mk make_pair
#define pill pair<int, int>
#define mst(a, b) memset(a, b, sizeof a)
#define lson (rt << 1)
#define rson ((rt << 1) | 1)

const int qq = 1e5 + 300;
const int INF = 1e9 + 10;
const int MOD = 987654321;
int ct[qq], num[qq], p[qq];

LL quickPow (LL a, LL b) {
	LL ans = 1;
	while (b > 0) {
		if (b & 1)	ans = ans * a % MOD;
		a = a * a % MOD;
		b >>= 1;
	}
	return ans;
}

int main() {
	int n;	scanf("%d", &n);
	for (int i = 2; i <= n; ++i) {
		int x = i;
		int cnt = 0;
		for (int j = 2; j * j <= x; j++) {
			if (x % j == 0) {
				num[cnt] = j;
				p[cnt] = 0;
				while (x % j == 0) {
					p[cnt]++;
					x /= j;
				}
				cnt++;
			}
		}
		if (x > 1) {
			num[cnt] = x;
			p[cnt++] = 1;
		}
		for (int j = 0; j < cnt; ++j) {
			ct[num[j]] = max(ct[num[j]], p[j]);
		}
	}
	LL ans = 1;
	for (int i = 2; i <= 100000; ++i) {
		if (ct[i] > 0) {
			ans = ans * quickPow(i, ct[i]) % MOD;
		}
	}
	printf("%lld\n", ans);
	return 0;
} 




但是如果n达到1e8,并且要求询问q次(1 <= q <= 1e3)的话,上面那种方法就不适用了

参考:传送门

位图:传送门

关于位图解释一下

const int SHIFT = 5;
const int RADIX = (1 << SHIFT) - 1;

inline void SetBit (int x) {
flag[x >> SHIFT] |= (1 << (x & RADIX));
}

关于这段代码,我们知道x >> SHIFT, 其实就是x / 32,这个没问题

RADIX = (1 << SHIFT) - 1,这段代码其实是 1 + 2 + 4 + 8 + 16的结果也就是31

x & 31,也就是 x % 32的结果


还有关于这段代码的骚操作

int m = (int)pow(n + 0.9, 1.0 / cnt);

之前觉得挺奇怪的,想通了真的觉得真是骚操作

可以想像 n^1 , n^(1/2), n^(1/3) ......, 代表 n以内的数的1次方小于等于n的最大数,n以内的数的2次方小于等于n的最大数,n以内的数的3次方小于等于n的最大数......

挺绕的,再结合一下sum[]数组基本就能看明白这整个过程,挺厉害的操作阿 仰慕QAQ

猜你喜欢

转载自blog.csdn.net/sasuke__/article/details/79876429