Printer-friendly versionPrinter-friendly version

Consider the problem of computing the exponential of a given number. We would like a procedure that takes as arguments a base b and a positive integer exponent n and computes bn. One way to do this is via the recursive definition

b^n = b*b^(n-1) and b^0 = 1

which translates readily into the procedure

(define (expt b n)
  (if (= n 0)
      (* b (expt b (- n 1)))))

This is a linear recursive process, which requires Θ(n) steps and Θ(n) space. Just as with factorial, we can readily formulate an equivalent linear iteration:

(define (expt b n)
  (expt-iter b n 1))

(define (expt-iter b counter product)
  (if (= counter 0)
      (expt-iter b
                (- counter 1)
                (* b product)))) 

This version requires Θ(n) steps and Θ(1) space.

We can compute exponentials in fewer steps by using successive squaring. For instance, rather than computing b8 as

b^n = b*b^(n-1) and b^0 = 1

we can compute it using three multiplications:

b^2 = b * b, b^4 = b^2 * b^2, b^8 = b^4 * b^4

This method works fine for exponents that are powers of 2. We can also take advantage of successive squaring in computing exponentials in general if we use the rule

b * (b * (b * (b * (b * (b * (b * b))))))

We can express this method as a procedure:

(define (fast-expt b n)
  (cond ((= n 0) 1)
        ((even? n) (square (fast-expt b (/ n 2))))
        (else (* b (fast-expt b (- n 1))))))

where the predicate to test whether an integer is even is defined in terms of the primitive procedure remainder by

(define (even? n)
  (= (remainder n 2) 0))

The process evolved by fast-expt grows logarithmically with n in both space and number of steps. To see this, observe that computing b2n using fast-expt requires only one more multiplication than computing bn. The size of the exponent we can compute therefore doubles (approximately) with every new multiplication we are allowed. Thus, the number of multiplications required for an exponent of n grows about as fast as the logarithm of n to the base 2. The process has Θ(log n) growth.[37]

The difference between Θ(log n) growth and Θ(n) growth becomes striking as n becomes large. For example, fast-expt for n = 1000 requires only 14 multiplications.[38] It is also possible to use the idea of successive squaring to devise an iterative algorithm that computes exponentials with a logarithmic number of steps (see exercise 1.16), although, as is often the case with iterative algorithms, this is not written down so straightforwardly as the recursive algorithm.[39]

[37] More precisely, the number of multiplications required is equal to 1 less than the log base 2 of n plus the number of ones in the binary representation of n. This total is always less than twice the log base 2 of n. The arbitrary constants k1 and k2 in the definition of order notation imply that, for a logarithmic process, the base to which logarithms are taken does not matter, so all such processes are described as Θ(log n). [back]
[38] You may wonder why anyone would care about raising numbers to the 1000th power. See section 1.2.6. [back]
[39] This iterative algorithm is ancient. It appears in the Chandah-sutra by Áchárya Pingala, written before 200 B.C. See Knuth 1981, section 4.6.3, for a full discussion and analysis of this and other methods of exponentiation. [back]


Exercise 1.16

Design a procedure that evolves an iterative exponentiation process that uses successive squaring and uses a logarithmic number of steps, as does fast-expt. (Hint: Using the observation that (bn/2)2 = (b2)n/2, keep, along with the exponent n and the base b, an additional state variable a, and define the state transformation in such a way that the product a bn is unchanged from state to state. At the beginning of the process a is taken to be 1, and the answer is given by the value of a at the end of the process. In general, the technique of defining an invariant quantity that remains unchanged from state to state is a powerful way to think about the design of iterative algorithms.)

Exercise 1.17

The exponentiation algorithms in this section are based on performing exponentiation by means of repeated multiplication. In a similar way, one can perform integer multiplication by means of repeated addition. The following multiplication procedure (in which it is assumed that our language can only add, not multiply) is analogous to the expt procedure:

(define (* a b)
  (if (= b 0)
      (+ a (* a (- b 1)))))

This algorithm takes a number of steps that is linear in b. Now suppose we include, together with addition, operations double, which doubles an integer, and halve, which divides an (even) integer by 2. Using these, design a multiplication procedure analogous to fast-expt that uses a logarithmic number of steps.

Exercise 1.18

Using the results of exercises 1.16 and 1.17, devise a procedure that generates an iterative process for multiplying two integers in terms of adding, doubling, and halving and uses a logarithmic number of steps.[40]

[40] This algorithm, which is sometimes known as the “Russian peasant method” of multiplication, is ancient. Examples of its use are found in the Rhind Papyrus, one of the two oldest mathematical documents in existence, written about 1700 B.C.(and copied from an even older document) by an Egyptian scribe named A’h-mose. [back]

Exercise 1.19

There is a clever algorithm for computing the Fibonacci numbers in a logarithmic number of steps. Recall the transformation of the state variables a and b in the fib-iter process of section 1.2.2: aa + b and ba. Call this transformation T, and observe that applying T over and over again n times, starting with 1 and 0, produces the pair Fib(n + 1) and Fib(n). In other words, the Fibonacci numbers are produced by applying Tn, the nth power of the transformation T, starting with the pair (1,0). Now consider T to be the special case of p = 0 and q = 1 in a family of transformations Tpq, where Tpq transforms the pair (a,b) according to abq + aq + ap and bbp + aq. Show that if we apply such a transformation Tpq twice, the effect is the same as using a single transformation Tpq of the same form, and compute p’ and q’ in terms of p and q. This gives us an explicit way to square these transformations, and thus we can compute Tn using successive squaring, as in the fast-expt procedure. Put this all together to complete the following procedure, which runs in a logarithmic number of steps:[41]

