diff -r 9b7b8b7ccf28 Lib/fractions.py --- a/Lib/fractions.py Sat Oct 12 23:16:32 2013 +0200 +++ b/Lib/fractions.py Sat Oct 12 22:22:42 2013 +0100 @@ -10,7 +10,7 @@ import re import sys -__all__ = ['Fraction', 'gcd'] +__all__ = ['Fraction', 'gcd','lcm'] @@ -24,6 +24,14 @@ a, b = b, a%b return a +def lcm(a, b): + """Calculate the Least Common Multiple of a and b.""" + return a * b // gcd(a,b) + + + + + # Constants related to the hash implementation; hash(x) is based # on the reduction of x modulo the prime _PyHASH_MODULUS. _PyHASH_MODULUS = sys.hash_info.modulus diff -r 9b7b8b7ccf28 Lib/test/test_fractions.py --- a/Lib/test/test_fractions.py Sat Oct 12 23:16:32 2013 +0200 +++ b/Lib/test/test_fractions.py Sat Oct 12 22:22:42 2013 +0100 @@ -12,6 +12,7 @@ from pickle import dumps, loads F = fractions.Fraction gcd = fractions.gcd +lcm = fractions.lcm class DummyFloat(object): """Dummy float class for testing comparisons with Fractions""" @@ -94,6 +95,35 @@ self.assertEqual(12, gcd(120, 84)) self.assertEqual(-12, gcd(84, -120)) +class LcmTest(unittest.TestCase): + """The Least Common Multiple (LCM) of two integers (a,b) is the smallest + integer that both a and b divide into. + + Note 1: LCM(a,b) * GCD(a,b) = a * b + + Note 2: GCD(a,b) is often written as HCF(a,b) (Highest Common Factor) + """ + + def test_lcm_int(self): + """ lcm should return an int, not a float """ + self.assertTrue(isinstance(lcm(1, 2), int)) + + def test_lcm(self): + """ test the basic cases, swapping arguments as lcm is symmetric.""" + for answer,a,b in [(1,1,1), + (2,1,2), + (6,2,3), + (4,2,4), + (30,5,6), + (30,10,15)]: + self.assertEqual(answer,lcm(a,b)) + self.assertEqual(answer,lcm(b,a)) + + def test_lcm_with_gcd(self): + """ lcm(a,b) * gcd(a,b) = a*b which allows an automatic co-test """ + for a in range(1,20): + for b in range(1,20): + self.assertEqual(a*b, lcm(a, b) * gcd(a, b)) def _components(r): return (r.numerator, r.denominator) @@ -606,7 +636,7 @@ self.assertRaises(AttributeError, setattr, r, 'a', 10) def test_main(): - run_unittest(FractionTest, GcdTest) + run_unittest(FractionTest, GcdTest,LcmTest) if __name__ == '__main__': test_main()