Print all Multiplicative Primes ≤ N in Java
Hi folks, today we will learn how to Print all Multiplicative Primes ≤ N in java.
We can assume you know about prime numbers. If you don’t check this: Java Program To Check A Number Is Prime or Not
So, what are multiplicative primes? If the product of the digits of a prime number is also a prime number then the number is known as a multiplicative prime.
Example:
for N=15,
multiplicative primes are { 2, 3, 5, 7, 13} as we can check on multiplying their digits, they will all result in a prime number.
Please Remember there could be multiple ways to solve a particular problem as per your understanding.
Multiplicative Primes ≤ N: Java Code
import java.util.Scanner; class Main { //check whether the passed no. is prime or not public static boolean checkPrime(int i) { int a=0; for(int j=2;j<=i;j++) { if(i%j==0) a++; if(a>1) return false; } return true; } //calculating the product of digits public static int proDigits(int i) { int a=1; while(i!=0) { a=a*(i%10); i/=10; } return a; } public static void main(String []args) { Scanner sc=new Scanner(System.in); int n=sc.nextInt(); if(n<=1) //Error handler { System.out.println("No Multiplicative prime!"); return; } for(int i=2;i<=n;i++) { if(checkPrime(i)) { int j=proDigits(i); if(checkPrime(j) && j>1) { System.out.print(i+" "); } } } } }
Output:
-5 //input No Multiplicative prime!
20 //input 2 3 5 7 13 17
1 //input No Multiplicative prime!
Explanation:
In the above code, we have defined two methods:
- checkprime() which takes an integer value and will return a boolean value based on the decision whether the passed number is prime or not.
- proDigits() which will take an integer number and multiply all the digits of that number and return the result.
So, the program logic is: first, we check whether the number (up to N) is prime or not and if the number is prime we will calculate the product of its digits: k (say) and again check the whether k is prime or not.
Now, you know how to Print all multiplicative primes ≤ N in java.
you may also read:
Leave a Reply