Skip to content

Instantly share code, notes, and snippets.

@rubik
Last active August 29, 2015 13:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rubik/9174635 to your computer and use it in GitHub Desktop.
Save rubik/9174635 to your computer and use it in GitHub Desktop.
import '/math'
from_root = n ->
a0 = int $ math.floor $ math.sqrt n
r = (a0, list!)
a, b, c = 1, 2 * a0, a0 ** 2 - n
delta = math.sqrt $ 4 * n
flag = True
while flag =>
if not c =>
res = tuple' r !! 0
c, flag = 2, False
d = int $ (b + delta) / (2 * c)
a, b, c = c, -b + 2 * c * d, a - b * d + c * d ** 2
(r !! 1).append $ abs d
if abs a == 1 =>
res = r
flag = False
res
print $ from_root 2
print $ from_root 4
print $ from_root 97
import math
def from_root(n):
'''
Construct a continued fraction from a square root. The argument
`n` should be an integer representing the radicand of the root:
>>> from_root(2)
(1, [2])
>>> from_root(4)
(2,)
>>> from_root(97)
(9, [1, 5, 1, 1, 1, 1, 1, 1, 5, 1, 18])
'''
a0 = int(math.floor(math.sqrt(n)))
r = (a0, [])
a, b, c = 1, 2 * a0, a0 ** 2 - n
delta = math.sqrt(4*n)
while True:
try:
d = int((b + delta) / (2 * c))
except ZeroDivisionError: # a perfect square
return (r[0],)
a, b, c = c, -b + 2*c*d, a - b*d + c*d ** 2
r[1].append(abs(d))
if abs(a) == 1:
break
return r
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment