Skip to content

Instantly share code, notes, and snippets.

@marshareb
Last active February 14, 2017 00:57
Show Gist options
  • Save marshareb/08246cc884552cf31f7ba9113b374ef3 to your computer and use it in GitHub Desktop.
Save marshareb/08246cc884552cf31f7ba9113b374ef3 to your computer and use it in GitHub Desktop.
Algorithms to find gcd and to reduce fractions
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