Implement the functions sum_iter() and sum_rec() in suxt_of_ints.py that take an
ID: 3814092 • Letter: I
Question
Implement the functions sum_iter() and sum_rec() in suxt_of_ints.py that take an integer n as argument and return the sum S(n) = 1+2 + 3+.....+n, computed iteratively (using a loop) and recursively. The recurrence equation for the latter implementation is S(n) = {1 if n = n + S(n - 1) if n > 1. $ python 8UB_of_int8.py 100 $050 $ 050 import stdio import sys # Returns the sum S(n) = 1 + 2 + ... + n, computed iteratively. def sum iter(n): # Returns the sum S(n) = 1 + 2 + ... + n, computed recursively, def sum rec(n): # Test client [DO NOT EDIT]. Reads an integer n from command line and # writes the sum S(n) = 1 + 2 + ... + n, computed both iteratively and # recursively, def _main(): n = int(sys.argv[1]) stdio.writeln(sum_iter(n)) stdio.writeln(sum rec(n)) if _name_ = '_main_'_main()Explanation / Answer
Dear Student,
Here is the program..
NOTE: Please note that the following program has been tested on ubuntu 14.04 system an dcompiled using python library.
-------------------------------------------------------------------------------------------------------------------------------------
program...
------------------------------------------------------------------------------------------------------------------------------------
import sys
import stdio
def sum_iter(n):
Sum = 0
if n == 1:
return 1
while n>1:
theSum = Sum + n - 1;
return theSum
def recur_sum(n):
"""Function to return the sum
of natural numbers using recursion"""
if n == 1:
return n
else:
return n + recur_sum(n-1)
def _main():
n = int(sys.argv[1])
stdio.writeln(sum_iter(n))
stdio.writeln(sum_rec(n))
if __name__ == '__main__':
_main()
---------------------------------------------------------------------------------------------------------------------------------------
Output: