Algorithm for calculating prime number (i) __ algorithm

Source: Internet
Author: User

There are often beginners to solve the problem of all prime numbers (prime) in N, for this, there are many answers on the internet, but many are either not professional, or only the program does not parse the algorithm, so Sanzang building to do a summary of this problem, discuss the common algorithm of solving prime numbers, and give the corresponding C language program and its analysis. For the convenience of beginners to understand, this article will be from easy to difficult to explain the different algorithms, master can directly look at the back of the efficient algorithm
Definition of prime number
A number, if only 1 and its own two factors, such a number is called Prime, also known as Prime.

Trial-and-remove judgment method
Algorithm Description: From the above definition, the prime number can not be divided by 1 and its own numbers, so, to determine whether a number x is a prime if it can be 2~sqrt (x) between the number of divisible, and all the primes in n is a cyclic repetition of the above process.
C Language implementation:

Copy Content to Clipboard

Code:

#include <time.h>
#include <malloc.h>
#define N 100000
Simple test and judgment method Ver1
int s i m P l eDivisionV1 (int n)
{
int i,j;
Number of prime numbers statistics
int count = 0;
Allocate space to store results
int* primes = (int*) malloc (sizeof (int) *n);

2 is a prime number.
primes[count++] = 2;
Calculating the number of 3~n between loops
for (i=3; i<=n; i++)
{
Why sqrt (i), think about it
for (j=2; j<=sqrt (i); j + +)
{
I'm divisible by J, obviously not a prime number.
if (i%j = = 0) break;
}
I cannot be divisible by the number of 2~sqrt (i) and the primes are also
if (J > sqrt (i))
{
primes[count++] = i;
}
}

Because of the output time-consuming, and the algorithm is not related to the core, so slightly

Free up memory, don't forget the legendary memory leak
Free (primes);

return count;
}

void Main ()
{
int count;
clock_t start, end;
Time function is not accurate, do it with clock
start = Clock ();
Count = S i m P l eDivisionV1 (N);

end = Clock ();
printf ("[%d]" number of characters:%d, calculation time:%d MS \ n ", N, Count, End-start);
Getch ();
}

Calculation Result:
[100000] Number of characters: 9592, calculation time: 468 milliseconds
[1000000] Number of characters: 78498, calculation time: 10859 milliseconds
[5000000] Number of characters: 348513, calculation time: 103560 milliseconds
Oh oh, 100,000 is OK, million is 10 seconds more, and time is growing fast, this does not, you have to optimize.
Optimization Analysis:
A closer look at the s i m P L eDivisionV1 we can find the following questions:

1. Repeated calls to sqrt (i) in the loop condition is obviously a waste of time.

2. Judging primes, really need to take all the integers between 2~sqrt (i) to remove it. We know that composite can be decomposed into several prime numbers, so as long as the prime number between 2~SQRT (i) cannot be divisible by I

According to the above two points, we can upgrade the s i m P l eDivisionV1 to s i m P l eDivisionV2, as follows

Copy Content to Clipboard

Code:

Simple test and judgment method Ver2
int s i m P l eDivisionV2 (int n)
{
int I, j, K, stop;
Number of prime numbers statistics
int count = 0;
Allocate space to store results
int* primes = (int*) malloc (sizeof (int) *n);

2 is a prime number.
primes[count++] = 2;
Stop = count;
Calculating the number of 3~n between loops
for (i=3; i<=n; i++)
{
K = sqrt (i);
Repeated calls to sqrt in cyclic conditions are inefficient, so the introduction of K
while (Primes[stop] <= k && Stop < count)
stop++;
Stop what to do, think about it.
for (j=0; j<stop; j + +)
{
if (i%primes[j] = = 0) break;
}
I cannot be divisible by the prime number between 2~sqrt (i), nor can it be divisible by other numbers, and primes
if (j = = stop)
{
primes[count++] = i;
}
}

Because of the output time-consuming, and the algorithm is not related to the core, so slightly

Free up memory, don't forget the legendary memory leak
Free (primes);

return count;
}

Then replace the function called in main with the S i m P l eDivisionV2, and look at the execution result:
[100000] Number of characters: 9592, calculation time: 46 milliseconds
[1000000] Number of characters: 78498, calculation time: 546 milliseconds
[5000000] Number of characters: 348513, calculation time: 3515 milliseconds
[10000000] Number of characters: 664579, calculation time: 8000 milliseconds
Very happy to see, after optimization, the speed increased dozens of times times, especially the time growth curve of the slope has become smaller, the greater the N value, the V2 function than V1 efficiency is higher
For the test of this prime number algorithm, Sanzang that the s i m P L eDivisionV2 Basic has been close to the limit, is unlikely to have a level of breakthrough, interested friends can further optimize their own. In addition to the above examples, beginners can try to do various modifications and details optimization, you can also multiply the division, more practice is a good way to learn programming.
Although, in the above example, V2 has been much faster than V1, but with the increase of N, time is still a lot, then we have a better way.


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.