筛法思想的题目

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

这种筛法的思想。

我们正着想对于每一个 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;
}
相关推荐
weixin_4462608527 分钟前
HACO:面向动态部署环境的对冲式智能计算可靠多智能体调度框架
后端·python·flask
我的xiaodoujiao42 分钟前
API 接口自动化测试详细图文教程学习系列32--Allure测试报告2
python·学习·测试工具·pytest
fqbqrr1 小时前
2607C++,使用微软detours勾挂工具
c++
qetfw1 小时前
MXU:Tauri 2 + React 的 MaaFramework 跨平台 GUI 源码
前端·python·react.js·前端框架·开源项目·效率工具
爱刷碗的苏泓舒1 小时前
PPP-AR 中的参考星选取:数学原理、评价指标与切换处理
算法·gnss·模糊度固定·ppp-ar·星间单差·参考星·卫星端偏差
用户8356290780512 小时前
Python 实现 Excel 页面布局与打印设置自动化
后端·python
一次旅行2 小时前
Python+大模型端到端自动化日报系统
开发语言·python·自动化
天天爱吃肉82182 小时前
【电源拆解:跟着问答逐一认识开关适配器PCB元器件】
大数据·人工智能·python·功能测试·嵌入式硬件·汽车
_Jimmy_2 小时前
AI应用开发工程师面试题库
人工智能·python·深度学习·机器学习·知识图谱
用户8356290780512 小时前
Python 实现 Excel 命名范围(Named Range)的创建与管理
后端·python