-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgcd_tools.py
221 lines (168 loc) · 5.58 KB
/
gcd_tools.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
# computes the gcd. taken from snappea
from functools import total_ordering
import re
def gcd(a, b):
a = abs(a)
b = abs(b)
if a == 0:
if b == 0: raise ValueError("gcd(0,0) undefined.")
else: return b
while 1:
b = b % a
if (b == 0): return a
a = a % b
if (a == 0): return b
# returns (gcd, a, b) where ap + bq = gcd. taken from snappea
def euclidean_algorithm(m, n):
# Given two long integers m and n, use the Euclidean algorithm to
# find integers a and b such that a*m + b*n = g.c.d.(m,n).
#
# Recall the Euclidean algorithm is to keep subtracting the
# smaller of {m, n} from the larger until one of them reaches
# zero. At that point the other will equal the g.c.d.
#
# As the algorithm progresses, we'll use the coefficients
# mm, mn, nm, and nn to express the current values of m and n
# in terms of the original values:
#
# current m = mm*(original m) + mn*(original n)
# current n = nm*(original m) + nn*(original n)
# Begin with a quick error check.
if m == 0 and n == 0 : raise ValueError("gcd(0,0) undefined.")
# Initially we have
#
# current m = 1 (original m) + 0 (original n)
# current n = 0 (original m) + 1 (original n)
mm = nn = 1
mn = nm = 0
# It will be convenient to work with nonnegative m and n.
if m < 0:
m = - m
mm = -1
if n < 0:
n = - n
nn = -1
while 1:
# If m is zero, then n is the g.c.d. and we're done.
if m == 0:
return(n, nm, nn)
# Let n = n % m, and adjust the coefficients nm and nn accordingly.
quotient = n // m
nm = nm - quotient * mm
nn = nn - quotient * mn
n = n - quotient * m
# If n is zero, then m is the g.c.d. and we're done.
if n == 0:
return(m, mm, mn)
# Let m = m % n, and adjust the coefficients mm and mn accordingly.
quotient = m // n
mm = mm - quotient * nm
mn = mn - quotient * nn
m = m - quotient * n
# We never reach this point.
# computes the lcm of the given list of numbers:
def lcm( a ):
cur_lcm = a[0]
for n in a[1 : ]:
cur_lcm = n * cur_lcm // gcd(n, cur_lcm)
return abs(cur_lcm)
# computes the continued fraction expansion of the given
# number p/q which must satisfy 0 < a/b < 1, a, b > 0
def positive_continued_fraction_expansion(a, b):
if not (0 < a < b): raise ValueError("must have 0 < a < b")
expansion = []
while a > 0:
# b = q a + r
q = b//a
r = b % a
expansion.append(q)
b, a = a, r
return expansion
# A fraction class
from types import *
@total_ordering
class frac:
# the fraction is stored as self.t/self.b where
# t and b are coprime and b > 0
#
# standard arithmatic and compareson ops implemented.
# can add, etc. fracs and integers
def __init__(self, p, q):
if (not isinstance(p, int)) or (not isinstance(q, int)):
raise TypeError
g = gcd(p, q)
if q == 0:
self.t, self.b = 1, 0
if q < 0:
self.t, self.b = -p//g, -q//g
else:
self.t, self.b = p//g, q//g
def copy(self):
return frac(self.t, self.b)
def __repr__(self):
if self.b == 1: return "%i" % self.t
return "%i/%i" % (self.t, self.b)
def __abs__(self):
return frac(abs(self.t), abs(self.b) )
def __add__(self, o):
if isinstance(o, int):
o = frac(o, 1)
if not isinstance(o, frac): raise TypeError
return frac(self.t*o.b + self.b*o.t, self.b*o.b)
def __radd__(self, o):
return self.__add__(o)
def __sub__(self, o):
if isinstance(o, int):
o = frac(o, 1)
if not isinstance(o, frac): raise TypeError
return frac(self.t*o.b - self.b*o.t, self.b*o.b)
def __rsub__(self, o):
if isinstance(o, int):
o = frac(o, 1)
if not isinstance(o, frac): raise TypeError
return frac(o.t*self.b - o.b*self.t, self.b*o.b)
def __mul__(self, o):
if isinstance(o, int):
o = frac(o, 1)
if not isinstance(o, frac): raise TypeError
return frac(self.t*o.t , self.b*o.b)
def __rmul__(self, o):
return self.__mul__(o)
def __truediv__(self, o):
if isinstance(o, int):
o = frac(o, 1)
if not isinstance(o, frac): raise TypeError
if o == 0: raise ZeroDivisionError
try:
p, q = self.t*o.b , self.b*o.t
return frac( p, q )
except OverflowError:
gt = gcd(self.t, o.t)
gb = gcd(self.b, o.b)
return frac( (self.t//gt)*(o.b//gb) , (self.b//gb)*(o.t//gt))
def __neg__(self):
return frac(-self.t, self.b)
def __bool__(self):
return self.t != 0
def __eq__(self, o):
if isinstance(o, int):
o = frac(o, 1)
if not isinstance(o, frac):
raise TypeError
return self.t*o.b == self.b*o.t
def __lt__(self, o):
if isinstance(o, int):
o = frac(o, 1)
if not isinstance(o, frac):
raise TypeError
return self.t*o.b < self.b*o.t
def string_to_frac(s):
data = re.match("([+-]{0,1}\d+)/([+-]{0,1}\d+)$", s)
if not data:
data = re.match("[+-]{0,1}\d+$", s)
if data:
return frac(int(s), 1)
else:
raise ValueError("need something of form a/b, a and b integers")
p, q = map(int, data.groups())
return frac(p, q)