-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathproblem64.rb
42 lines (35 loc) · 916 Bytes
/
problem64.rb
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
30
31
32
33
34
35
36
37
38
39
40
41
42
require 'euler_helper.rb'
require 'mathn'
NAME ="How many continued fractions for N ≤ 10000 have an odd period?"
DESCRIPTION ="All square roots are periodic when written as continued fractions and can be written in the form:"
def sqroot x
y = 1.0
11.times {y = (y + x/y) / 2}
y
end
def period x
sq = sqroot x
return 0 if int?(sq)
ints = []
coef = 1
int = sq.to_i
denom = x - int ** 2
add = int
until ints.include?([coef, add, denom]) do
ints.push [coef, add, denom]
#puts [coef, add, denom].inspect
int = ((sq*coef +add) / denom.to_f).to_i
#puts int
add = add - int*denom
#puts [coef, add, denom].inspect
coef, denom = denom, x - add ** 2
coef, denom = coef / coef.gcd(denom), denom / coef.gcd(denom)
add = -add
#puts [coef, add, denom].inspect
#puts
end
ints.size
end
benchmark do
puts (2..10000).count {|n| period(n) % 2 == 1 }
end