write a program in java to input a number and check whether it is a automorphicnumber or not.
Answers
Question:-
Write a Java program to input a number and check whether it is a automorphic number or not.
Code:-
A number n is said to be an automorphic number if the square of the number ends with the same digit as the number has.
Consider n=5
n*n=25 and 25 ends with 5.
So, here the code comes.
import java.util.*;
class Automorphic
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int n=sc.nextInt();
int sq=n*n;
int x=n;
int digits=0;
while(n!=0)
{
digits++;
n/=10;
}
n=x;
int mod=sq%(int)Math.pow(10, digits);
if(mod==n)
System.out.println("Automorphic Number. ");
else
System.out.println("Not an Automorphic Number.");
}
}
Another approach using String function.
import java.util.*;
class Automorphic
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int n=sc.nextInt();
int sq=n*n;
String s1=n+"";
String s2=sq+"";
if(s2.endsWith(s1))
System.out.println("Automorphic Number. ");
else
System.out.println("Not an Automorphic Number.");
}
}