Reputation: 37
I'm doing my course exercise that states the following:
A number a
is a power of b
if:
b
a/b
is a power of b
.Write a function called is_power
that takes parameters a
and b
and returns True
if a
is a power of b
.
However, I have to do it using recursion and somehow using the following function:
def is_divisible(x, y):
if x % y == 0:
return True
else:
return False
I don't know exactly where they relate to each other but yeah, that's what I'm supposed to do.
What I did so far (without using the above function) is:
def is_power(a, b):
while a % b == 0:
if a == b: return True
a = a / b
return False
print(10, 2)
Thoughts on why I have no output/how to relate the is_divisible
function to is_power
?
Upvotes: 0
Views: 1510
Reputation: 31
If a
is a power of b
, then a
is divisible by b
. Logically the contrapositive is also true i.e. if a
is not divisible by b
, then a
is not a power of b
. This is where your is_divisible
function possibly comes in - to break out of the recursion, not to propagate it.
In case is_divisible(a, b)
returns True
, then you go to your second condition, a/b
is a power of b
. Do we have a function that when given two numbers checks if one of them is a power of the other? This is the condition to propagate the recursion.
Think about what your base case will be if a
does happen to be a power of b
.
Upvotes: 3