If you're seeing this message, it means we're having trouble loading external resources on our website.

Hvis du er bak et webfilter, vær vennlig å sørge for at domenene .kastatic.org og .kastatic.org ikke er blokkert.

Hovedinnhold

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 xn, where x is any real number and n is any integer. It's easy if n is 0, since x0=1 no matter what x is. That's a good base case.
So now let's see what happens when n is positive. Let's start by recalling that when you multiply powers of x, you add the exponents: xaxb=xa+b for any base x and any exponents a and b. Therefore, if n is positive and even, then xn=xn/2xn/2. If you were to compute y=xn/2 recursively, then you could compute xn as yy. What if n is positive and odd? Then xn=xn1x, and n1 either is 0 or is positive and even. We just saw how to compute powers of x when the exponent either is 0 or is positive and even. Therefore, you could compute xn1 recursively, and then use this result to compute xn=xn1x.
What about when n is negative? Then xn=1/xn, and the exponent n is positive, since it's the negation of a negative number. So you can compute xn recursively and take its reciprocal.
Putting these observations together, we get the following recursive algorithm for computing xn:
  • The base case is when n=0, and x0=1.
  • If n is positive and even, recursively compute y=xn/2, and then xn=yy. Notice that you can get away with making just one recursive call in this case, computing xn/2 just once, and then you multiply the result of this recursive call by itself.
  • If n is positive and odd, recursively compute xn1, so that the exponent either is 0 or is positive and even. Then, xn=xn1x.
  • If n is negative, recursively compute xn, so that the exponent becomes positive. Then, xn=1/xn.

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.
Forstår du engelsk? Klikk her for å se flere diskusjoner på Khan Academys engelske side.