#=======================================================================
# Author: Isai Damier
# Title: Subtraction of Fractions
# Project: geekviewpoint
# Package: algorithms
#
# Statement:
# Subtract the two given positive fractions
#
# Sample Input: [5,6], [7,8]
# Sample Output: [-1,24]
#
# Technical Details:
# This is the same algorithm you learned in grade school:
# 1) find the lowest common denominator, which is the same as finding
# the lowest common multiplier of the given denominators.
# 2) Convert the given fractions into equivalent fractions with the
# new denominator
# 3) subtract the numerators
# 4) reduce the resulting fraction by dividing the GCD (greatest
# common divisor) of its numerator and denominator.
#=======================================================================
def fractionSubtraction( a, b ):
denominator = LCM( a[1], b[1] )
numA = denominator / a[1] * a[0]
numB = denominator / b[1] * b[0]
numerator = numA - numB;
gcd = GCD( 0 > numerator and -numerator or numerator, denominator )
gcd = 0 > gcd and -gcd or gcd
return [numerator / gcd, denominator / gcd]
import unittest
from algorithms import numbers as algorithm
class Test( unittest.TestCase ):
def testFractionSubtraction( self ):
expResult = [-1, 24]
result = algorithm.fractionSubtraction( [5, 6], [7, 8] )
self.assertEquals( expResult, result )
result = algorithm.fractionSubtraction( [5, 6], [6, 8] )
self.assertEquals( [1, 12], result )