Answer:
Here is the Python program.
def is_power(a, b): # function that takes two positive integers a and b as arguments
if a == b: #first base case: if both the numbers are equal
return True #returns True if a=b
elif b==1: #second base case: if the value of b is equal to 1
return False #returns False if b==1
else: #recursive step
return a%b==0 and is_power(a/b, b) #call divisible method and is_power method recursively to determine if the number is the power of another
Step-by-step explanation:
return a%b==0 and is_power(a/b, b) statement basically means a number, a, is a power of b if it is divisible by b and a/b is a power of b
In the statement return a%b==0 and is_power(a/b, b) , a%b==0 checks whether a number a is completely divisible by number b. The % modulo operator is used to find the remainder of the division. If the remainder of the division is 0 it means that the number a is completely divisible by b otherwise it is not completely divisible.
The second part of the above statement calls is_power() method recursively. The and operator between the two means that both of the parts of the statement should be true in order to return true.
is_power() method takes two numbers a and b as arguments. First the method checks for two base cases. The first base case: a == b. Suppose the value of a = 1 and b =1 Then a is a power of b if both of them are equal. So this returns True if both a and b are equal.
Now the program checks its second base case b == 1. Lets say a is 10 and b is 1 Then the function returns False because there is no positive integer that is the power of 1 except 1 itself.
Now the recursive case return return a%b==0 and is_power(a/b, b) takes the modulo of a and b, and is_power method is called recursively in this statement. For example if a is 27 and b is 3 then this statement:
a%b==0 is True because 27 is completely divisible by 3 i.e. 27 % 3 = 0
is_power(a/b,b) is called. This method will be called recursively until the base condition is reached. You can see it has two arguments a/b and b. a/b = 27/3 = 9 So this becomes is_power(9,3)
The base cases are checked. Now this else statement is again executed return a%b==0 and is_power(a/b, b) as none of the above base cases is evaluated to true. when a%b==0 is True as 9 is completely divisible by 3 i.e. 9%3 =0 and is_power returns (9/3,3) which is (3,3). So this becomes is_power(3,3)
Now as value of a becomes 3 and value of b becomes 3. So the first base case a == b: condition now evaluates to true as 3=3. So it returns True.
Now in order to check the working of this function you can call this method as:
print(is_power(27, 3))
The output is:
True