Python Code that has two methods that computes xn using recursion and iteration.
ID: 3765869 • Letter: P
Question
Python Code that has two methods that computes xn using recursion and iteration. Remember xn is just x multiplied by itself n times. If n is 0 the result is defined to be 1, if n is one, the result is x, if n is two, the result is x times x, etc.
The main program will solicit two numbers (x and n) from the user and call your xn method to compute xn. X can be any decimal number, while n must be a non-negative integer. If a negative value is input for n, the program must display an error message and request input again until a legal value is input. When the method finally computes the value, it will return it to the main program which will display a message giving the original input numbers and the results of the power from the two functions (they had better be the same). It will then ask the user if he / she wants to determine xn for another pair of numbers.
Note that one method must use recursion to compute the value of xn, that is, the method calls itself until the value is computed.
Explanation / Answer
x=raw_input("Enter x")
n=raw_input("Enter n")
if(n>0)
rec=powrec(x,n)
itr=powitr(x,n)
disp(rec)
disp(itr)
else print("Error..n is negative");
def powrec(x, n):
if n == 0:
return 1
elif n%2 == 0:
powrecer = powrec(x, n/2)
return powrecer*powrecer
else:
return x*powrec(x, n-1)
def powitr(x,n)
total=1
for i in range(1,n):
total=total*(x)
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.