skip to Main Content

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


    1. In the original code, the line counter = counter + 1; should be
      replaced with counter = counter – 1;. We need to decrement the
      counter by 1 in each iteration of the loop to calculate the
      factorial correctly.
    2. Instead of dividing the factorial by the counter (factorial =
      factorial / counter;), we need to multiply them (factorial =
      factorial * counter;) to calculate the factorial.

    this is your fixed 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);
    
    Login or Signup to reply.
  1. From what I could understand from your question. Hard to read since its poorly formatted. Here is a suggestion on how to fix it

    var counter = 5
    var factorial = 1;
    if (counter === 0) {
    console.log(factorial);
    } else {
      while (counter > 0) {
        factorial *= counter;
        counter--;
      }
      console.log(factorial);
    }
    
    

    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

    1. so counter shoudld be decremented
    2. factorial should be multiplied not divided
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search