
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Print all multiplicative primes <= N in C++
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
#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
- Related Articles
- Print all safe primes below N in C++
- Print all Proth primes up to N in C++
- Find the sum of all Truncatable primes below N in Python
- Alternate Primes till N in C++?
- Print all n-digit strictly increasing numbers in C++
- Print all n digit patterns formed by mobile Keypad in C++
- Queries to Print All the Divisors of n using C++
- Print all prime numbers less than or equal to N in C++
- Print all possible sums of consecutive numbers with sum N in C++
- Generate a list of Primes less than n in Python
- Print all leaf nodes of an n-ary tree using DFS in C++
- Print all Semi-Prime Numbers less than or equal to N in C++
- Maximum Primes whose sum is equal to given N in C++
- Multiplicative order in java
- Print all odd numbers and their sum from 1 to n in PL/SQL

Advertisements