Java Program to Check Automorphic Number
An automorphic number is a number whose square ends with the same digits as the number itself.
For example, 25 is an automorphic number because 25² = 625 (ends with 25).
1. Understanding the Problem
Determine whether a given number is an automorphic number.
Number: 5 → Automorphic Number: 25 → Automorphic Number: 7 → Not Automorphic
2. Using Basic Loop
Java
Check automorphic number using loop
import java.util.Scanner;
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;
boolean isAutomorphic = true;
while (temp > 0) {
if (temp % 10 != square % 10) {
isAutomorphic = false;
break;
}
temp /= 10;
square /= 10;
}
if (isAutomorphic)
System.out.println("Automorphic Number");
else
System.out.println("Not an Automorphic Number");
}
}
3. Optimized Approach
Java
Check automorphic number using string comparison
import java.util.Scanner;
public class AutomorphicOptimized {
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;
String numStr = String.valueOf(num);
String squareStr = String.valueOf(square);
if (squareStr.endsWith(numStr))
System.out.println("Automorphic Number");
else
System.out.println("Not an Automorphic Number");
}
}
4. Common Mistakes
1. Comparing entire square instead of last digits.
2. Forgetting to square the number.
3. Incorrect digit comparison logic.
4. Not handling single-digit cases properly.
5. Applications
1. Useful in number theory concepts.
2. Helps practice digit comparison logic.
3. Common beginner programming problem.
Conclusion
Automorphic numbers help in understanding number patterns and digit matching.
Using string methods can simplify the implementation.
Codecrown