In: Computer Science
Python: Write a function named power() that calculates rootpow recursively. It receives two arguments root (float) and pow (int) > = 1, and it returns the result root raised to power pow. The recursion of the power function is defined as: Base case: rootpow = root, if pow = 1 Recursive case: rootpow = root* rootpow-1 , otherwise. b) Develop a greatestC( ) function that determines the greatest common divisor of two integer numbers. Test greatestC() in a simple main program on the following numbers: 12 and 24; 50 and 10; 33649 and 17043. The recursive definition of the gcd function is as follows: Base case: greatestC(x, y) = x if y = 0 Recursive case: greatestC(x, y) = greatestC(x, x % y) otherwise, where % is the modulus operator.
SOLUTION FOR ROOT POWER
def power(root,rootpow):
if(rootpow==1 or root==1 or root==0):
return root
elif(rootpow<=0):
return 1
else:
return root*power(root,rootpow-1)
print("power(1,2)",power(1,2))
print("power(5,0)",power(5,0))
print("power(9,1)",power(9,1))
print("power(2,3)",power(2,3))
print("power(7,-2)",power(7,-1))
"""Here, we are defining power function with 2 parameters of root and power and checking if the power is 1 or the root (base) is 1 or 0 then we'll simply return the root without any computation. Then we'll check if the power is less than or equal to 0, simply returns the number itself or we'll compute the power of the number"""
SOLUTION FOR GCD (GREATEST COMMON DIVISOR) OR HCF (HIGHEST COMMON FACTOR)
def greatestC(x,y):
if (y==0):
return x
else:
return greatestC(y,x%y)
print("greatestC(12,24)",greatestC(12,24))
print("greatestC(50,10)",greatestC(50,10))
print("greatestC(33649,17043)",greatestC(33649,17043))
"""Here, we are defining greatestC function with 2 parameters of number 1 and number 2 and checking if the number 2 simply return the number 1 after operating with modulo function of number2"""