跳到正文

算法·理论

简单数论

liminghao2024约 1 分钟
原文

这是 2025年12月3日 存档的第 1 版,不是当前版本。查看当前版本

文章信息与版本

文章信息

发布
2025年8月14日
收录
2025年12月12日
更新
2026年11月14日
篇幅
约 1 分钟

版本

  1. v2当前
  2. v1

线性求欧拉函数

C++
#include<bits/stdc++.h>
using namespace std;
long long n,m,T,prime[2001010],phi[2001010],a[2010100];
const int N=101010;
int main(){
	for(int i=2;i<=N;i++){
		if(!a[i]){
			prime[++prime[0]]=i;
			phi[i]=i-1;
		}
		for(int j=1;j<=prime[0]&&prime[j]*i<=2e6;j++){
			a[i*prime[j]]=1;
			if(i%prime[j]==0){
				phi[i*prime[j]]=phi[i]*prime[j];
				break;
			}
			phi[i*prime[j]]=phi[i]*(prime[j]-1);
		}
	}
	return 0;
}

单个求欧拉函数

C++
#include<bits/stdc++.h>
#define int long long 
using namespace std;
int n
int phi(int x){
	int ans=x;
	for(int i=2;i*i<=x;i++){
		if(x%i==0)ans=ans/i*(i-1);
		while(x%i==0)x/=i;
	}if(x>1)ans/x*(x-1);
	return ans;
}
int main(){
	cin>>n;
	cout<<phi(n);
    return 0;
}