欧拉函数

一、性质求欧拉函数

from collections import Counter
# 证明:容斥原理
# f(N) = N * (1 - 1/p1) * (1 - 1/p2) * ... * (1 - 1/pn)
# 与N互质的数的个数: N - N/P1 - N/P2 - ... - N/Pn + N/(p1p2) + ... + ... - ...
def cal_euler(x):
    ans = x
    cnt = Counter()
    i = 2
    while i * i <= x:
        while x % i == 0:
            x //= i
            cnt[i] += 1
        i += 1
    if x > 1:
        cnt[x] += 1
    for key in cnt.keys():
        ans = ans * (key - 1) // key
    return ans
for _ in range(int(input())):
    a = int(input())
    print(cal_euler(a))

二、筛法求欧拉函数

# 筛法求euler函数,跟线性筛差不多
n = int(input())
prime = []
vis = [0] * (n + 1)
phi = [0] * (n + 1)
phi[1] = 1

def cal_eulers():
    for i in range(2,n + 1):
        if not vis[i]:
            prime.append(i)
            # 质数i的欧拉函数为 i - 1
            phi[i] = i - 1
        for x in prime:
            if x * i > n:
                break
            vis[x * i] = 1
            if i % x == 0:
                phi[i * x] = x * phi[i]
                break
            phi[i * x] = (x - 1) * phi[i]
cal_eulers()
ans = sum(phi)
print(ans)
posted @ 2024-04-03 18:17  gebeng  阅读(30)  评论(0)    收藏  举报