Automorphic Number in Java
An Automorphic Number is a number whose square ends with the number itself. Automorphic numbers are commonly asked in Java programming assignments, school exams, and coding interviews because they test logical reasoning and understanding of number manipulation.
What Is an Automorphic Number?
A number n is considered automorphic if:
The last digits of n² match the digits of n
Examples
- 5 → 25 (ends with 5)
- 6 → 36 (ends with 6)
- 25 → 625 (ends with 25)
- 76 → 5776 (ends with 76)
Therefore, numbers like 5, 6, 25, 76, 376, 625 are automorphic.
How Do We Check Automorphic Numbers in Java?
The logic is straightforward:
- Compute the square of the number
- Count the digits of the original number
- Extract the last digits of the square equal to the number of digits of the original number
- Compare both values
Java Program to Check Automorphic Number
import java.util.*;
public class AutomorphicNumber {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = sc.nextInt();
int square = num * num;
int temp = num;
int digits = 0;
while (temp > 0) {
digits++;
temp /= 10;
}
int lastDigits = square % (int)Math.pow(10, digits);
if (lastDigits == num) {
System.out.println(num + " is an Automorphic Number.");
} else {
System.out.println(num + " is NOT an Automorphic Number.");
}
}
}
Example Explanation
If the input is 76:
- 76² = 5776
- Last two digits = 76
- Since both match, 76 is an Automorphic Number
Common Automorphic Numbers
- 1
- 5
- 6
- 25
- 76
- 376
- 625
Practice Challenge
Write a Java program that prints all automorphic numbers between 1 and 10,000. Use the same logic as above but apply it inside a loop. This will help reinforce the concept and improve your understanding of number-based Java programs.