Java Online Compiler
Example: Automorphic Number Checker in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// Automorphic Number Checker import java.util.Scanner; // Main class containing the entry point of the program public class Main { public static void main(String[] args) { // Step 1: Create a Scanner object to read input from the user Scanner scanner = new Scanner(System.in); // Step 2: Prompt the user to enter a number System.out.print("Enter an integer: "); int number = scanner.nextInt(); // Step 3: Calculate the square of the number long square = (long) number * number; // Use long to prevent overflow for larger numbers // Step 4: Determine the number of digits in the original number // This is needed to extract the correct number of last digits from the square int tempNumber = number; int numberOfDigits = 0; if (tempNumber == 0) { // Handle the case for number 0 numberOfDigits = 1; } else { while (tempNumber > 0) { tempNumber /= 10; numberOfDigits++; } } // Step 5: Calculate the divisor to extract the last 'numberOfDigits' from the square // For example, if number is 5 (1 digit), divisor is 10^1 = 10 // If number is 25 (2 digits), divisor is 10^2 = 100 long divisor = 1; for (int i = 0; i < numberOfDigits; i++) { divisor *= 10; } // Step 6: Extract the last digits of the square long lastDigitsOfSquare = square % divisor; // Step 7: Compare the original number with the extracted last digits if (number == lastDigitsOfSquare) { System.out.println(number + " is an automorphic number."); } else { System.out.println(number + " is not an automorphic number."); } // Step 8: Close the scanner scanner.close(); } }
Output
Clear
ADVERTISEMENTS