Main content
Computer science
Course: Computer science > Unit 1
Lesson 6: Recursive algorithms- Recursion
- The factorial function
- Challenge: Iterative factorial
- Recursive factorial
- Challenge: Recursive factorial
- Properties of recursive algorithms
- Using recursion to determine whether a word is a palindrome
- Challenge: is a string a palindrome?
- Computing powers of a number
- Challenge: Recursive powers
- Multiple recursion with the Sierpinski gasket
- Improving efficiency of recursive functions
- Project: Recursive art
© 2023 Khan AcademyTerms of usePrivacy PolicyCookie Notice
The factorial function
For our first example of recursion, let's look at how to compute the factorial function. We indicate the factorial of n by n, !. It's just the product of the integers 1 through n. For example, 5! equals 1, dot, 2, dot, 3, dot, 4, dot, 5, or 120. (Note: Wherever we're talking about the factorial function, all exclamation points refer to the factorial function and are not for emphasis.)
You might wonder why we would possibly care about the factorial function. It's very useful for when we're trying to count how many different orders there are for things or how many different ways we can combine things. For example, how many different ways can we arrange n things? We have n choices for the first thing. For each of these n choices, we are left with n, minus, 1 choices for the second thing, so that we have n, dot, left parenthesis, n, minus, 1, right parenthesis choices for the first two things, in order. Now, for each of these first two choices, we have n, minus, 2 choices for the third thing, giving us n, dot, left parenthesis, n, minus, 1, right parenthesis, dot, left parenthesis, n, minus, 2, right parenthesis choices for the first three things, in order. And so on, until we get down to just two things remaining, and then just one thing remaining. Altogether, we have n, dot, left parenthesis, n, minus, 1, right parenthesis, dot, left parenthesis, n, minus, 2, right parenthesis, \@cdots, 2, dot, 1 ways that we can order n things. And that product is just n, ! (n factorial), but with the product written going from n down to 1 rather than from 1 up to n.
Another use for the factorial function is to count how many ways you can choose things from a collection of things. For example, suppose you are going on a trip and you want to choose which T-shirts to take. Let's say that you own n T-shirts but you have room to pack only k of them. How many different ways can you choose k T-shirts from a collection of n T-shirts? The answer (which we won't try to justify here) turns out to be n, !, slash, left parenthesis, k, !, dot, left parenthesis, n, minus, k, right parenthesis, !, right parenthesis. So the factorial function can be pretty useful. You can learn more about permutations and combinations here, but you don't need to understand them to implement a factorial algorithm.
The factorial function is defined for all positive integers, along with 0. What value should 0! have? It's the product of all integers greater than or equal to 1 and less than or equal to 0. But there are no such integers. Therefore, we define 0! to equal the identity for multiplication, which is 1. (Defining 0! = 1 meshes nicely with the formula for choosing k things out of n things. Suppose that we want to know how many ways there are to choose n things out of n things. That's easy, because there is only one way: choose all n things. So now we know that, using our formula, n, !, slash, left parenthesis, n, !, dot, left parenthesis, n, minus, n, right parenthesis, !, right parenthesis should equal 1. But left parenthesis, n, minus, n, right parenthesis, ! is 0!, so now we know that n, !, slash, left parenthesis, n, !, dot, 0, !, right parenthesis should equal 1. If we cancel out the n, ! in both the numerator and denominator, we see that 1, slash, left parenthesis, 0, !, right parenthesis should equal 1, and it does because 0! equals 1.)
So now we have a way to think about n, !. It equals 1 when n, equals, 0, and it equals 1, dot, 2, \@cdots, left parenthesis, n, minus, 1, right parenthesis, dot, n when n is positive.
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.
Want to join the conversation?
- Can someone clarify why 0! = 1? I'm really getting lost on the last paragraph, specifically:
"It's the product of all integers greater than or equal to 1 and less than or equal to 0. But there are no such integers. Therefore, we define 0! to equal the identity for multiplication, which is 1."(32 votes)- n! is the product of all integers greater than or equal to 1 and less than or equal to n
or more simply:
the product of all integers from 1 to n (starting at 1 and going up to n)
i.e. 1 * 2 * 3 * 4 * 5 * ... * n-1 * n
so when n=0 we have
the product of all integers from 1 to 0 (starting at 1 and going up to 0)
But 1 is already larger than 0 so there are no integers from 1 to 0 (counting up)
So what do we use for the product of no integers ?
We use 1.
Why ?
Because it is convenient, it makes makes math easier, and most importantly it makes our formulas that could calculate 0! make sense. The article gives an example of how it makes our formulas make sense. It shows that when we calculate the number of ways of choosing a group of n items from n items (which should obviously be 1), the formula needs 0! to be 1.
Hope this makes sense(78 votes)
- I'm still really confused on this subject. If one of y'all could explain how n and n! work in a really simple almost kindergarten version, that would be amazing! I'm trying to relate this so something that I have already learned/know about so the concept will be easily identified and understandable. Thanks in advance!(9 votes)
- n! is the product (multiplication) of all the whole numbers from n to 1
e.g.
3! = 3 * 2 * 1
2! = 2 * 1
1! = 1
0! is a special case. We say that 0! = 1.
We use factorials when we look at permutations and combinations.
Permutations tell us how many different ways we can arrange things if their order matters.
Combinations tells us how many ways we can choose k item from n items if their order does not matter.
If we have n different items, then we can permute (arrange) them in n! different arrangements.
e.g.
If we have 3 items: A,B,C then there are 3! = 3 * 2 * 1 = 6 different permuations
Here they are:
ABC, ACB, BAC, BCA, CAB, CBA
If we have n items there are n!/(k! * (n-k)!) different combinations of choosing k items from those n items.
e.g.
If we 5 items: A,B,C,D,E and we want to choose 2 items at a time then there are:
5!/( 2! * (5-2)!) = 5! / (2! * 3!) = 120/(2 * 6) = 10 different combinations
Here they are:
AB, AC, AD, AE, BC, BD, BE, CD, CE, DE
Note: CB would be considered as the same combination as BC, because order doesn't matter
For more info check out:
https://www.khanacademy.org/math/precalculus/prob-comb/combinatorics-precalc/v/factorial-and-counting-seat-arrangements
https://www.khanacademy.org/math/precalculus/prob-comb/combinations/v/introduction-to-combinations(24 votes)
- In the for loop when we say result = result * i; how do these two results not override each other? How does the computer know that one result is referring to the previous sum of the multiplications and the other is that value times i?(2 votes)
result = result * i;
is really telling the computer to do this:
1. Compute the value ofresult * i
and store it somewhere
2. Take the stored value and assignresult
to that value
When you use the=
operator, the entire right hand side is evaluated to some value, and then that value is put into the left hand side variable. Everything is happening in steps, not all at once.(12 votes)
- In the example given above where you have n t-shirts and want to be able to pack only k amount, the given formula is n!/(k!⋅(n−k)!)
In the permutations course given in the link, the formula is stated to to be n!/(n-k)!
Can someone explain where the extra k! in the denominator came from?(3 votes)- n!/(k! (n-k)!) would tell you the number of ways you could pick k t-shirts from n shirts where the order does not matter
n!/(n-k)! would tell you the number of ways you could pick k t-shirts from n shirts where the order matters e.g. the first shirt you pick you write 1 on it, the 2nd shirt you write 2 on it, etc.
Dividing by k! accounts for the number of ways each selection of k shirts will be counted.
e.g. Suppose k= 3 and one possible selection of shirts is shirts: 5, 7 and 13
You could have picked those shirts in these 3! = 6 different ways:
5 then 7 then 13 or,
5 then 13 then 7 or,
7 then 5 then 13 or,
7 then 13 then 5 or,
13 then 5 then 7 or,
13 then 7 then 5(8 votes)
- when you are writing python code for any given factorial say one that a user enters like 11. what if you also need to determine which values are odd and which are even is it true that they are always even? do you ever get odd results going down thru the range values?(2 votes)
- All the results of the factorial function are always even UNLESS it's 1! or 0!. Therefore for all n! such that n doesn't equal 0 or 1 the result is even. That's because 0! and 1! equals 1, which is odd.
This is because an odd number multiplied by an even number is even, and an even number multiplied by an even number is also even. Therefore for every n! where n > 1 an even number is involved, making the answer even.
Hope that helped!(2 votes)
- When doing factorials with code, I find that people use a for loop to get the answer, but I want to use an equation that's not tedious like the method we use.
Just like how there's an equation for triangular numbers (these are numbers that are themselves added to every integer below them), isn't there an equation for factorials?(1 vote)- There isn't an equation for n! like the one you are asking for, but there is an approximation (it is more accurate as n becomes larger) called Stirling's approximation:
n! ~ sqrt( 2 * Pi * n ) * ( n / e )^n
where e is Euler's number i.e. ~2.71828
e.g. 10! = 3,628,800
Stirling's Approximation says:
10! ~ sqrt( 2 * Pi * n ) * ( n / e )^n = sqrt( 2 * Pi * 10 ) * ( 10 / e )^10 = 3,598,696
Which is within 1% of the actual value
For more info see: https://en.wikipedia.org/wiki/Stirling%27s_approximation(4 votes)
- I have a question about the next challenge
My code works and even passes the auto-grader but it doesn't match the hint
[Edited to remove code]
in the for loop, it wants me to put i <= n but that messes everything up. It works perfectly without the equals. I'm sure there is a reason for the <= and if anyone could shed some light on it, i'd greatly appreciate it!!(1 vote)- The hint code only provides a suggested approach to solving the problem. While the exercise designer has some solution in mind that looks like the hint code, the grader may also accept other valid solutions. These other solutions may or may not match all the features of the hint code.
If one wanted to multiply some result by the numbers from 1 to n, in order, a loop condition of i <=n would make sense. If you follow a different approach it might not.(3 votes)
- The autograder isn't working for me. The console is showing me that the code works, but the autograder doesn't.(2 votes)
- That happened to me too. I reported it and am hoping they'll fix the issue. (the console showed it worked, and my code is just like the code in the hint).(1 vote)
- I'm confused on this excerpt:
"For each of these n n nn choices, we are left with n−1 n-1 n−1n, minus, 1 choices for the second thing, so that we have n⋅(n−1) n \cdot (n-1) n⋅(n−1)n, dot, left parenthesis, n, minus, 1, right parenthesis choices for the first two things, in order. Now, for each of these first two choices, we have n−2 n-2 n−2n, minus, 2 choices for the third thing, giving us n⋅(n−1)⋅(n−2) n \cdot (n-1) \cdot (n-2) n⋅(n−1)⋅(n−2)n, dot, left parenthesis, n, minus, 1, right parenthesis, dot, left parenthesis, n, minus, 2, right parenthesis choices for the first three things."
What is the reasoning behind why calculate the factorial in the way mentioned?(1 vote)- They wrote it like this to set you up to understand how to calculate iterative and recursive factorials.
If you write 4! like this:
4! = 4 * 3 * 2 * 1
This gives you the iterative way to find 4!
That is, loop through the numbers from 4 to 1 (or 1 to 4) and multiply them together.
Later on, you will write 4! like this:
4! = 4 * 3!
This gives you the recursive way to find 4!
That is, multiply 4 by 3!. But then we need to figure out what 3! is first.
Which we get by multiplying 3 * 2!. But then we need to figure out what 2! is first.
Which we get by multiplying 2 * 1!. But then we need to figure out what 1! is first.
Which we get by multiplying 1 * 0!. But then we need to figure out what 0! is first.
0! is just 1. So now we can go back up each of the steps and complete our calculations.(3 votes)
- I can not get the next challenge completed what am i doing wrong? Here is my code (edited to only show relevant parts)
var result = 1;
for(var i= result; i>=n; i--) {
n=i*n;
}
I looked through the comments for help but all I could find were Cameron's cryptic answers can I have a more firm hint please. (not saying Cameron did a bad job just saying I can not understand their hints)(1 vote)- Let's review some for loop basics:
//This for loop will:
//-begin the counter at start,
//-do some stuff each loop
//-then increment counter
//until the counter exceeds last
for( var counter = start; counter <= last; counter++){
//this is the body where we do some stuff
}
A simple for loop that would print out the numbers from 1 to 10 would be:for( var i = 1; i <= 10; counter++){
println(i);
}
Many find the BASIC version of this a bit easier to understand:FOR I=1 TO 10
PRINT(I)
NEXT I
There are a couple of things that you almost never want to do inside the body of the for loop:
1) change the value of the counter
2) change the value of the number you are stepping the counter towards e.g.last
in the first example
Doing either of those usually leads to unpredictable behaviour.
Here's some extra hints using the hint code:var factorial = function(n) {
//this will set the value of result before we start looping
var result = ;
//think about calculating n! by hand
// n! = 1 * 2 * 3 * ... * n-2 * n-1 * n
// what number do we start at ?
// what number do we end at ?
for(var i = ; i <= ; ) {
//we need to update the value of result here, so that it
//will be equal to n! by the time we stop looping
//changing the counter i, or the value that it is going to, would be bad here
;
}
//we are returning the value of result here
//so result should now hold the value of n!
return result;
};
Good Luck(2 votes)