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

recursively calculate if x is power of b

The assignment is to write a recursive function that receives 2 whole non-negative numbers b, x, and returns True if there’s a natural integer n so that b**n=x and False if not. I’m not allowed to use any math operators or loops, except % to determine if a number is even or odd.
but i do have external functions that i can use. Which can add 2 numbers, multiply 2 numbers, and divides a number by 2. also i can write helper function that i can use in the main function.

this is what i got so far, but it only works if b is in the form of 2^y (2,4,8,16 etc)

def is_power(b, x):
    if b == x:
        return True
    if b > x:
        return False
    return is_power(add(b, b), x)  # the func 'add' just adds 2 numbers

Furthermore, the complexity needs to be O(logb * logx)
Thank you.

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

>Solution :

You can essentially keep multiplying b by b until you reach, or pass, n.

A recursive implementation of this, using a helper function, could look something like this:

def is_power(b, x):
    if b == 1:          # Check special case
        return x == 1
    return helper(1, b, x)

def helper(acc, b, x):
    if acc == x:
        return True
    elif acc > x:
        return False
    else:
        return helper(mul(acc, b), b, x)
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