I am given the function gcd, which is defined as follows:
def gcd(a, b):
if (0 == a % b):
return b
return gcd(b, a%b)
Now I am asked to write a recursive function gcd2(a,b) that returns a list of three numbers (g, s, t) where g = gcd(a, b) and g = s*a + t*b.
This means that you would enter two values (a and b) into the gcd(a, b) function. The value it returns equals g in the next function.
These same a and b values are then called into gcd2(a, b). The recursive part is then used to find the values for s and t so that g = s*a + t*b.
I am not sure how to approach this because I can’t really envision what the “stopping-condition” would be, or what exactly I’d be looping through recursively to actually find s and t. Can anyone help me out?
The key insight is that we can work backwards, finding
sandtfor eachaandbin the recursion. So say we havea = 21andb = 15. We need to work through each iteration, using several values —a,b,b % a, andcwherea = c * b + a % b. First, let’s consider each step of the basic GCD algorithm:So our gcd (
g) is 3. Once we have that, we determinesandtfor 6 and 3. To do so, we begin withg, expressing it in terms of(a, b, s, t = 3, 0, 1, -1):Now we want to eliminate the 0 term. From the last line of the basic algorithm, we know that 0 = 6 – 2 * 3:
Simplifying, we get
Now we swap the terms:
So we have
s == -1andt == 3fora = 6andb = 3. So given those values ofaandb,gcd2should return(3, -1, 3).Now we step back up through the recursion, and we want to eliminate the 3 term. From the next-to-last line of the basic algorithm, we know that 3 = 15 – 2 * 6. Simplifying and swapping again (slowly, so that you can see the steps clearly…):
So for this level of recursion, we return
(3, 3, -7). Now we want to eliminate the 6 term.And voila, we have calculated
sandtfor 21 and 15.So schematically, the recursive function will look like this:
Note that for our purposes here, using a slightly different base case simplifies things: