Hovedinnhold
Kurs: (Informatikk > Enhet 1
Leksjon 6: Rekursive algoritmer- Rekursjon
- Fraktal funksjoner
- Utfordring: Iterative fakultet
- Rekursiv fakultet
- Utfordring: Rekursiv fakultet
- Egenskaper for rekursive algoritmer
- Å bruke rekursjon for å avgjøre om et ord er en palindrome (er ord som er det samme forlengs og baklengs)
- Utfordringen: er en linje en palindrome?
- Generere potensen av et tall
- Utfordring: Rekursive potenser
- The Sierpinski gasket
- Prosjekt: Rekursiv kunst
© 2024 Khan AcademyBrukervilkårPersonvernVarsel om informasjonskapsler
Generere potensen av et tall
Although JavaScript has a builtin
pow
function that computes powers of a number, you can write a similar function recursively, and it can be very efficient. The only hitch is that the exponent has to be an integer.Suppose you want to compute , where is any real number and is any integer. It's easy if is 0, since no matter what is. That's a good base case.
So now let's see what happens when is positive. Let's start by recalling that when you multiply powers of , you add the exponents: for any base and any exponents and . Therefore, if is positive and even, then . If you were to compute recursively, then you could compute as . What if is positive and odd? Then , and either is 0 or is positive and even. We just saw how to compute powers of when the exponent either is 0 or is positive and even. Therefore, you could compute recursively, and then use this result to compute .
What about when is negative? Then , and the exponent is positive, since it's the negation of a negative number. So you can compute recursively and take its reciprocal.
Putting these observations together, we get the following recursive algorithm for computing :
- The base case is when
, and . - If
is positive and even, recursively compute , and then . Notice that you can get away with making just one recursive call in this case, computing just once, and then you multiply the result of this recursive call by itself. - If
is positive and odd, recursively compute , so that the exponent either is 0 or is positive and even. Then, . - If
is negative, recursively compute , so that the exponent becomes positive. Then, .
This content is a collaboration of Dartmouth Computer Science professors Thomas Cormen and Devin Balkcom, plus the Khan Academy computing curriculum team. The content is licensed CC-BY-NC-SA.
Ønsker du å delta i samtalen?
Ingen innlegg enda.