Q:

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

0

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 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

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

#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;
}

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Similar questions


need a help?


find thousands of online teachers now