Simple JavaScript program to calculate the factorial of a number using iteration:
Factorial Formula: n!=n*(n-1)*(n-2)*....
Factorial zero should be 0!=1
Check the below step here:
Step1: Check edge case for factorial number 0 is 1
Step2: Initialize the factorial to 1;
Step3: Multiply the number from 1 to num.
Step4: Return factorial
--------------------------------------
function factorial(num){
if(num===0){
return 1;
}
let factorial=1;
for(let i=1;i<=num;i++)
{
factorial = factorial*i;
}
return factorial;
}
console.log(factorial(5));
----------------------------------------
The recursion involves a function that calls itself until it reaches a base condition. It is used for only small number not large number case.
#ShravanGhanchi
No comments:
Post a Comment