Implement the function power() in power() that takes two integer arguments a and
ID: 3814095 • Letter: I
Question
Implement the function power() in power() that takes two integer arguments a and b and returns the value of a^b, computed recursively using the recurrence equation a^b = {1 if b = 0, aa^b - 1 if b is odd, (a^2)^b/2 if b is even. $python power.py 3 5 243 import stdio import sys # Returns a to the power b, computed recursively, def power(a, b): # Test client [DO NOT EDIT]. Reads integers a and b from command line and # writes the value of a to the power b, computed recursively, def _main(): a = int(sys.argv[1]) b = int(sys.argv[2]) stdio.writeln(power(a, b)) if _name_ = = '_main_': main()Explanation / Answer
Here is the code for you:
#!/usr/bin/python
import stdio
import sys
# Returns a to the power b, computed recursively.
def power(a, b):
if b == 0:
return 1
elif b % 2 == 1:
return a * power(a, b-1)
else:
return power(a*a, b/2)
# Test client. Reads integers a and b from command line and
# writes the value of a to the power b, computed recursively.
def _main():
a = int(sys.argv[1])
b = int(sys.argv[2])
stdio.writeln(power(a, b))
if __name__ == '__main__':
_main()