I have the following code but it is not giving perfect result for factorial can u find it out plz
I've seen a recursive approach used in many places (Eloquent JavaScript etc). Here, the function is called recursively until it reaches 0, which should not be the case. We should only call the function till it is >= 2 because the last number we need to multiply by is 1.
It's a very minor change, and probably does not matter. Curious to know what other people think of it. Assuming it is a valid positive integer.
/**
* Popular approach - the recursive function is called till x is 0
*
* @param x
*/
function popularFactorial(x) {
console.log(x)
if(x === 0) {
return 1
} else {
return x * popularFactorial(x - 1)
}
}
var result = popularFactorial(8)
console.log(result)
/**
* Using this approach, the recursive function is called one less time
* i.e till x is 1
*
* @param x
*/
function factorial(x) {
console.log(x)
if(x === 0) {
return 1
} else if(x >= 2) {
return x * factorial(x - 1)
}
return x
}
var result = factorial(8)
console.log(result)
//This is fastest way to implement factorial
const fact = n => !n ? 1 : n * fact(--n);
console.log(fact(10))
The important part of the function is this line:
x = x * fact(x-1);
but the fact function does not return a value, so this is the same as x * undefined. Try adding return x; to the bottom of your function.
var factorialNumber , factorial=1;
factorialNumber=prompt("Factorial Number" , "write Factorial Number");
for(var i = 1; i<= factorialNumber;i++){
factorial *= i;
}
alert(factorial);
The code above first defines two variables, factorialNumber and factorial. factorial is initialized with 1. factorialNumber will get the result of the prompt (a number is expected) and then, using a cycle, in each step, factorial is multiplied with the index of the step, which is represented by i. When successfully calculated, we show the result using alert.
function factorial(num){
if(num<1||typeof num!=='number'){
return undefined
}
if(num===1){
return num
}
return num*factorial(num-1)
}
console.log(factorial(3))
https://jsfiddle.net/mohittadhiyal/6w64x0sL/10/
function factorial(n) {
return [...Array(n + 1).keys()].slice(1).reduce((total, currentValue) => total * currentValue, 1);
}