hi, I think I have a misunderstanding for the for loop or there is a technical issue. here are 2 pieces of code where fol loop is considered an infinite loop and I don’t know why
1 -
function sumPrimes(num) {
var nums = [2];
var ss =[];
// Not to add all numbers , but add only Primes in the Nums Array by checking if the added number / every number in the Nums array addd before it isn't out of 1 and the number itself
for (var i = 3 ; i <= num ; i++){
for (var j = 0 ; j < nums.length; j++){
var di = i / nums[j];
if (di !== Math.floor(di)){
nums.push(i) ;
}
}
//nums.push(i);
}
var res = nums.reduce(function (a,b){return a+b;},0);
return nums;
}
sumPrimes(20);
2-
function sumFibs(num) {
var fiboNums = [1,1];
var firstFibo = 1 ;
var secondFibo = 1 ;
var sum = firstFibo + secondFibo;
fiboNums.push(sum);
for ( var i = 0 ; i < num ; i++){
/* 1 + 1 == 2 ;
1 + 2 == 3
2 + 3 == 5
3 + 5 == 8*/
sum = sum + secondFibo;
fiboNums.push(sum);
}
return fiboNums;
}
sumFibs(4);
So on your first function, what your doing is mutating the condition nums.length
for the for()
loop with nums.push()
. Every time that you push to nums
it increases the length and j
won’t trigger the condition.
1 Like
In sumPrimes
, the inner for-loop pushes values to the nums
array. This keeps increasing the value of nums.length
, and the j
variable can’t catch up, so you get an infinite loop.
1 Like
Well, I got what you mean thank you. What about the second one ?! why it is considered as n infinite loop?
That’s right. What about the second piece of code ?!
The second one runs fine (although I presume it gives the wrong answer).
1 Like
What if I till U that it stops my browser from working !! the second for loop stops the browser until i open this url and change it
Cn u till me what’s wrong ?!
Ok that’s it
function sumFibs(num) {
var fiboNums = [1,1];
var firstFibo = 1 ;
var secondFibo = 1 ;
var sum = firstFibo + secondFibo;
fiboNums.push(sum);
for ( var i = 0 ; i < num ; i++){
/* 1 + 1 == 2 ;
1 + 2 == 3
2 + 3 == 5
3 + 5 == 8*/
sum = sum + secondFibo;
fiboNums.push(sum);
}
return fiboNums;
}
sumFibs(4);
Is this ok ?
Great Explanation! I got my wrong in the logic but what i need to make sure that it is right that if the only reason of it considered infinite was it takes too long in 400000 ?!!
Actually, I had solved it with for loop Thank You at all for your help and your time