Provided your X
is small enough, you can use the Sieve of Eratosthenes to do it more efficiently. This is ideal for the "primes up to X" case since it maintains a memory of previously discarded primes. It does so by keeping a set of flags for each candidate number, all initially set to true (except for 1, of course).
Then you take the first true value (2), output that as a prime, and then set the flags for all multiples of that to false.
Then carry on with:
- 3;
- 5 (since 4 was a multiple of 2);
- 7 (since 6 was a multiple of 2 and 3);
- 11 (since 8 and 10 were multiples of 2 and 9 was a multiple of 3);
- 13 (since 12 was a multiple of 2);
- 17 (since 14 and 16 were multiples of 2 and 15 was a multiple of 3 and 5);
- and so on.
Pseudo-code would be similar to:
def showPrimesUpTo (num):
// create array of all true values
array isPrime[2..num] = true
// start with 2 and go until finished
currNum = 2
while currNum <= num:
// if prime, output it
if isPrime[currNum]:
output currNum
// also flag all multiples as nonprime
clearNum = currNum * 2
while clearNum <= num:
isprime[clearNum] = false
clearNum = clearNum + currNum
// advance to next candidate
currNum = currNum + 1
Otherwise, you can do trial division as per your suggestion. The basic idea is to check each number from 2 up to the square root of your target number to see if it's a multiple. In pseudo-code, that would be something like:
def isPrime (num):
// val is the value to check for factor
val = 2
// only need to check so far
while val * val <= num:
// check if an exact multiple
if int (num / val) * val == num:
return false
// no, carry on
val = val + 1
// if no factors found, it is a prime
return true
The reason you only need to check up to the square root is because, if you find a factor above there, you would have already found the corresponding factor below the square root.
For example, 3 x 17
is 51
. If you're checking the numbers from 2 through 50 to see if 51
is prime, you'll find 3
first, meaning you never need to check 17
.