Check Automorphic Number in Java
Problem
An automorphic number is a number that appears unchanged as the trailing digits of its own square.
Given a number, determine whether it is an automorphic number.
Java Program
public class AutomorphicCheck {
public static void main(String[] args) {
int num = 76;
long square = (long) num * num; // avoid int overflow on larger inputs
String numStr = String.valueOf(num);
String squareStr = String.valueOf(square);
boolean isAutomorphic = squareStr.endsWith(numStr);
System.out.println(num + " is an automorphic number: " + isAutomorphic);
}
}Output
Core Logic
Squaring the number and checking whether the square's string representation ends with the original number's digits answers the question directly.
- 1
squareis computed asnum * num, cast to alongto avoid overflow on larger inputs. - 2
String.valueOf(square)andString.valueOf(num)convert both values into text. - 3
.endsWith(numStr)checks whether the square's digits end with exactly the original number's digits.
76, the square is 5776, whose text representation "5776" ends with "76" — a match.Key Point: Casting to long before squaring matters for larger automorphic numbers — an int square can silently overflow well before the number itself looks large.
Why: Squaring and formatting a fixed-size number are both constant-time operations that don't scale with the number's magnitude in any meaningful way for typical input sizes.
Key Concepts
Approach 2: Without String Conversion
public class AutomorphicCheckArithmetic {
public static void main(String[] args) {
int num = 76;
long square = (long) num * num;
int digitCount = String.valueOf(num).length();
long divisor = (long) Math.pow(10, digitCount);
// Extracts the last digitCount digits of the square using modulo
boolean isAutomorphic = (square % divisor) == num;
System.out.println(num + " is an automorphic number: " + isAutomorphic);
}
}
Output
Core Logic
The same trailing-digits check can be done with pure arithmetic — take the square modulo a power of 10 matching the original number's digit count.
- 1
digitCountis found fromString.valueOf(num).length(), purely to size the modulo divisor — no string comparison happens. - 2
Math.pow(10, digitCount)computes the divisor:10raised to the digit count, e.g.100for a 2-digit number. - 3
square % divisorextracts exactly the lastdigitCountdigits of the square. - 4That remainder is compared directly against the original number.
76, digitCount is 2, so the divisor is 100; 5776 % 100 = 76, which matches the original number.Key Point: This avoids building any String objects at all — the comparison stays entirely in the numeric domain, which matters more for very large numbers checked repeatedly.
Why: The modulo and power operations run in constant time regardless of the number's magnitude, with no string allocation involved.