Technical Interview Questions

The largest pool of technical questions with answers, explantions, code and detailed analysis

Prime Numbers: Finding the first N Primes – Part 2 Skipping Multiples

Posted by tekpool on October 4, 2006

Q: Finding the first N primes.
In the last post, we looked into some trivial approaches. How can we make this faster?

Most of the work in problems like these (Finding matches) are spent in the core problem itself (Finding the match), in this case, Primality test. So lets look into how we can avoid this? One simple approach is to not do primality checks for even numbers

void GetPrimesSkipEven(int n) 
{ 
    // Start from 5 
    int j=3; 
    // Set count to 1 
    // 2 is already a prime 
    int count = 1; 
    while(count

Improvements In GetPrimesSkipEven:

  1. Every second number (even) is not tested for primality
  2. In primality test, division test are reduced by half, since we do not divide by even numbers any more (i+=2)
  3. Modulo divisions are replaced by bit operators (i%2) == (i&1)

How can we get better,

void GetPrimesSkipSecondThird(int n) 
{ 
    // Start from 5 
    int j=5; 
    // Set count to 2, 
    // already 2 primes have been found (2 and 3) 
    int count = 2; 
    while(count

Improvements In GetPrimesSkipSecondThird:

  1. Every second and third number is not tested for primality
  2. In primality test, division test are reduced around 60%, since we do not divide by numbers divisible be 2 or 3
    Skip incrementing i by 2 or 4 (alternatively)
  3. Modulo divisions are replaced by bit operators (i%2) == (i&1)

In a later post, we will look into the speeds of all these, but to those curious ones out there, I am list faster algorithms as we go by

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

 
Follow

Get every new post delivered to your Inbox.