All square roots are periodic when written as continued fractions and can be written in the form:
1 | |||
a1 + | 1 | ||
a2 + | 1 | ||
a3 + ... |
1 | = 4 + | 1 | ||
1 | 1 + | 7 |
1 | ||||
1 + | 1 | |||
3 + | 1 | |||
1 + | 1 | |||
8 + ... |
a0 = 4, | 1 | = | 7 | = 1 + | 7 | |
a1 = 1, | 7 | = | 7( 14 | = 3 + | 2 | |
a2 = 3, | 2 | = | 2( 14 | = 1 + | 7 | |
a3 = 1, | 7 | = | 7( 7 | = 8 + | ||
a4 = 8, | 1 | = | 7 | = 1 + | 7 | |
a5 = 1, | 7 | = | 7( 14 | = 3 + | 2 | |
a6 = 3, | 2 | = | 2( 14 | = 1 + | 7 | |
a7 = 1, | 7 | = | 7( 7 | = 8 + |
The first ten continued fraction representations of (irrational) square roots are:
How many continued fractions for N
My Solution
This time, I use the Mathematica
Length[Select[Table[ContinuedFraction[Sqrt[i]], {i, 1, 10000}], Length[#] == 2 && OddQ [Length[#[[2]]]] &]]
Others' Solution using LISP
(defun list-as-for-sqrt (n) (iter (for i first (isqrt n) then (truncate x))
(for di first i then (- (- di (* i d))))
(for d first (- n (* di di))
then (/ (- n (* di di)) d))
(for dl previous d initially -1)
(for x = (/ (+ di (sqrt n)) d))
(collecting i)
(until (= dl 1))))
(defun 64-count-odd-periods (max)
(iter (for n from 2 to max)
(when (integer-root-p n) (next-iteration))
;; This checks evenness, because it counts the ;; initial digit, which isn't in the repeating ;; section.
(when (evenp (length (list-as-for-sqrt n))) (sum 1))))
First Solution
Second Solution
(defun cont-frac-odd-p (n)
(do* ((b0 (isqrt n))
(l b0 (- (* b p) l))
(bflag t (not bflag))
(p (- n (expt b0 2)) (/ (- n (expt l 2)) p))
(l b0 (- (* b p) l))
(bflag t (not bflag))
(p (- n (expt b0 2)) (/ (- n (expt l 2)) p))
(b (if (zerop p)
(return nil)
(floor (+ b0 l) p))
(floor (+ b0 l) p))) ((= 1 p) bflag)))
(defun main (toplim)
(loop :for n :from 1 :to toplim :count (cont-frac-odd-p n)))
(princ (main 10000)) (terpri)
No comments:
Post a Comment