# Print all multiplicative primes <= N in C++

C++Server Side ProgrammingProgramming

In this problem, we are given an integer n and we have to print all multiplicative primes less than or equal to n.

Multiplicative primes are prime numbers that have a product of their digits also prime numbers. Like 2, 3, 5, 7, 13, 17.

23 is prime but not a multiplicative prime because of 2*3 = 6.

Let’s take an example to understand the problem −

Input: n = 9
Output: 2 3 5 7

To solve this problem, we will find all prime numbers less than n. And check if the number is multiplicative prime. And print all multiplicative prime less than n.

## Example

The program illustrates the solution to the problem

Live Demo

#include <bits/stdc++.h>
using namespace std;
int digitMultiply(int n) {
int prod = 1;
while (n) {
prod = prod * (n % 10);
n = n / 10;
}
return prod;
}
void generateMprime(int n) {
bool prime[n + 1];
memset(prime, true, sizeof(prime));
prime[0] = prime[1] = false;
for (int p = 2; p * p <= n; p++) {
if (prime[p]) {
for (int i = p * 2; i <= n; i += p)
prime[i] = false;
}
}
for (int i = 2; i <= n; i++) {
if (prime[i] && prime[digitMultiply(i)])
cout<<i<<"\t";
}
}
int main() {
int n = 10;
cout<<"All multiplicative Prime Numbers =< "<<n<<" are :\n";
generateMprime(n);
}

## Output

All multiplicative Prime Numbers =< 10 are −
2 3 5 7
Published on 22-Jan-2020 10:50:49