recursive factorial
Dec 1, 2016 at 2:40am
Hello everyone so I'm trying to understand this code.
I'm throwing 5 into the paramter aka int x, and the function starts
5 * 4 = 20
20 * 3 = 60
60 * 2 = 120
now x is finally 1 which is == to the base case and it returns the total number we calculated after the else statement.
Am I understanding this correctly or is there a better way to understand this. Thank you in advance for your help.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
|
#include <iostream>
using namespace std;
int factorialFinder(int x){
if(x==1){
return 1;
}else{
return x*factorialFinder(x-1);
}
}
int main()
{
cout << factorialFinder(5) << endl;
}
|
Last edited on Dec 1, 2016 at 2:43am
Dec 1, 2016 at 3:00am
Sounds reasonable, and it works too! :)
Dec 1, 2016 at 3:41am
> I'm throwing 5 into the paramter aka int x, and the function starts
> 5 * 4 = 20
> 20 * 3 = 60
> 60 * 2 = 120
It is the other way around.
factorial(5) == 5 * factorial(4) == 5 * 24 == 120
ie. factorial(5) == 5 * factorial(4) == 5 * ( 4 * factorial(3) ) == 5 * ( 4 * 6 ) == 5 * 24 == 120
etc.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
|
#include <iostream>
#include <string>
int factorial( int n )
{
static int depth = 0 ;
++depth ;
const std::string tab( depth*4, ' ' ) ;
std::cout << tab << depth << ". factorial(" << n << ") == " ;
if( n < 2 )
{
std::cout << 1 << '\n' ;
--depth ;
return 1 ;
}
else
{
std::cout << n << " * factorial(" << n-1 << ")\n" ;
const int fact_nm1 = factorial(n-1) ;
const int result = n * fact_nm1 ;
std::cout << tab << depth << ". factorial(" << n << ") == "
<< n << " * " << fact_nm1 << " == " << result << '\n' ;
--depth ;
return result ;
}
}
int main()
{
factorial(8) ;
}
|
1. factorial(8) == 8 * factorial(7)
2. factorial(7) == 7 * factorial(6)
3. factorial(6) == 6 * factorial(5)
4. factorial(5) == 5 * factorial(4)
5. factorial(4) == 4 * factorial(3)
6. factorial(3) == 3 * factorial(2)
7. factorial(2) == 2 * factorial(1)
8. factorial(1) == 1
7. factorial(2) == 2 * 1 == 2
6. factorial(3) == 3 * 2 == 6
5. factorial(4) == 4 * 6 == 24
4. factorial(5) == 5 * 24 == 120
3. factorial(6) == 6 * 120 == 720
2. factorial(7) == 7 * 720 == 5040
1. factorial(8) == 8 * 5040 == 40320 |
http://coliru.stacked-crooked.com/a/02e804b483393271
Topic archived. No new replies allowed.