More Efficient Prime Searching Algorithm?

I started working on some Project Euler problems today, and I'm having problems with the one that seeks the sum of all prime number less than 2000000.
It's running very slowly, so I was wondering if there existed a faster prime searching algorithm than the one I have now. (It's currently some sort of inefficient prime sieve.)
Here is the code:

Re: More Efficient Prime Searching Algorithm?

For a sieve you don't need to divide anything; for all multiples of 2 (except 2 itself) clear the corresponding flag. Check the first next number with its flag set, say x; clear all multiples of x (except x itself) and repeat the process until done. While checking for those numbers with their flag set in the outer iteration, you might as well add them to a total value; that way, when you're done with your sieve you're done with your entire algorithm.

Re: More Efficient Prime Searching Algorithm?

Wouldn't it be more efficient to only check for values of x up to b.length/2? It seems a bit ridiculous to be incrementing x when x+x will always be greater than or equal to b.length, so the inner for loop will never execute once x > b.length/2.

So instead of what josAH posted, unless I'm missing something, this would end faster, if not by much for tests up to less than a million or so:

Re: More Efficient Prime Searching Algorithm?

Originally Posted by Singing Boyo

Wouldn't it be more efficient to only check for values of x up to b.length/2? It seems a bit ridiculous to be incrementing x when x+x will always be greater than or equal to b.length, so the inner for loop will never execute once x > b.length/2.

So instead of what josAH posted, unless I'm missing something, this would end faster, if not by much for tests up to less than a million or so:

It is, indeed, a bit more efficient, i.e. for the last half (here 500,000) nothing needs to be done and the inner loop doesn't execute; but for the first half many more iterations have been made; 1e6/2+1e6/3+1e6/4 ...