Check and display whether it is a prime number or not OR an automorphic number or not.
Identify the number is EITHER prime number or not OR an automorphic number or not.
If you need some data from the user then you need to import the Scanner class. If you want to know more about Scanner class then, please visit this link (https://programmerbrothers.blogspot.com/2019/04/scanner-class-in-java-scanner-is-class.html)
import java.util.Scanner;public class NumberCheck{// instance variablesprivate int x;int b;public void Prime(){System.out.println("Enter a number");x= new Scanner(System.in).nextInt();
The statements mentioned below check that the input number is either prime or not. Prime numbers are perfectly divisible by only 1 and the same number. So, following such trick, the number is divided by every number to that number and checked.
for(int a=1;a<=x;a++){if(x%a==0){b++;}}if(b>2){System.out.println(x+" is not a prime number");}else{System.out.println(x+" is a prime number");}}public void automorphicNumber(){System.out.println("Enter a number");x= new Scanner(System.in).nextInt();int y=x*x;// Conversion of the value of int Datatype to String DatatypeString Str_x=Integer.toString(x);String Str_y=Integer.toString(y);
Java String Str_y.endsWith(Str_x) check whether the ends of the Str_y match with the string(Str_x) or not. It provides the result in boolean type(either true or false). If the given condition is satisfied(the ends of the Str_y match with the string(Str_x)) then it returns the value 'true' and the statements inside that condition is executed and if the given condition is not satisfied(the ends of the Str_y does not match with the string(Str_x)) then it returns the value 'false' and skip the statements inside that condition.
if(Str_y.endsWith(Str_x)){System.out.println(x+" is a automorphic number");}else{System.out.println(x+" is not a automorphic number");}}public static void main(String []args){NumberCheck n= new NumberCheck();n.Prime();n.automorphicNumber();}}
Output of the above program seems like this:-
Comments
Post a Comment