Project Euler 57

Project Euler 57

题目

Square root convergents

It is possible to show that the square root of two can be expressed as an infinite continued fraction. 2=1+12+12+12+ By expanding this for the first four iterations, we get:

1+12=32=1.5

1+12+12=75=1.4

1+12+12+12=1712=1.41666

1+12+12+12+12=4129=1.41379

The next three expansions are 9970, 239169, and 577408, but the eighth expansion, 1393985, is the first example where the number of digits in the numerator exceeds the number of digits in the denominator.

In the first one-thousand expansions, how many fractions contain a numerator with more digits than the denominator?

解决方案

观察上面的连分数,将其写成一个序列 a1,a2,a3,,容易发现规律: an=11+an1+1 因此,直接通过此式子进行 1000 次迭代求出每个序列的值。

本代码使用的是 fractions 库中的 Fraction 类,它用于维护一个分数的类型。

代码

1
2
3
4
5
6
7
8
9
10
11
from fractions import Fraction

N = 1000
a = Fraction(1, 1)
ans = 0
for i in range(1000):
a = 1 / (1 + a) + 1
if len(str(a.numerator)) > len(str(a.denominator)):
ans += 1
print(ans)

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