# This is a phython3 script import time, timeit # Four functions/methods that compute the sum of the first natural numbers: def sumRec(k): if(k==0): return 0 return k+sumRec(k-1) def sumIter(n): result = 0 for k in range(0,n+1): result+=k return result def sumPy(n): return sum(range(n+1)) def sumFormula(n): return n*(n+1)/2 # Comparing the execution time of the above: print('Evaluate the functions 9999 times at 990:') print('Evaluating the naive recursion takes ',timeit.timeit('sumRec(990)', setup='from __main__ import sumRec', number=9999),' seconds.') print('Evaluating the first iteration takes ',timeit.timeit('sumIter(990)', setup='from __main__ import sumIter', number=9999),' seconds.') print('Evaluating the second iteration takes ',timeit.timeit('sumPy(990)', setup='from __main__ import sumPy', number=9999),' seconds.') print('Evaluating the closed formula takes ',timeit.timeit('sumFormula(990)', setup='from __main__ import sumFormula', number=9999),' seconds.')