1

I need to use a loop to find the factorial of a given number. Obviously what I have written below will not work because when i = inputNumber the equation will equal 0.

How can I stop i reaching inputNumber?

var inputNumber = prompt('Please enter an integer');
var total = 1;

for (i = 0; i <= inputNumber; i++){
    total = total * (inputNumber - i);
}

console.log(inputNumber + '! = ' + total);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
who's.asking
  • 83
  • 2
  • 2
  • 5
  • Possible duplicate of [factorial of a number](http://stackoverflow.com/questions/4438131/factorial-of-a-number) – Harald Gliebe Apr 30 '17 at 16:13
  • Possible duplicate of [Fast factorial function in JavaScript](https://stackoverflow.com/questions/3959211/fast-factorial-function-in-javascript) – Krisztián Balla Sep 15 '18 at 13:02

6 Answers6

2

here is an error i <= inputNumber

should be i < inputNumber

var inputNumber = prompt('Please enter an integer');
var total = 1;

for (i = 0; i < inputNumber; i++){
    total = total * (inputNumber - i);
}

console.log(inputNumber + '! = ' + total);
Zhenya Telegin
  • 589
  • 2
  • 9
2

you can keep this: i <= inputNumber

and just do this change: total = total * i;

then the code snippet would look like this:

var inputNumber = prompt('Please enter an integer');
var total = 1;

for (i = 1; i <= inputNumber; ++i){
total = total * i;
}

console.log(inputNumber + '! = ' + total);
1
var inputNumber = prompt('Please enter an integer');
var total = 1;

for (i = 0; i < inputNumber; i++){
    total = total * (inputNumber - i);
}

alert(inputNumber + '! = ' + total);
bboy
  • 36
  • 7
1

You could use the input value and a while statement with a prefix decrement operator --.

var inputNumber = +prompt('Please enter an integer'),
    value = inputNumber,
    total = inputNumber;

while (--value) {                           // use value for decrement and checking
    total *= value;                         // multiply with value and assign to value
}

console.log(inputNumber + '! = ' + total);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
1

Using total *= i; will set up all of your factorial math without the need of extra code. Also, for proper factorial, you'd want to count down from your input number instead of increasing. This would work nicely:

var inputNum = prompt("please enter and integer");
var total = 1;
for(i = inputNum; i > 1; i--){
 total *= i;
}
console.log(total);
Carla
  • 56
  • 4
0

function factorialize(num) {
  
  var result = num;
  if(num ===0 || num===1){
    
    return 1;
  }
  
  while(num > 1){
    num--;
    result =num*result;
  }
  return result;
}

factorialize(5);