Last active
February 14, 2017 00:57
-
-
Save marshareb/08246cc884552cf31f7ba9113b374ef3 to your computer and use it in GitHub Desktop.
Algorithms to find gcd and to reduce fractions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import warnings | |
def warn(m,n): | |
#If m,n are not integers, or are not less than 0, return a warning | |
if type(m) != int or type(n) != int or m < 0 or n < 0: | |
warnings.warn("Input was not a strictly positive integer") | |
def euclidean_division(m, n): | |
#The Euclidean division algorithm takes two inputs, m and n in this case, and returns two values which represent | |
#q and r such that, if m > n, m = qn + r, where 0 <= r < n. | |
#We can assume WLOG that m, n > 0. | |
warn(m,n) | |
if m >= n: | |
q = int(m/n) | |
r = m - q*n | |
else: | |
q = int(n/m) | |
r = n - q*m | |
return (q,r) | |
def gcd(m, n): | |
#This algorithm uses the Euclidean algorithm prior defined in order to find the greatest common divisor. | |
#See: https://en.wikipedia.org/wiki/Euclidean_algorithm | |
#We once again assume m,n > 0 WLOG. | |
warn(m,n) | |
ma = max(m,n) | |
mi = min(m,n) | |
q, r = euclidean_division(ma,mi) | |
if r == 0: | |
return mi | |
else: | |
return gcd(mi, r) | |
def reduce_fraction(numerator, denominator): | |
#Takes two inputs, numerator and denominator, and returns the reduced fraction | |
greatest = gcd(numerator, denominator) | |
num = int(numerator/ greatest) | |
den = int(denominator/greatest) | |
return (num, den) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment