Factorial Function in JavaScript – Quick Explanation.

Factorial is a mathematical formula that multiplies a number by every number below it down to one.

when you see this code example,

function factorial(n) {
if (n == 0) {
return 1;
} else {
return factorial(n – 1) * n;
}
13
}
console.log(factorial(8))…


This content originally appeared on DEV Community and was authored by Jessica-Agorye

Factorial is a mathematical formula that multiplies a number by every number below it down to one.

when you see this code example,

function factorial(n) {
if (n == 0) {
return 1;
} else {
return factorial(n - 1) * n;
}
13
}
console.log(factorial(8));
// → 40320

Here's how it's solved

  • if n is 0, it returns 1 and ends the condition for recursion, else
  • if n is not 0, it calls itself with n-1 multiplied by n

Finding factorial(8)

factorial(n - 1) * n

n becomes 8 - we can say that 8 is the argument that is passed to the factorial function

factorial (n-1)*n

is simply

(8-1) * 8

which becomes

factorial (7 )* 8

First, find the factorial of 7 then multiply the result by 8

7! is 7x6x5x4x3x2x1 - which equals to 5040

Multiply the result of the factorial of 7 by 8

5040 * 8 equals 40320

Finir!


This content originally appeared on DEV Community and was authored by Jessica-Agorye


Print Share Comment Cite Upload Translate Updates
APA

Jessica-Agorye | Sciencx (2024-07-23T01:25:44+00:00) Factorial Function in JavaScript – Quick Explanation.. Retrieved from https://www.scien.cx/2024/07/23/factorial-function-in-javascript-quick-explanation/

MLA
" » Factorial Function in JavaScript – Quick Explanation.." Jessica-Agorye | Sciencx - Tuesday July 23, 2024, https://www.scien.cx/2024/07/23/factorial-function-in-javascript-quick-explanation/
HARVARD
Jessica-Agorye | Sciencx Tuesday July 23, 2024 » Factorial Function in JavaScript – Quick Explanation.., viewed ,<https://www.scien.cx/2024/07/23/factorial-function-in-javascript-quick-explanation/>
VANCOUVER
Jessica-Agorye | Sciencx - » Factorial Function in JavaScript – Quick Explanation.. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2024/07/23/factorial-function-in-javascript-quick-explanation/
CHICAGO
" » Factorial Function in JavaScript – Quick Explanation.." Jessica-Agorye | Sciencx - Accessed . https://www.scien.cx/2024/07/23/factorial-function-in-javascript-quick-explanation/
IEEE
" » Factorial Function in JavaScript – Quick Explanation.." Jessica-Agorye | Sciencx [Online]. Available: https://www.scien.cx/2024/07/23/factorial-function-in-javascript-quick-explanation/. [Accessed: ]
rf:citation
» Factorial Function in JavaScript – Quick Explanation. | Jessica-Agorye | Sciencx | https://www.scien.cx/2024/07/23/factorial-function-in-javascript-quick-explanation/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.