Customs of House Numbers (C++) kkmd66

ideas

The meaning of the title is to find a prime number in a given interval, and the conventional idea is timed out, such as code 1.
Use Eratosthenes to filter prime numbers without timeout, code 2.

Description:

There is a strange custom in a certain area: it's like, first of all, their town hall has the house number 1, then next is the house number of the inhabitants (poor or rich), the rich man's house number can't always be used by the poor Divisible, the house number of the poor can be at least divisible by the house number of a rich man, and a house number corresponds to either the poor or the rich, and no house number corresponds to anyone (except for the city hall).
Now Sake students need to count at least how many rich people in a certain house section. Can you guys help sake?

Input:

There are multiple sets of test data, each set of test data includes two positive integers a,b (a<=b<1000000)

Output:

Output the at least rich people in the interval a and b (including the two endpoints of a and b).

Sample Input:

7 11

Sample Output:

2

code 1

#include <iostream>
#include <valarray>

using namespace std;

/**
 * kkmd66
 * @return
 */

int main() {
    
    

    int a, b;
    while (cin >> a >> b) {
    
    

        int count = 0;

        for (int i = a; i <= b; ++i) {
    
    
            bool flag = true;

            for (int j = 2; j <= sqrt(i); ++j) {
    
    
                if (i % j == 0) {
    
    
                    flag = false;
                    break;
                }
            }
            if (flag)
                count++;
        }

        cout << count << endl;
    }

    return 0;
}

code 2

#include<iostream>
#include<vector>

using namespace std;

/**
 * kkmd66
 * @return
 */

int main() {
    
    
    int a, b;

    //为了数和下标对应
    vector<bool> vec(1000002, true);
    vector<int> sum(1000002, 0);

    //埃拉托色尼筛选算法
    //从2开始,把 i 的倍数删除
    for (int i = 2; i <= 1000001; i++) {
    
    
        if (vec[i]) {
    
    
            for (int j = 2 * i; j <= 1000000; j += i) {
    
    
                vec[j] = false;
            }
        }
    }

    //截止到 i 为止,素数个数
    for (int i = 2; i <= 1000001; i++) {
    
    
        if (vec[i])
            sum[i] = sum[i - 1] + 1;
        else
            sum[i] = sum[i - 1];
    }

    //包含 a 端点,所以要-1
    while (cin >> a >> b) {
    
    
        cout << sum[b] - sum[a - 1] << endl;
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324123773&siteId=291194637