Home > Back-end >  Logical math operations
Logical math operations

Time:10-29

I need to write a recursive function that applies the following operations:

  1. If a = 0 or b = 0, return [a, b]. Otherwise, go to step (2);
  2. If a >= 2b, set a = a - 2b, and repeat step (1). Otherwise, go to step (3);
  3. If b >= 2a, set b = b - 2a, and repeat step (1). Otherwise, return [a, b].

Some examples of what I want to achieve:

  • input(6, 19) returns [6, 7]
  • input(2, 1) returns [0, 1]
  • input(22, 5) also returns [0, 1]
  • input (8796203,7556) returns [1019,1442]

I can't get 3rd and 4th examples correct. The problem is, since the function must be recursive, I cannot use a for a loop.

My code so far:

if a == 0 or b == 0:
    return[a, b]
if a >= 2 * b:
    a -= 2 * b
    if a == 0 or b == 0:
        return [a, b]
if b >= 2 * a:
    b -= 2 * a
    if a == 0 or b == 0:
        return [a, b]
return [a, b]

CodePudding user response:

This is the recursive function you need:

def f(a, b):
    if a == 0 or b == 0: # step 1
        return [a, b]

    if a >= 2 * b: # step 2
        a = a - 2 * b
        return f(a, b) # recursive call
    
    if b >= 2 * a: # step 3
        b =  b - 2 * a
        return f(a, b) # recursive call

    return [a, b] 

Testing f with the inputs you have provided:

>>> f(6, 19)
[6, 7]
>>> f(2, 1)
[0, 1]
>>> f(22, 5) 
[0, 1]
>>> f(8796203,7556)
[1019, 1442]

CodePudding user response:

You can use this:

def calculate(a,b):

    if b==0 or a==0:
        print(a,b)
    elif a >= 2*b :
        a = a - 2*b
        calculate(a,b)
    elif b >= 2*a:
        b = b - 2*a
        calculate(a,b)
    else:
        print(a,b)

# Testing
calculate(8796203,7556)

And this one with return function:

def calculate(a,b):

    if b==0 or a==0:
        return [a,b]
    elif a >= 2*b :
        a = a - 2*b
        return calculate(a,b)
    elif b >= 2*a:
        b = b - 2*a
        return calculate(a,b)
    else:
        return [a,b]

x = calculate(8796203,7556)
print(x)
  • Related