Today, learning the method of prime numbers, it feels great, share it. First of all, compare the two methods: the common method of calculating prime numbers and the method of selecting prime numbers based on the screening method.
- normal method to calculate prime number
The common method of finding prime numbers is to determine whether a number n is prime (only 1 and itself can divide itself) according to the definition of prime numbers. Therefore, the method is generally to test whether 1 to n all numbers are divisible by n, to determine whether N is prime. The code example is as follows:
#include <stdio.h>
#include <math.h>
#define N 10000001
int prime[n];
int main ()
{
int i, j, num = 0;
For (i=2 i<n; i++)
{for
(j=2; j<=sqrt (i); j + +)
if (j%i==0) break;
if (j>sqrt (i)) prime[num++] = i;
}
For (i=2 i<100; i++)//output only prime number within 2-100
if (prime[i)) printf ("%d", I);
return 0;
}
This code in my 1G memory, single core CPU on the cloud host, will run for quite a long time.
- the method of selecting prime numbers based on the selection method
Based on the method of selecting prime numbers, we use the array to access the candidate set, and then filter the number of prime numbers according to the multiple of the primes. However, it is not known why the end position of the For loop is sqrt (N).
#include <stdio.h>
#include <math.h>
#define N 10000001
int prime[n];
int main ()
{
int i, J;
For (i=2 i<n; i++) {
if (i%2) prime[i]=1;
else prime[i]=0;
}
For (i=3 i<=sqrt (N), i++)
{ if (prime[i]==1) for
(j=i+i; j<n; j+=i) prime[j]=0;
}
For (i=2 i<100; i++)//output only prime number within 2-100
if (prime[i]==1) printf ("%d", I);
printf ("\ n");
return 0;
}
Based on the method of selecting prime numbers, the running time is short. Part of the reason is that the time complexity is small, part of the reason is to omit the CPU to open the square root of the time occupied. In summary, the method of selecting prime numbers based on the screening method is a fast and practical way to obtain prime numbers.
In addition, we can further optimize the method based on the selection of prime numbers. Simplifies the footprint of an array: Since all even numbers are not prime (except 2), the array can hold only the odd number, eliminating half of the space occupied.