Click here to Skip to main content
15,886,199 members
Articles / Programming Languages / C
Alternative
Tip/Trick

Quicker Prime Number Test

Rate me:
Please Sign up or sign in to vote.
4.88/5 (5 votes)
6 Nov 2011CPOL 9.3K   33   4
When you search manually, you can search for every odd number that is a step of 2. If you're a bit more clever (as you are), you can use steps of 6 (2 * 3). Testing (testno+1)%6==0 is very similar to (testno % 6) = 5.You can speed up big time by having a loop that increments per steps of...
When you search manually, you can search for every odd number that is a step of 2. If you're a bit more clever (as you are), you can use steps of 6 (2 * 3).

Testing (testno+1)%6==0 is very similar to (testno % 6) = 5.

You can speed up big time by having a loop that increments per steps of 6.

C#
// you meant to use && here not ||
if ((testno % 2 != 0) && (testno % 3 != 0) && (testno % 5 != 0))
{
  for(i=6;i*i <= testno; i+=6)
  {
    if ((testno % (i + 1) == 0)
      || (testno % (i + 5) == 0))
    {
      printf("\nNot Prime");
      getch();
      exit();
    }
}
else
{
   printf("\nNot Prime");
   getch();
   exit();
}


If you're a computer, you can take steps of (2*3*5)=30 or even perhaps (2*3*5*7)=210.

For 30, initially you have to check for multiples of 2 3 5 7 11 13 17 19 23 29.
Then, if this pass, you can do 30k+1 30k+7 30k+11 30k+13 30k+17 30k+19 30k+23 30k+29

This is saving you a lot of tests.
With your method, you'd do:
6k-1 6k+1
05 07
11 13
17 19
23 25
29 31
35 37
41 43
47 49
53 55
59 61

With steps of 30, you avoid 25 35 55.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
France France
I am a French programmer.
These days I spend most of my time with the .NET framework, JavaScript and html.

Comments and Discussions

 
GeneralMy vote of 4 Pin
Shaown.Sarker17-May-12 2:05
Shaown.Sarker17-May-12 2:05 
GeneralRe: My vote of 4 Pin
Pascal Ganaye17-May-12 6:25
Pascal Ganaye17-May-12 6:25 
GeneralClever. Pin
Nagy Vilmos24-Jan-12 6:07
professionalNagy Vilmos24-Jan-12 6:07 
GeneralReason for my vote of 5 I too would have suggested to increm... Pin
Member 311671023-Jan-12 20:52
Member 311671023-Jan-12 20:52 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.