In: Computer Science
The power function for ^2, ^3, and ^4 can be defined recursively as follows:
n is the number whose power is to be computed.
If power is 2, return n * n
If power is 3, return n * power(n,2)
If power is 4, return n * power(n,3)
For all other powers, this function will return -1.
The python program is as follows:
#function power
#first parameter is the number whose power is to be calculated
#second parameter is the number for the power operation ^2, ^3 or ^4
#if invalid value of power is passed, the function returns -1
def power(n,p):
    
    #for ^2
    if (p == 2):
        return n*n
    
    #for ^3
    if (p == 3):
        return n*power(n,2)      #recursive call
        
    #for ^4
    if (p == 4):
        return n*power(n,3)      #recursive call
    
    #for invalid
    else:
        return -1
        
print(power(4,2))      #4^2
print(power(3,3))      #3^3
print(power(2,4))      #2^4
print(power(4,6))      #4^6  -> invalid power 6
Output:

Code snippet:
