筛法思想的题目

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

这种筛法的思想。

我们正着想对于每一个 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;
}
相关推荐
PXM的算法星球22 分钟前
【leetcode】3524 求出数组的X值1
算法·leetcode·职场和发展
老胖闲聊1 小时前
Python PyAutoGUI库【GUI 自动化库】深度解析与实战指南
python
椰羊~王小美3 小时前
LeetCode -- Flora -- edit 2025-04-27
算法·leetcode·职场和发展
GeekABC3 小时前
FastAPI系列06:FastAPI响应(Response)
开发语言·python·fastapi·web
fen_fen3 小时前
Python3:Jupyter Notebook 安装和配置
ide·python·jupyter
charade3124 小时前
【C语言】内存分配的理解
c语言·开发语言·c++
float_六七4 小时前
Python语言基础知识详解:分支结构控制语句
python
声声codeGrandMaster4 小时前
django之优化分页功能(利用参数共存及封装来实现)
数据库·后端·python·django
缘友一世4 小时前
从线性回归到逻辑回归
算法·逻辑回归·线性回归
Johny_Zhao4 小时前
OpenStack 全套搭建部署指南(基于 Kolla-Ansible)
linux·python·信息安全·云计算·openstack·shell·yum源·系统运维