# Print all Semi-Prime Numbers less than or equal to N in C++

In this problem, we are given an integer N. and we have to print all the semiprime numbers that are less than or equal to N.

Before solving this problem, let’s understand what is a semi-prime number.

A semi-prime number is a number whose value is the product of two distinct prime numbers.

Let’s take an example,

21 = 3*7 is a semiprime number.

25 = 5*5 is not a semiprime number.

Now, let’s take an example of semiprime numbers less than or equal to n.

Input: N = 15
Output: 6 10 14 15

To solve this problem, we have to take each number less than equal to N and check if it has exactly two distinct prime factors.

Tip − we can also start our algorithm from 6 as the smallest semi-prime number is 6.

## Example

Live Demo

#include <bits/stdc++.h>
using namespace std;
vector<int>generateSemiPrimeNumbers(int n){
int index[n + 1];
for (int i = 1; i <= n; i++)
index[i] = i;
int countDivision[n + 1];
for (int i = 0; i < n + 1; i++)
countDivision[i] = 2;
for (int i = 2; i <= n; i++) {
if (index[i] == i && countDivision[i] == 2) {
for (int j = 2 * i; j <= n; j += i) {
if (countDivision[j] > 0) {
index[j] = index[j] / i;
countDivision[j]--;
}
}
}
}
vector<int> semiPrime;
for (int i = 2; i <= n; i++) {
if (index[i] == 1 && countDivision[i] == 0) semiPrime.push_back(i);
}
return semiPrime;
}
int main(){
int n = 15;
cout<<"Semi-prime numbers less that or equal to "<<n<<"are :\n";
vector<int>semiPrime = generateSemiPrimeNumbers(n);
for (int i = 0; i < semiPrime.size(); i++)
cout<<semiPrime[i]<<"\t";
return 0;
}

## Output

Semi-prime numbers less than or equal to 15 are −

6 10 14 15

Advertisements