Write a java loop program to accecpt a number and find the largest prime digit present in it.
Answers
Answer:
The given program is written in Java.
import java.util.*;
public class PrimeDigit {
static boolean isPrime(int a){
for(int i=2;i<a;i++){
if(a%i==0)
return false;
}
return true;
}
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
int n,max=0,d;
System.out.print("Enter a number: ");
n=sc.nextInt();
while(n!=0) {
d=n%10;
if(isPrime(d))
max=Math.max(max,d);
n/=10;
}
System.out.println("Largest prime digit is: "+max);
sc.close();
}
}
The isPrime() function checks whether a number is prime or not.
Logic is very simple, check whether the digit is prime or not. If prime, compare that digit with the max variable. Repeat this process until the number is not zero and then display the largest prime digit.
Refer to the attachment for output.
•••♪
Program:-
import java.util.*;
public class Demo
{
public static void main(String args[ ])
{
Scanner in=new Scanner(System.in);
int n,num=0,a=0,c=0,max=0;
System.out.println("Enter the number");
n=in.nextInt();
num=n;
while(n!=0)
{
a=n%10;
n=n/10;
for(int i=1;i<=a;i++)
{
if(a%i==0)
c++;
}
if(c==2)
max=Math.max(max,a);
}
System.out.println("Largest prime digit="+max);
}
}
Refer to the attachment.
- Refer to the attachment.The first photo is the program I hided the main method and class all so that you focus on the logic.
- .The second photo is the input.
- .The second photo is the input.The third photo is the output.