DEV Community

Hariprasath
Hariprasath

Posted on

Recursion For Factorial Easyyyy

b = 6
6 * 5 * 4 * 3 * 2 * 1

so we need to get the num less than before
so

function factorial(b){
    if(b === 0){
      return 1
    }
    else {
      b * factorial(b-1) 
}

Enter fullscreen mode Exit fullscreen mode

6 * factorial(6-1){
if(5 === 0){return 1} // false
else {5 * factorial(5-1) //true
{if(4 === 0){return 1} // false
else {4*factorial(4-1) //true
{if(3 === 0){return 1} // false
else {3 * factorial(3-1) //true
{if(2 === 0){return 1} //false
else {2 * factorial(2-1) //true
{if(1 === 0){return 1} // false
else {1 * factorial(1 -1) //true
{if(0 === 0){return 1} //true
else {0 * factorial(0-1)} // false
}}}}}}}}}}}}

here the function dosent call in every return but after calling upto n === 0 it saves each function value and multiple from right to left

like factorial(0) = 1
factorial(1) * factorial(0) = 1 * 1
factorial(2) * factorial(1) = 2 * 1
factorial(3) * factorial(2) = 3 * 2
factorial(4) * factorial(3) = 4 * 6
factorial(5) * factorial(4) = 5 * 24
factorial(6) * factorial(5) = 6 * 120

it call the function after stacking in top order
the last called function is on top of stack

Heroku

Amplify your impact where it matters most — building exceptional apps.

Leave the infrastructure headaches to us, while you focus on pushing boundaries, realizing your vision, and making a lasting impression on your users.

Get Started

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more