I have such a problem, I’ve been struggling with it since yesterday, but I just can’t find an error. The condition is: Find and fix the error in the program for finding the factorial.
And here is the code:
var counter = prompt("Enter the number");
var factorial = 1;
document.write("Factorial of a number: " + counter + "! = ");
do {
if (counter == 0) {
factorial = 1;
break;
}
factorial = factorial / counter;
counter = counter + 1;
}
while (counter > 0);
document.write(factorial);
The tooltips say that something is wrong with the factorial variable itself, but I can’t see anything. I have tried different options, including writing factorial = factorial * counter; instead of factorial = factorial / counter;, but it’s for sure something else. We are talking about a site with automatic checking, so I think that there is something small that needs to be corrected, and there is no need to rewrite everything completely. So, the idea is to make some corrections to the existing code. Help me, please!
I have tried different options, including writing factorial = factorial * counter; instead of factorial = factorial / counter. As well, most probably the while loop is endless, because of this condition while (counter > 0).
2
Answers
replaced with counter = counter – 1;. We need to decrement the
counter by 1 in each iteration of the loop to calculate the
factorial correctly.
factorial / counter;), we need to multiply them (factorial =
factorial * counter;) to calculate the factorial.
this is your fixed code
From what I could understand from your question. Hard to read since its poorly formatted. Here is a suggestion on how to fix it
I just replaced the document.write with console.log
The logic that i modified is that to compute the factorial you just multiply
n*(n-1)(n-2)….*(1) so the counter is updated