You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

74 lines
2.5 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

#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里面包含28里面包含210里面包含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;
}