Files
python/TangDou/LuoGuBook/P3601_Prepare_3.cpp
HuangHai 1f397eca87 'commit'
2025-08-30 18:35:01 +08:00

74 lines
2.5 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
LL l = 1, r = 2000000;
const int N = 1e7 + 10;
//欧拉筛[线性筛法]
int primes[N], cnt; // primes[]存储所有素数
bool st[N]; // st[x]存储x是否被筛掉
void get_primes(int n) {
for (int i = 2; i <= n; i++) {
if (!st[i]) primes[cnt++] = i;
for (int j = 0; primes[j] <= n / i; j++) {
st[primes[j] * i] = true;
if (i % primes[j] == 0) break;
}
}
}
vector<int> v[N];
int main() {
/**=====================================================***/
//计时开始
clock_t startTime = clock();
/**=====================================================***/
//1、筛出小于sqrt(r)的所有质数
get_primes(sqrt(r));
//遍历每个小质数因子
for (int i = 0; i < cnt; i++) {
int p = primes[i];
//1、利用数组下标的位移,记录数据
//2、找到大于l的第一个p的倍数,然后,每次增加p,相当于找出p的整数倍
for (LL j = ((l - 1) / p + 1) * p; j <= r; j += p)
//在每个倍数中记录下这个共同的质数因子p,比如 6里面包含2,8里面包含2,10里面包含2,相当于埃筛一次找到所有p的整数倍
v[j - l].push_back(p); //标识数组vec[j-l],也就是真实的l这个数字中,存在p这个因子。
}
//如果还存在大的质数因子
for (LL i = l; i <= r; i++) {
LL tmp = i; //将i拷贝出来给了tmp,tmp要不断的减少啦,而i要保留。
//遍历每个已经找到的因子
for (int p: v[i - l]) {
//除干净
while ((tmp % p) == 0) tmp /= p;
}
//如果还存在大的质数因子
if (tmp > 1)v[i - l].push_back(tmp);
}
//输出质数因子有哪些
for (int i = l; i <= r; i++) {
cout << i << ": ";
for (auto c:v[i - l]) cout << c << " ";
cout << endl;
}
cout << endl;
/**************************************************************/
//计时结束
clock_t endTime = clock();
cout << "The run time is: " << (double) (endTime - startTime) / CLOCKS_PER_SEC << "s" << endl;
/**=====================================================***/
//第一种方法用时:
//The run time is: 4.273s
//第二种方法用时:
//The run time is: 1.677s
return 0;
}