1 USING: accessors arrays classes.tuple io kernel locals math
2 math.functions math.ranges prettyprint project-euler.common
6 ! http://projecteuler.net/index.php?section=problems&id=64
11 ! All square roots are periodic when written as continued
12 ! fractions and can be written in the form:
14 ! √N=a0+1/(a1+1/(a2+1/a3+...))
16 ! For example, let us consider √23:
18 ! √23=4+√(23)−4=4+1/(1/(√23−4)=4+1/(1+((√23−3)/7)
20 ! If we continue we would get the following expansion:
22 ! √23=4+1/(1+1/(3+1/(1+1/(8+...))))
24 ! The process can be summarised as follows:
26 ! a0=4, 1/(√23−4) = (√23+4)/7 = 1+(√23−3)/7
27 ! a1=1, 7/(√23−3) = 7*(√23+3)/14 = 3+(√23−3)/2
28 ! a2=3, 2/(√23−3) = 2*(√23+3)/14 = 1+(√23−4)/7
29 ! a3=1, 7/(√23−4) = 7*(√23+4)/7 = 8+√23−4
30 ! a4=8, 1/(√23−4) = (√23+4)/7 = 1+(√23−3)/7
31 ! a5=1, 7/(√23−3) = 7*(√23+3)/14 = 3+(√23−3)/2
32 ! a6=3, 2/(√23−3) = 2*(√23+3)/14 = 1+(√23−4)/7
33 ! a7=1, 7/(√23−4) = 7*(√23+4)/7 = 8+√23−4
35 ! It can be seen that the sequence is repeating. For
36 ! conciseness, we use the notation √23=[4;(1,3,1,8)], to
37 ! indicate that the block (1,3,1,8) repeats indefinitely.
39 ! The first ten continued fraction representations of
40 ! (irrational) square roots are:
42 ! √2=[1;(2)] , period=1
43 ! √3=[1;(1,2)], period=2
44 ! √5=[2;(4)], period=1
45 ! √6=[2;(2,4)], period=2
46 ! √7=[2;(1,1,1,4)], period=4
47 ! √8=[2;(1,4)], period=2
48 ! √10=[3;(6)], period=1
49 ! √11=[3;(3,6)], period=2
50 ! √12=[3;(2,6)], period=2
51 ! √13=[3;(1,1,1,1,6)], period=5
53 ! Exactly four continued fractions, for N <= 13, have an odd period.
55 ! How many continued fractions for N <= 10000 have an odd period?
64 C: <cont-frac> cont-frac
66 : deep-copy ( cont-frac -- cont-frac cont-frac )
67 dup tuple>array rest cont-frac slots>tuple ;
69 : create-cont-frac ( n -- n cont-frac )
70 dup sqrt >fixnum dup 1 <cont-frac> ;
72 : step ( n cont-frac -- n cont-frac )
76 ! Extract the constant
80 ! Find the new denominator
81 num-const 2 ^ n swap -
84 ! Find the fraction in lowest terms
90 ! Find the new whole number
91 num-const n sqrt + new-denom / >fixnum
94 ! Find the new num-const
100 ! Finally, update the continuing fraction
101 drop new-whole new-num-const new-denom <cont-frac>
104 :: loop ( c l n cf -- c l n cf )
105 n cf step :> new-cf drop
107 l new-cf = [ loop ] unless ;
109 : find-period ( n -- period )
119 [ perfect-square? ] reject
126 : euler064a ( -- n ) try-all ;
135 : >cfrac< ( fr -- n a b )
136 [ n>> ] [ a>> ] [ b>> ] tri ;
138 ! (√n + a) / b = 1 / (k + (√n + a') / b')
140 ! b / (√n + a) = b (√n - a) / (n - a^2) = (√n - a) / ((n - a^2) / b)
141 :: reciprocal ( fr -- fr' )
142 fr >cfrac< :> ( n a b )
148 :: split ( fr -- k fr' )
149 fr >cfrac< :> ( n a b )
160 reciprocal split nip ;
162 :: period ( n -- period )
163 n sqrt >integer sq n = [ 0 ] [
164 n pure split nip :> start
173 : euler064b ( -- ct )
174 10000 [1,b] [ period odd? ] count ;