ZZW's Blog

Step by step!


  • 首页

  • 关于

  • 标签12

  • 分类6

  • 归档22

  • 搜索

欧拉函数模板

发表于 2019-01-21 更新于 2020-07-03 分类于 ACM模板
本文字数: 1.3k 阅读时长 ≈ 1 分钟

两种求解方法!

快速求欧拉函数:$ O(\sqrt{n}) $

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>
#include <cstdio>
#include <cstring>
#include <map>
#include <vector>
#include <set>
using namespace std;
typedef long long LL;
const int maxn = 1e6+5;
LL n;
LL get_Euler(LL x){
LL res = x; //初始值
for(LL i = 2LL; i * i <= x; ++i) {
if(x % i == 0) {
res = res / i * (i - 1); //先除后乘,避免数据过大
while(x % i == 0) x /= i;
}
}
if(x > 1LL) res = res / x * (x - 1); //若x大于1,则剩下的x必为素因子
return res;
}

int main(){
while(cin >> n) {
cout << get_Euler(n) << endl; //求n的互质数的个数
cout << n * get_Euler(n) / 2 << endl; //求n的所有互质数之和
}
return 0;
}

埃氏筛法预处理打表:$ O(nlog^{log^n})$

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>
#include <cstdio>
#include <cstring>
#include <map>
#include <vector>
#include <set>
using namespace std;
typedef long long LL;
const int maxn = 1e6+5;
int n, phi[maxn];
void phi_table() {
phi[0] = 0, phi[1] = 1; //1的欧拉函数值为1:唯一与1互质的数
for(int i = 2; i < maxn; ++i) phi[i] = i; //先初始化为其本身
for(int i = 2; i < maxn; ++i) {
if(phi[i] == i) { //如果欧拉函数值仍为其本身,说明i为素数
for(int j = i; j < maxn; j += i) //把i的欧拉函数值改变,同时也把能被素因子i整除的数的欧拉函数值改变
phi[j] = phi[j] / i * (i - 1);
}
}
}

int main(){
phi_table(); //预处理打表
while(cin >> n) {
cout << phi[n] << endl;
}
return 0;
}
  • 本文作者: wzomg
  • 本文链接: http://blog.wzomg.cn/posts/ee22c535.html
  • 版权声明: 本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
欧拉函数
欧拉函数
数论笔记整理1
  • 文章目录
  • 站点概览
wzomg

wzomg

A thousand miles begins with a single step.
22 日志
6 分类
12 标签
GitHub E-Mail 博客园 简书
Creative Commons
  1. 1. 两种求解方法!
    1. 1.1. 快速求欧拉函数:$ O(\sqrt{n}) $
    2. 1.2. 埃氏筛法预处理打表:$ O(nlog^{log^n})$
© 2019 – 2021 wzomg  粤ICP备19066467号-1 | 113k | 1:43
0%