筛法思想的题目

这道题目比较经典,或者说这种思想比较经典。

这种筛法的思想。

我们正着想对于每一个 n 、 n − 1 、 n − 2 、 . . . 、 2 、 1 n、 n-1、n-2、...、2、1 n、n−1、n−2、...、2、1都分解一遍质因数显然是来不及的时间复杂度达到 O ( n n ) O(n \sqrt{n}) O(nn )

我们考虑对于每一个1e6以内的质因数的个数

跑了一下程序是 78498 78498 78498个

素数定理告诉我们不超过x的素数近似有 x l n x \frac{x}{lnx} lnxx个

对于每一个质因子我们看一下那些数有一个这个质因子,那些数有两个,那些数有3个这个每次是平方的增长很快

时间复杂度: O ( n l o g x ∗ l o g n ) O(\frac{n}{logx} * logn) O(logxn∗logn)近似 O ( n ) O(n) O(n)

cpp 复制代码
#include <bits/stdc++.h> 
#define int long long
#define rep(i,a,b) for(int i = (a); i <= (b); ++i)
#define fep(i,a,b) for(int i = (a); i >= (b); --i)
#define pii pair<int, int>
#define pll pair<long long, long long>
#define ll long long
#define db double
#define endl '\n'
#define x first
#define y second
#define pb push_back

using namespace std;

const int N=1e6+10,mod=1e9+7;
int vis[N];
vector<int>p;
void solve()
{
	int n;cin>>n;
	auto get=[&](int x){
		rep(i,2,x){
			if(!vis[i])	p.pb(i);
			for(int j=0;p[j]*i<=x;++j){
				vis[i*p[j]]=1;
				if(i%p[j]==0)	break;
			}
		}
	};
	get(1e6);
	cout<<p.size()<<endl;
	int res=0;
	vector<int>ans(n+1);
	rep(i,0,p.size()-1){
		for(int j=p[i];j<=n;j*=p[i]){
			ans[i]+=n/j;
			res+=n/j;
		}
	}
	rep(i,0,p.size()-1){
		cout<<p[i]<<' '<<ans[i]<<endl;
	}
	return;
}

signed main(){
	ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
//   	freopen("1.in", "r", stdin);
  	int _;
//	cin>>_;
//	while(_--)
	solve();
	return 0;
}
相关推荐
BK贝壳3 小时前
bool-hybrid-array 的 GPU_opt 与 cjx:一个没显卡就报错的开关,一个把 800 字压到 96 字节的编码
python
BD_Marathon7 小时前
安装Jupyter notebook
ide·python·jupyter
Zlzxzw7 小时前
End-to-End Autonomous Generation of Human Assembly Plans
python
Wellijohn8 小时前
2000 个请求、30% 失败率:我把 Python 批量并发的限流和重试参数算了一遍
后端·python·性能优化
小飞在努力10 小时前
【实现负载均匀在线判题③】从零散模块到统一,编译运行全链路封装
c语言·开发语言·c++·笔记
Logintern0910 小时前
deep agents 多智能体模式——规划与委派
python·langchain
2601_9679801111 小时前
Python 办公自动化合集 ⑰:Excel自动计算——总和/平均分/最大值
python·pycharm·办公自动化·数据处理·excel自动计算
民乐团扒谱机13 小时前
【超详细】基频音高提取算法之SWIPE 算法深度解析:频谱匹配的精度极限与工程边界
人工智能·算法
饮水桶_T13 小时前
C++ stack & queue复习笔记
开发语言·笔记·算法