I wrote 3 simple implementations of factorials in JavaScript. When I compared them, I found out that they are not giving the same values. I've checked the logic in all, but I can't figure out why they are not equal to each other for some input values greater than 24.
Please take a look at my code and help me figure out why they differ and which implementation is correct? Thanks
function recursiveFactorial(n) {
return n > 1 ? n * recursiveFactorial(n - 1) : 1;
}
function iterativeFactorial1(n) {
let result = 1;
while (n > 1) {
result *= n;
--n;
}
return result;
}
function iterativeFactorial2(n) {
let result = 1;
for (let i = 2; i <= n; ++i) {
result *= i;
}
return result;
}
console.log('Iterative 1 vs Iterative 2');
for (let i = 1; i <= 50; ++i) {
console.log(i, iterativeFactorial1(i) === iterativeFactorial2(i));
}
console.log('\nIterative 1 vs Recursive');
for (let i = 1; i <= 50; ++i) {
console.log(i, iterativeFactorial1(i) === recursiveFactorial(i));
}
console.log('\nIterative 2 vs Recursive');
for (let i = 1; i <= 50; ++i) {
console.log(i, iterativeFactorial2(i) === recursiveFactorial(i));
}
NOTE: After testing I found out that Iterative 2 and Recursive are giving same results but Iterative 1 and Recursive are giving different results which tells me that there's an issue with Iterative 1.
PS: I have updated the question since I forgot to put the recursive function as mentioned in the comments.