Location>code7788 >text

Linear screen

Popularity:511 ℃/2025-02-02 12:11:51

Linear screen

Introduce


-The example (F question)

Give two positive integers\(n\),\(q\)Then ask\(q\)Second, ask each time\(m\)Small quality guarantee quality is less than equal to equal\(n\)

-Thinking

Use an array to store quality numbers, and then output\(m\)It's okay, but we need to consider the time and space restrictions. Generally, violence is also possible, but someTang DynastyThe title wants us to use a linear screen. Next explanation is made for you to appreciate.

Linear screen


-principle

Traversing a certain number\(k\)When, if, if\(k\)It is a qualitative number, then its multiple (\(2*k\),\(3*k\)...\(n*k\)) It must not be quality, if\(k\)It is not a mass number, it must be expelled by a certain quality number in front.

-Enar code

Vector <Bool> Prime (N+1, TRUE); // Use an array to save 0-n, the default number is quality (true)
 prime [0] = prime [1] = false; // 0, 1 is not a quality number (FALES)
 for (int i = 2; i*i <= n; ++ i) {// Traversing (Q1: Why is i*i?)
 if (private [i]) {
 For (int j = i*i; j <= n; j+= i) {// Remove the multiple after the square of this quality number (Q2: Why start from i*i?)
 prime [j] = false; // exclude
 }
 }
 }

-Tips

Q1:

The nature of the number:

If n is the number, then it has at least one mass factor P meets P ≤ √N.

For example, n = 100, √100 = 10. If n is the number, it has at least one mass factor P ≤ 10.

The termination of the screening method:

When i> √N, ii> n, the multiple of I at this time I2, i3, ..., i(i-1) It has been removed by smaller quality numbers.

Therefore, it is meaningless to continue sieve.

Q2:

The nature of the number:

If n is the number, then it has at least one mass factor P meets P ≤ √N.

For example, n = 100, √100 = 10. If n is the number, it has at least one mass factor P ≤ 10.

The starting point of the sieve method:

For Quality I, I multiples I, I2, i3, ..., i*(i-1) have been removed by smaller quality numbers.

Therefore, starting from J = I * I directly.

Coding


#include <bits/stdc ++. h>
 using namespace std;

 int Main () {
 int n, q, m;
 cin >> n >> q;
 vector <bool> Prime (n+1, true);
 prime [0] = prime [1] = false;
 for (int i = 2; i*i <= n; ++ i) {
 if (private [i]) {
 For (int j = i*i; j <= n; j+= i) {{
 prime [j] = false;
 }
 }
 }
 	
 vector <int> Primes; // Stock in quality
     for (int i = 2; i <= n; ++ i) {
         if (prime [i]) primes.push_back (i);
     }
 	
 While (q-) {// Ask multiple times
 cin >> m;
 if (m> = 1 && m <= ()) {
 core << Primes [m-1] << Endl;
 } Else {
 core <<-1 << Endl;
 }
 }
 	
 	
     Return 0;
 }

Title ++, task-!

Thank you for watching!