Related Tags

automorphic
java
communitycreator

# How to check automorphic numbers in Java Harsh Jain

In this shot, we will learn how to check whether or not a number is automorphic. An automorphic number is a number whose square ends with the same digits as the number itself.

For example, 25 and 76 are automorphic numbers because their squares are 625 and 5776, respectively. The square’s last two digits represent the number itself. Other automorphic numbers are 5, 6, 36, 890625, and so on.

If we take 35 or 20 as input, we will see that the squares of these numbers, i.e., 1225 and 400, do not contain 35 or 20 at the end. So these numbers are not automorphic.

### Solution

We can follow the solution approach described below.

• Take a number as input.
• Square the number.
• Compare the last digit of the square with the last digit of the number till the number doesn’t become zero.
• If any digit mismatches, the number is not automorphic.

We will create an isAutomorphic() function which takes the square of the number and the number as input and returns true if the number is automorphic. Otherwise, it returns false.

### Code

Let’s look at the code now.

To test, input a number in the input box.

import java.util.Scanner;
class Automorphic {
public static void main(String[] args) {
Scanner sc= new Scanner (System.in);
int number= sc.nextInt();
int sqr= number*number;

//check whether the last digits of square are matched
// with the number itself
if(isAutomorphic(sqr,number))
System.out.println(number + " is an automorphic number");
else
System.out.println(number + " is not an automorphic number");
}

static boolean isAutomorphic(int square, int number){
while(number >0){
if(square%10!=number%10)
return false;
square/=10;
number/=10;
}
return true;
}
}


Enter the input below

Check whether or not the number is automorphic

### Explanation

• In the first line of code, we imported the java.util.Scanner class to read input from the user.

• In line 6, inside the main function, we take the number from the user by creating Scanner object and store that input in an integer number

• In line 7, we calculate the square of that number and store it in a variable sqr of integer type.

Assume that the square of that number is not more than Integer.MAX_VALUE in Java.

• In line 9, we call the isAutomorphic() function. If it returns true then we print that the number is automorphic. Otherwise we do not.

• From lines 17 to 27, we define the isAutomorphic() function. In this function, we run a while loop till the number is greater than 0. Then we compare the last digit of both squares of the number and the number itself, respectively. If they are not equal, we return false. Otherwise, we return true.

In this way, we can check whether a number is automorphic or not.

RELATED TAGS

automorphic
java
communitycreator

CONTRIBUTOR Harsh Jain
RELATED COURSES

View all Courses

Keep Exploring

Learn in-demand tech skills in half the time 