Project Euler 72

Project Euler 72

题目

Counting fractions

Consider the fraction, $\dfrac{n}{d}$, where n and d are positive integers. If $n<d$ and $\gcd(n,d)=1$, it is called a reduced proper fraction.
If we list the set of reduced proper fractions for $d \leq 8$ in ascending order of size, we get:

It can be seen that there are $21$ elements in this set.

How many elements would be contained in the set of reduced proper fractions for $d \leq 1,000,000$?

解决方案

根据题意,第$m$个Farey 序列$F_m$的所有元素可以由该集合定义:$\left{\dfrac{n}{d} | \gcd(n,d)=1,1\le n<d \le m\right}$.

通过分子分母互质的性质,联系到欧拉函数$\varphi$的定义,可以得出本题答案:

代码

1
2
3
4
5
6
7
8
9
10
N = 1000000
phi = [i for i in range(N + 1)]
for i in range(2, N + 1):
if i == phi[i]:
for j in range(i, N + 1, i):
phi[j] //= i
phi[j] *= i - 1
ans = sum(phi) - 1
print(ans)

如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
Ujimatsu Chiya 微信 微信
Ujimatsu Chiya 支付宝 支付宝