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
Rekursiv fakultet
For positive values of , let's write as we did before, as a product of numbers starting from and going down to 1: = . But notice that is another way of writing , and so we can say that . Did you see what we just did? We wrote as a product in which one of the factors is . We said that you can compute by computing and then multiplying the result of computing by . You can compute the factorial function on by first computing the factorial function on . We say that computing is a subproblem that we solve to compute !.
Let's look at an example: computing 5!.
- You can compute 5! as
. - Now you need to solve the subproblem of computing 4!, which you can compute as
!. - Now you need to solve the subproblem of computing 3!, which is
. - Now 2!, which is
. - Now you need to compute 1!. You could say that 1! equals 1, because it's the product of all the integers from 1 through 1. Or you can apply the formula that
. Let's do it by applying the formula. - We defined 0! to equal 1.
- Now you can compute
. - Having computed
, you can compute . - Having computed
, you can compute . - Having computed
, you can compute . - Finally, having computed
, you can finish up by computing .
So now we have another way of thinking about how to compute the value of , for all nonnegative integers :
- If
, then declare that . - Otherwise,
must be positive. Solve the subproblem of computing , multiply this result by , and declare equal to the result of this product.
When we're computing in this way, we call the first case, where we immediately know the answer, the base case, and we call the second case, where we have to compute the same function but on a different value, the recursive case.
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.