-
Notifications
You must be signed in to change notification settings - Fork 0
/
id_0064.py
executable file
·76 lines (73 loc) · 2 KB
/
id_0064.py
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#!/usr/bin/python2
# #####################################################################
# id_0064.py
#
# Przemyslaw Kaminski <cgenie@gmail.com>
# Time-stamp: <>
######################################################################
from math import sqrt
from id_0033 import gcd
def continued_fraction_sqrt(n):
a = 1
b = 0
m = 1
s = int(sqrt(n))
while True:
l = (a*s + b)/m
yield l
b = b - l*m
aa = m*a
bb = -m*b
m = n*a*a - b*b
a = aa
b = bb
am = gcd(a, m)
bm = gcd(b, m)
abm = gcd(am, bm)
if abm > 1:
a = a/abm
b = b/abm
m = m/abm
if m == 0:
raise StopIteration
if __name__ == '__main__':
n = 2
odd = 0
period_len = 20
limit = 13
while True:
f = continued_fraction_sqrt(n)
r1 = f.next()
lst = []
cont_frac = True
for i in range(period_len):
try:
lst.append(f.next())
except StopIteration:
cont_frac = False
break
# find a period
if cont_frac:
for l in range(1, period_len/2):
first = lst[:l]
next = []
for x in range(period_len/l):
next.append(lst[x*l:(x + 1)*l])
has_period = True
for x in next:
if first != x:
has_period = False
break
if has_period:
print "sqrt(" + str(n) + ") = {" + str(r1) + "; " + str(lst[:l]) + "}, period of length " + str(l)
if l % 2 == 1:
print "n = " + str(n) + " -- odd period found"
odd += 1
break
if not has_period:
print "No period found..."
raise Error
if n >= limit:
break
n += 1
print odd