(define (fib n)
  (fib-iter 1 0 0 1 n))
(define (fib-iter a b p q count)
  (cond ((= count 0) b)
        ((even? count)
         (fib-iter a
                   <??>      ; compute p'
                   <??>      ; compute q'
                   (/ count 2)))
        (else (fib-iter (+ (* b q) (* a q) (* a p))
                        (+ (* b p) (* a q))
                        (- count 1)))))
[41] This exercise was suggested to us by Joe Stoy, based on an example in Kaldewaij 1990. [back]


replica handbags wholesale china

Jerseys From China Cheap

nd article concentrates on the basal metabolic rate, or BMR.Because tennis does not require nearly as much vertical jumping as basketball, or the repetitive forward impact of running, jogging and track sports, the additional cushioning under the heel is not necessary. This is not the only hitch of internet shopping. Love is the most powerful force in the Wholesale Jerseys Supply universe. Ladies out there would definitely agree that shoesspecifically wearing lady designer shoesare a crucial part of both her overall personality and a reflection of her self-image. They also Lewis Jersey Ravens Lewis Jersey help with improving your inner personal / mental strength and with improving weight control and sleep. Split sole shoes tend to be a little more comfortable and provide better traction.Never con

Chris Myers Jersey

terned good-looking shoes, and in the south people wore palm fiber shoes.The unique thing about the Dubarry shoes is that they have been able to combine the functionality of the shoe as well as the fashion. The skin is Always equipped by * with sunscreen protection. Make sure you purchase versatile shoes, that will match with different outfits you have. You ought to have the solution to customize Kids Ryan Tannehill Game Jersey the scans in accordance to your choice, so that you can tailor it according to Youth Philip Wheeler Game Jersey your needs. Although Ugg Classic Short boots were fashioned to be worn unshod, they could also be worn with socks. Its also a good time to start planning those Christmas Womens Cameron Wake Elite Jersey presents, and kids shoes can fit the bill.Do not forget to check the quality of shoes and brand valu

UGG Outlet……………
UGG Outlet

Louis Vuitton Outlet…………………………………
Louis Vuitton Outlet

UGG Outlet………………
UGG Outlet

UGG Outlet…
UGG Outlet

Belanja Online Cari Voucher Diskon, deal dan Kupon di GrantonWor

Thank you for this interesting variety of information and I am very happy to be here, I just want to share about online shopping Cari Voucher Diskon, deal dan Kupon di GrantonWorld……………]…………….……………….……………………………

Qualcosa di conoscere il semplice fatto sistema Melissa gli stivali reali della collezione possono essere davvero facile accoppiati con lusso e perfino senza dubbio razionale, La particolare nuovo Frye Melissa Trapunto. Avere eccessiva genere scarpa che ha un canale per quanto riguarda 17 componenti, panno umido di questo stivale ha una ricerca d’antiquariato che è certamente alternate neo in tutto questo string.Prime 10 [url=]ugg bailey button[/url] per ottenere un matrimonio.E ’ inutile dire che didn ” t prendiamo permanente prima eccellente del semplice popolare [url=]ugg saldi[/url] tentarono di sollevare specialmente i Wellington. Al 1875 ha finito per essere un terreno di 600 agenti di vendita legati alla formulazione di una qualsiasi delle molte molte soprascarpe.

Ovviamente, Un fratello insieme, sono genuini, Isola Crawford a Hong Kong, Oltre che, se il gestore ha a che fare con falsi, Esso infatti non decidere dove si può essere sarà inoltre applicarsi avere a disposizione. Ma, purtroppo, Taobao, Davvero non separare prodotti halal e soluzioni contraffatti sicuro, Illuminato leggere stupito, acqua [url=]stivali ugg[/url] è generalmente molto, Taobao UGG escursioni calzature per la campagna, Per visualizzare le opere d’arte e siti web, pertanto accettate esattamente lo stesso, tuttavia, Usual luogo di mille euro stivali, acquistati da tale dipartimento gente negozi on-line che molti dollari, si può osa tutto.

Sicuramente, dichiarata molti libra innumerevoli pad [url=]ugg stivali[/url] eccellente superiore alta è raccomandabile, uno è onesto stivali di gomma Hunter flatsoled, però in qualche modo ero stato molto probabilmente affidabilità brandnames,Bloomies avranno presto un compositore coltellaccio a venire con prodotti pregiati su una due alternative di dovrebbero ottenere UGGS. Hanno una grande varietà di [url=]ugg italia[/url] calzature là fuori con molto vere forme porno star e dimensioni. Presto si può anche sintonizzarsi 1 segno distintivo di ragazzi di tutti i giorni pantaloni liquidazione del costo di 12 dollari moobs.

Ollie ha una varietà di grandi dimensioni di tutto il percorso attraverso anteriore proprietà, così come i layout a pieghe, a contrasto colorazione per di più forme.Vai alla [url=]ugg jimmy choo[/url] questa prossimi mesi estivi e tirare fuori grandi infradito. Inoltre mesi frigide, Una scelta alternativa al boot del sistema [url=]ugg mini[/url] globale potrebbe essere la calzatura morbide perché a cavallo cavalcabile. Cose che si irrita per i creditori sbiancare, e anche in una varietà di pezzi più prossimi attraverso l’ dimostrare, è quando, in generale, rimane tempo in modo abbastanza dal lancio radice di eroi che hai appena può semplicemente stanca rapidamente mi permetta di spiegare la dovuta attenzione e pensare tanto per che i capitani delle barche inoltre cattivi in tutto.

Post new comment

  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <pre> <hr> <ul> <ol> <li> <dl> <dt> <dd> <img>
  • Lines and paragraphs break automatically.
  • Adds typographic refinements.

More information about formatting options