Reputation: 321
I want to reduce the computing load in a test for primes. Currently my loop just tests odds, like so:
for (k=3; k<=end; k+=2) {
I read that every prime other than 2 and 3 is a function of k= 6 +/- 1 though. By only testing 2/3rds of the odds I can reduce computing load by 33%. The only way I can think to do this is to oscillate the counter to increment by 2, then 4, then 2, then 4 each iteration, for example testing 5, 7, 11, 13, etc.
Is there a way to tell the loop to do this? Is there another way to do this I'm not considering?
P.S. I'm aware of the sieve method of testing
Upvotes: 1
Views: 196
Reputation: 10148
Just for the fun of it...
for (var k=3,l=0; k<=end; k+=2*(l%2+1),l++){ }
Upvotes: 2
Reputation: 12375
Something like this?
oscillate = false;
k = 3;
while(k <= end)
{
testForPrimes(k);
k += oscillate ? 2 : 4;
oscillate != oscillate;
}
Upvotes: 2
Reputation: 17487
Use a while
loop, instead:
k = 3;
odd = false;
while( k<=end ) {
k += odd ? 2 : 4;
odd = !odd;
}
Upvotes: 2