Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
w3resource

C++ Exercises: Count the prime numbers less than a given positive number

C++ Math: Exercise-24 with Solution

Write a C++ program to count the prime numbers less than a given positive number.

Sample Input: n = 8
Sample Output: Number of prime numbers less than 8 is 2
Sample Input: n = 30
Sample Output: Number of prime numbers less than 30 is 10

Sample Solution:

C++ Code :

#include <iostream>
#include <cmath>

using namespace std;
class Solution {
public:
    int count_Primes(int n) {
        int ctr = 0;
        for (int i = 2; i < n; i++) {
            if (is_Prime(i)) {
            
                ctr++;
            }
        }
        return ctr;
    }

bool is_Prime(int n) {
        int n_ = int(sqrt(n));
        for (int i = 2; i <= n_; i++) {
            if (0 == n % i) {
                return false;
            }
        }
        return true;
    }
};

int main() {
    Solution *solution = new Solution();
    int n = 8;
    cout << "Number of prime numbers less than " << n << " is " <<  solution->count_Primes(5) << endl;
    n = 30;
    cout << "Number of prime numbers less than " << n << " is " <<  solution->count_Primes(30) << endl;    
    n = 100;
    cout << "Number of prime numbers less than " << n << " is " <<  solution->count_Primes(100) << endl;    
    return 0;
}

Sample Output:

Number of prime numbers less than 8 is 2
Number of prime numbers less than 30 is 10
Number of prime numbers less than 100 is 25

Flowchart:

Flowchart: Count the prime numbers less than a given positive number

C++ Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a C++ program to compute square root of a given non-negative integer.
Next: Write a C++ program to count the total number of digit 1 pressent in all positive numbers less than or equal to a given integer.

What is the difficulty level of this exercise?