百万小小兵

版权声明:写得不好,随便转载,但请注明出处,感激不尽 https://blog.csdn.net/xyc1719/article/details/87528551

【简要题意】求1-n中与n不互质的数的个数。 n<=1e8

【分析】
当然是求 φ ( n ) \varphi(n) 然后相减啦。。。。利用公式
φ ( n ) = n ( 1 1 p 1 ) ( 1 1 p 2 ) ( 1 1 p 3 ) \varphi(n)=n(1-\frac{1}{p_1})(1-\frac{1}{p_2})(1-\frac{1}{p_3})······

然后通过计算得知n至多有9个不同的质因数,所以也可以直接容斥原理。

【code】
只有容斥的部分

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
int n,ans;
int p[50],cnt=0;
void dfs(int u,int chs,int num){
	if(u>cnt){
		if(!chs) return ;
		if(chs&1)ans+=n/num;
		else ans-=n/num;
		return ;
	}
	dfs(u+1,chs+1,num*p[u]);
	dfs(u+1,chs,num);
}
int main(){
	freopen("million.in","r",stdin);
	freopen("million.out","w",stdout);
	cin>>n;int x=n;
	for(int i=2;i*i<=x;i++){
		if(x%i==0){
			p[++cnt]=i;
			while(x%i==0) x/=i;
		}
	}
	if(x>1) p[++cnt]=x;
	dfs(1,0,1);
	cout<<ans<<endl;
	return 0;
}

猜你喜欢

转载自blog.csdn.net/xyc1719/article/details/87528551