Ordinary screen prime number and linear screen Prime Number

Source: Internet
Author: User

General screening method:

Normal screening method: const int maxn = 70000; void prime () // screening method for prime number table P [I] = 1 is a prime number, similar to hash ing! {Int I, j; for (I = 0; I <maxn; I ++) prime [I] = 1; prime [0] = prime [1] = 0; for (I = 2; I <maxn; I ++) {If (! Prime [I]) continue; For (j = I * 2; j <maxn; j + = I) prime [J] = 0 ;}}

Linear screening method:

Understanding if (I % prime [J] = 0) is the key.

Principle:
1. Any sum can represent the product of a prime number and a number.
2. Assume that A is a combination of a and a = x * Y. Here, X is also a combination, so there are:
A = x * Y; (assume that Y is a prime number and X is a combination of numbers)
X = a * B; (assume that A is a prime number, and a <X --> A <Y)
-> A = a * B * Y = A * z (Z = B * Y)
That is, a sum (X) and a prime number (Y) Can be expressed as a larger sum (z) and a smaller prime number (A) Product !!!!
This is also the key to understanding if (I % primes [J] = 0) break; in the code.
For example, if I = 8; then because I % 2 = 0; therefore, for I = 8, you only need to check primes [1] = 2, because for prime numbers greater than primes [1], such as 3, there are:
8*3 = 2*4*3 = 12*2
That is to say, 24 (8*3 = 24) does not need to be checked at 8 hours.

Linear screening method: # include <iostream> using namespace STD; const int n = 200000; long prime [N] = {0}, num_prime = 0; // num_pirme records the number of prime numbers int main () {int m; CIN> m; int A [n] = {1, 1}, I, j; for (I = 2; I <m; I ++) {If (! A [I]) prime [num_prime ++] = I; for (j = 0; j <num_prime & I * prime [J] <m; j ++) {A [I * prime [J] = 1; // when the sum mark is 1, prime [J] is the minimum prime factor if (! (I % prime [J]) // obtain the break by multiplying the product of a prime number with a larger sum with a smaller prime number ;}} for (I = 0; I <num_prime; I ++) // output {if (I % 10 = 0) printf ("\ n "); printf ("% 3d", prime [I]);} printf ("\ n"); Return 0 ;}

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.