# Thread: Looping with different values

1. ## Looping with different values

I want to write a loop to check for prime numbers. So I'm going to check only numbers ending with 1,3,7,9.

So I need a loop that will increment with 2,4,2,2 and again 2,4,2,2...

What king of loop is best, a 'for loop' or a 'while' with switches in it or something else?

Basically I need to increment three times with 2 and then with 4, three times with 2 and then with 4... 2. Don't bother: starting from 3, increment by 2. Then, in your trial division, check for 5 as a divisor. You will be checking for 3 anyway, so that isn't a problem. What this gains you is not having to check for 2 as a divisor.

Note that trial division only requires checking with primes as divisors. 3. Something like this could work.
Code:
```int inc[]={2,4,2,2};
for(int x=??,i=0; ?? ; x+=inc[i++%4]){}``` 4. OK, thanks Laserlight. So you don't think that there is any gain in speed in my method vs checking every number for 5 as a divisor? Not even when you're looking for a long series of big prime numbers? 5. Originally Posted by manasij7479 Something like this could work.
Code:
```int inc={2,4,2,2};
for(int x=??,i=0; ?? ; x+=inc[i++%4]){}```
Yes, that's a good solution. Thanks Manasij! 6. If you want a significant gain in speed, then consider changing algorithm, e.g., implement the Sieve of Eratosthenes, or use that sieve algorithm to obtain all the possible prime divisors for the range you're looking at, and then use perfect trial division.

As to whether you will actually get a gain in speed from skipping multiples of 5 without testing them as opposed to testing them and then quickly moving on (just two tests: 3 then 5), that should be determined by testing with timing. 7. If you actually want performance, then the fastest way to test if a small number (with say 4 digits or less) is to have a hard coded list of prime numbers. 8. Sorry?

If you have a hard coded list of prime numbers what are you going to test for? 9. Originally Posted by Ducky
If you have a hard coded list of prime numbers what are you going to test for?
Whether a larger number is prime, using the numbers in that list as trial divisors. 10. Originally Posted by Ducky Sorry?

If you have a hard coded list of prime numbers what are you going to test for?
You test if the number the user enters is in the list. Popular pages Recent additions 