1

I want to see all the prime numbers from the beginning (2) to the end (according to my setting).

var nums = [2];
for (var i = 3; i < 103; i++) {
    for (var x = 0; x < nums.length; x++) {
        if (i % nums[x] != 0) nums.push(i);
    }
}
$("body").append(nums);

I don't understand what is the prolem.

Moazzam Khan
  • 3,130
  • 2
  • 20
  • 35
Eyal
  • 1,649
  • 3
  • 25
  • 49
  • 1
    Maybe you could describe what you are trying to do, and why you think this solves the problem. In other words work through your formula by hand and see why it infinite loops. – dcaswell Sep 05 '13 at 15:22
  • 1
    So, what is the problem? What do you expect, and what happens? What have you tried to solve it? How long have you tried? – starblue Sep 05 '13 at 15:45

1 Answers1

3

You add 'i' to 'nums' every time it cannot be divided by any previous number. So '4' is added because it cannot be divided by '3'. '5' is added 3 times because it cannot by divided by '2', '3' nor '4', '6' is added 4 times because it cannot be divided by '4' (1 occurrence) nor '5' (3 occurrences). So actually what your algorithm does is adding all the numbers multiple times approximately doubling size of 'nums' array on every number.

So there are two answers:

  1. it doesn't work as you would expect because you add to nums 'when any' instead of 'when all'

  2. it crashes because it would require array with 2^100 elements (that's a lot of memory).

Milosz Krajewski
  • 1,160
  • 1
  • 12
  • 19