forked from ahmedkareem999/MITx-6.00.1x
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgcdRecur.py
35 lines (24 loc) · 925 Bytes
/
gcdRecur.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
'''
Week-2:Exercise-gcd Recur
The greatest common divisor of two positive integers is the largest integer that divides each of them without remainder. For example,
gcd(2, 12) = 2
gcd(6, 12) = 6
gcd(9, 12) = 3
gcd(17, 12) = 1
A clever mathematical trick (due to Euclid) makes it easy to find greatest common divisors. Suppose that a and b are two positive integers:
If b = 0, then the answer is a
Otherwise, gcd(a, b) is the same as gcd(b, a % b)
See this website for an example of Euclid's algorithm being used to find the gcd.
Write a function gcdRecur(a, b) that implements this idea recursively. This function takes in two positive integers and returns one integer.
'''
#code
def gcdRecur(a, b):
'''
a, b: positive integers
returns: a positive integer, the greatest common divisor of a & b.
'''
# Your code here
if b == 0:
return a
else:
return gcdRecur(b,a % b)