Qiita Teams that are logged in
You are not logged in to any team

Community
Service
Qiita JobsQiita ZineQiita Blog
0
Help us understand the problem. What is going on with this article?
@yopya

# Project Euler 57「平方根の近似分数」

More than 3 years have passed since last update.

3/2、7/5、17/12、41/29をジーっと眺めて法則性を探して、やってみたら正解だっただけ。

# Problem 57 「平方根の近似分数」

2の平方根は無限に続く連分数で表すことができる.

√ 2 = 1 + 1/(2 + 1/(2 + 1/(2 + ... ))) = 1.414213...

1 + 1/2 = 3/2 = 1.5
1 + 1/(2 + 1/2) = 7/5 = 1.4
1 + 1/(2 + 1/(2 + 1/2)) = 17/12 = 1.41666...
1 + 1/(2 + 1/(2 + 1/(2 + 1/2))) = 41/29 = 1.41379...

``````def hoge(num):
def cnt():
n, d = 1, 1
for _ in range(num):
n, d = n + d * 2, n + d
yield len(str(n)) > len(str(d))
return sum(cnt())

print(hoge(1000))
``````

``````from fractions import Fraction

def hoge(num):
def cnt():
s = '1 + 1/2'
for _ in range(num):
F = Fraction(eval(s)).limit_denominator()
numer, denom = str(F).split('/')
yield len(numer) > len(denom)
s = s.replace('1/2', '1/(2 + 1/2)')
return sum(cnt())

print(hoge(1000))
``````
0
Help us understand the problem. What is going on with this article?
Why not register and get more from Qiita?
1. We will deliver articles that match you
By following users and tags, you can catch up information on technical fields that you are interested in as a whole
2. you can read useful information later efficiently
By "stocking" the articles you like, you can search right away