Why am I getting infinite loop in JavaScript
I am trying to return the factorial of a provided integer. In this case, for example:
factorialize(num) {
for (var i = 1;i <= num; i++){
num*=i;
}
return num;
}
factorialize(5);
I get an infinite loop. Although I understand that this shouldn't give me the correct answer, because my understanding of it would be something like this:
n! = 5 * 1 * 2 * 3 * 4 * 5 = 600
when should it really go:
n! = 1 * 2 * 3 * 4 * 5 = 120
But still, I don't understand why I am getting an infinite loop here?
source to share
Let's assume the value of the variable num
is 2
.
-
First cycle:
for (var i = 1; i <= 2; i++) { //true num *= i; //2 = 2 * 1 => 2 }
-
Second loop:
for (var i = 2; i <= 2; i++) { //true num *= i; //2 = 2 * 2 => 4 }
-
Third cycle:
for (var i = 3; i <= 4; i++) { //true num *= i; //4 = 4 * 3 => 12 }
-
Fourth cycle:
for (var i = 4; i <= 12; i++) { //true num *= i; //12 = 12 * 4 => 48 }
The value num
increases exponentially and the value i
increases linearly .
i <= num
the condition will always be met , so you end up with an infinite loop.
Snippet containing the diagram:
var num = {
x: [1, 2, 3, 4, 5],
y: [2, 4, 12, 48, 240],
type: 'scatter',
name: 'num'
};
var i = {
x: [1, 2, 3, 4, 5],
y: [1, 2, 3, 4, 5],
type: 'scatter',
name: 'i'
};
var data = [num, i];
Plotly.newPlot('myDiv', data);
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
<div id="myDiv" style="width: 480px; height: 400px;">
source to share
Your loop is chasing a moving target.
It will end when i
reached num
, but you continue to do num
anymore; in fact i
never reach num
.
As you pointed out, your algorithm is wrong anyway.
function factorialize(num) {
var result = 1;
for (var i = 2; i <= num; i++) {
result *= i;
}
return result;
}
console.log(factorialize(0)); // 1
console.log(factorialize(1)); // 1
console.log(factorialize(2)); // 2
console.log(factorialize(3)); // 6
console.log(factorialize(4)); // 24
console.log(factorialize(5)); // 120
source to share
Taking your example:
Before starting 1: num = 5; After starting 1: num = 5; After starting 2: num = 10; After starting 3: num = 30;
According to your condition, the loop will only stop when num is greater than i, which it never will, since you change its value at each iteration by a huge difference.
source to share
The end condition for is i<=num
always true
, therefore, an infinite loop, because the argument num
keeps increasing with each iteration. The best approach is
function factorialize(num) {
var res = 1;
if(num ===0 || num === 1){
return 1;
}
for (var i = 2;i <= num; i++){
res*=i;
}
return res;
}
factorialize(5);
source to share