Finding the GCD of Two Numbers

advertisement
Finding the GCD of Two Numbers
In this exercise, we will compute the GCD of two numbers by increasingly efficient (but
decreasingly intuitive) methods.
1. Stupid way
Check all the numbers less than a to see whether they divide both a and b. Return the
largest one that does.
2. Less stupid way
Here is a function that takes two sorted lists and returns a list containing their common
elements:
def intersection(A,B):
C=[]
while len(A)>0 and len(B)>0:
if A[0] > B[0]:
B = B[1:len(B)]
else:
if A[0] < B[0]:
A = A[1:len(A)]
else:
C.append(A[0])
B = B[1:len(B)]
A = A[1:len(A)]
return C
Use this function together with your prime factor function and list multiplication function
to find the GCD of a and b by taking the product of their common prime factors.
(Optional but interesting: try to write this function in only one line.)
3. Smart way
Implement the Euclidean algorithm. This should give you the same result as the other
two algorithms, but is should be much faster. Try all three on some biggish numbers to
see how they behave.
If you have extra time, try whichever of the following looks more interesting:
4A. Recursion
A recursive function is one that calls itself as it computes. Try writing your Euclidean
algorithm function using recursion.
4B. Timing
Look up how to time functions in python (Jim Carlson’s python tutorial, linked on the
course web page, discusses this on page 17.) and time the three algorithms. See if you
can find any patterns.
Download