1 ! Copyright (C) 2009 Kye W. Shi.
2 ! See https://factorcode.org/license.txt for BSD license.
3 USING: accessors classes.tuple kernel math math.functions
4 project-euler.common ranges sequences ;
7 ! http://projecteuler.net/problem=64
12 ! All square roots are periodic when written as continued
13 ! fractions and can be written in the form:
15 ! √N=a0+1/(a1+1/(a2+1/a3+...))
17 ! For example, let us consider √23:
19 ! √23=4+√(23)−4=4+1/(1/(√23−4)=4+1/(1+((√23−3)/7)
21 ! If we continue we would get the following expansion:
23 ! √23=4+1/(1+1/(3+1/(1+1/(8+...))))
25 ! The process can be summarised as follows:
27 ! a0=4, 1/(√23−4) = (√23+4)/7 = 1+(√23−3)/7
28 ! a1=1, 7/(√23−3) = 7*(√23+3)/14 = 3+(√23−3)/2
29 ! a2=3, 2/(√23−3) = 2*(√23+3)/14 = 1+(√23−4)/7
30 ! a3=1, 7/(√23−4) = 7*(√23+4)/7 = 8+√23−4
31 ! a4=8, 1/(√23−4) = (√23+4)/7 = 1+(√23−3)/7
32 ! a5=1, 7/(√23−3) = 7*(√23+3)/14 = 3+(√23−3)/2
33 ! a6=3, 2/(√23−3) = 2*(√23+3)/14 = 1+(√23−4)/7
34 ! a7=1, 7/(√23−4) = 7*(√23+4)/7 = 8+√23−4
36 ! It can be seen that the sequence is repeating. For
37 ! conciseness, we use the notation √23=[4;(1,3,1,8)], to
38 ! indicate that the block (1,3,1,8) repeats indefinitely.
40 ! The first ten continued fraction representations of
41 ! (irrational) square roots are:
43 ! √2=[1;(2)] , period=1
44 ! √3=[1;(1,2)], period=2
45 ! √5=[2;(4)], period=1
46 ! √6=[2;(2,4)], period=2
47 ! √7=[2;(1,1,1,4)], period=4
48 ! √8=[2;(1,4)], period=2
49 ! √10=[3;(6)], period=1
50 ! √11=[3;(3,6)], period=2
51 ! √12=[3;(2,6)], period=2
52 ! √13=[3;(1,1,1,1,6)], period=5
54 ! Exactly four continued fractions, for N <= 13, have an odd period.
56 ! How many continued fractions for N <= 10000 have an odd period?
65 C: <cont-frac> cont-frac
67 : deep-copy ( cont-frac -- cont-frac cont-frac )
68 dup tuple>array rest cont-frac slots>tuple ;
70 : create-cont-frac ( n -- n cont-frac )
71 dup sqrt >fixnum dup 1 <cont-frac> ;
73 : step ( n cont-frac -- n cont-frac )
77 ! Extract the constant
81 ! Find the new denominator
82 num-const 2 ^ n swap -
85 ! Find the fraction in lowest terms
91 ! Find the new whole number
92 num-const n sqrt + new-denom / >fixnum
95 ! Find the new num-const
101 ! Finally, update the continuing fraction
102 drop new-whole new-num-const new-denom <cont-frac>
105 :: loop ( c l n cf -- c l n cf )
106 n cf step :> new-cf drop
108 l new-cf = [ loop ] unless ;
110 : find-period ( n -- period )
120 [ perfect-square? ] reject
127 : euler064a ( -- n ) try-all ;
136 : >cfrac< ( fr -- n a b )
137 [ n>> ] [ a>> ] [ b>> ] tri ;
139 ! (√n + a) / b = 1 / (k + (√n + a') / b')
141 ! b / (√n + a) = b (√n - a) / (n - a^2) = (√n - a) / ((n - a^2) / b)
142 :: reciprocal ( fr -- fr' )
143 fr >cfrac< :> ( n a b )
149 :: split ( fr -- k fr' )
150 fr >cfrac< :> ( n a b )
161 reciprocal split nip ;
163 :: period ( n -- period )
164 n sqrt >integer sq n = [ 0 ] [
165 n pure split nip :> start
174 : euler064b ( -- ct )
175 10000 [1..b] [ period odd? ] count ;