Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Logical math operations

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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]

>Solution :

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]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading