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

  • برمجة سي بلس بلس
  • برمجة

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

الأجوبة

#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;
}
هل كان المحتوى مفيد؟

تبحث عن مدرس اونلاين؟

محتاج مساعدة باختيار المدرس الافضل؟ تواصل مع فريقنا الان لمساعدتك بتأمين افضل مدرس
ماهو التخصص الذي تبحث عنه؟
اكتب هنا...