Contact
CoCalc Logo Icon
StoreFeaturesDocsShareSupport News AboutSign UpSign In
| Download

All published worksheets from http://sagenb.org

Views: 168742
Image: ubuntu2004
Problem\mathbf{Problem}: Computing ana^n for positive integer exponents. (See pages 157-159 from Chapter 5 of the textbook titled "Introduction to The Design and Analysis of Algorithms", 2nd Edition by A. Levitin) \\ Here expa\mathbf{expa} function is an implementation for the decrease(byone)andconquer\mathbf{decrease-(by-one)-and-conquer} algorithm (top down -recursive-). expb\mathbf{expb} function is an implementation for the decrease(byone)andconquer\mathbf{decrease-(by-one)-and-conquer} algorithm (bottom up same as the brute force algorithm). expc\mathbf{expc} function is an implementation for the decrease(byhalf)andconquer\mathbf{decrease-(by-half)-and-conquer} algorithm (top down -recursive- algorithm).
import sys sys.setrecursionlimit(15000) def expa(a,n): if n>1: return expa(a,n-1)*a else: return a def expb(a,n): product=a for g in range(0,n-1): product=a*product return product def expc(a,n): if (n%2)==0: return expc(a,n/2)^2 elif (n%2)==1 and n>1: return (expc(a,(n-1)/2)^2)*a elif n==1: return a
expa(2,40)