who's.asking
who's.asking

Reputation: 83

Finding the factorial using a loop in javascript

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);

Upvotes: 1

Views: 37203

Answers (6)

Ogundeji Yusuff
Ogundeji Yusuff

Reputation: 1

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

factorialize(5);

Upvotes: 0

Carla
Carla

Reputation: 56

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);

Upvotes: 1

Islam Sayed
Islam Sayed

Reputation: 56

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);

Upvotes: 2

Nina Scholz
Nina Scholz

Reputation: 386670

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);

Upvotes: 1

bboy
bboy

Reputation: 38

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

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

alert(inputNumber + '! = ' + total);

Upvotes: 1

Zhenya Telegin
Zhenya Telegin

Reputation: 587

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);

Upvotes: 2

Related Questions