Find count of Almost Prime numbers from 1 to N in C++


Suppose we have a number N. We have to find almost prime numbers in range 1 to N. A number is called almost prime when it has exactly two distinct factors. The numbers can have any number of non-prime factors, but should be two prime factors. So if N is 2, then output will be 2. There are two numbers 6 and 10.

Here we will use the Sieve of Eratosthenes approach. Please check the following implementation to get better idea.

Example

 Live Demo

#include<iostream>
#define N 100005
using namespace std;
bool prime[N];
void SieveOfEratosthenes() {
   for(int i = 0; i<N; i++)
   prime[i] = true;
   prime[1] = false;
   for (int i = 2; i * i < N; i++) {
      if (prime[i] == true) {
         for (int j = i * 2; j < N; j += i)
            prime[j] = false;
      }
   }
}
int countAlmostPrime(int n) {
   int result = 0;
   for (int i = 6; i <= n; i++) {
      int div_count = 0;
      for (int j = 2; j * j <= i; j++) {
         if (i % j == 0) {
            if (j * j == i) {
               if (prime[j])
                  div_count++;
            }else {
               if (prime[j])
                  div_count++;
               if (prime[i / j])
                  div_count++;
            }
         }
      }
      if (div_count == 2)
         result++;
   }
   return result;
}
int main() {
   SieveOfEratosthenes();
   int n = 21;
   cout << "Number of almost primes in range 1 to "<<n << " is: " << countAlmostPrime(n);
}

Output

Number of almost primes in range 1 to 21 is: 8

Updated on: 18-Dec-2019

265 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements