What is an Automorphic Number?
An automorphic number is a special number where the square of the number has the same digits as the number itself. In simpler terms, if you square the number and the last digits of the resulting number are the same as the original number, we can say that it’s an automorphic number. Here are some examples:
52 = 25 (ends in 5)
62= 36 (ends in 6)
252= 625 (ends in 25)
3762= 141376 (ends in 376)
How to Check if a Number is Automorphic?
Given a number N, the task is to check whether the number is an Automorphic number or not.Let’s take a look at how to write a Java program to check automorphic numbers:
Steps to Identify Automorphic Numbers
1. Compute the square of the number:
First, take the given number and calculate its square. For example, if the number is 25, you will calculate the 25 x 25 = 625.
2. Compare the last digits of the square with the number:
Next, focus on the last digits of the squared result. There are a couple of ways to do this. You can use the modulo operation to isolate the last digits. For example, to get the last two digits of 625, you can calculate 625 mod 100, which gives 25. You can also convert the numbers to strings and compare the last few characters.
3. Check for a match:
Now, compare the last digits of the square with the original number. If the digits match, the number is automorphic. For example, with the number 25, the square is 625, and the last two digits (25) match the original number, so 25 is automorphic.
Example Workflow
Continuing from the last example, let’s see how 25 is an automorphic number in Java. The program follows the same logic by squaring the number and comparing the last digits of the square to the original number. If they match, the number is automorphic.
Algorithm
1. Initialize an integer variable number with the value 25.
2. Compute the square of the number: square = number * number.
3. Find the number of digits in number by converting it to a string and finding its length: numDigits = String.valueOf(number).length().
4. Extract the last digits of the square by modulus operation: lastDigits = square % (Math.pow(10, numDigits)).
5. Compare lastDigits with number:
- If they are equal, print that the number is an Automorphic number.
- Otherwise, print that the number is not an Automorphic number.
Code
public class Main {
public static void main(String[] args) {
int number = 25;
// Step 1: Compute the square of the number
int square = number * number;
// Step 2: Get the number of digits in the original number
int numDigits = String.valueOf(number).length();
// Step 3: Get the last digits of the square
int lastDigits = square % (int) Math.pow(10, numDigits);
// Step 4: Compare and check for a match
if (lastDigits == number) {
System.out.println(number + " is an Automorphic number.");
} else {
System.out.println(number + " is not an Automorphic number.");
}
}
}
How The Code Works
- Compute the Square: The number is squared (25 * 25 = 625).
- Find the Number of Digits: The code determines how many digits the original number has (in this case, 25 has 2 digits).
- Get the Last Digits of the Square: It uses the modulus operation to extract the last 2 digits of the square (625 % 100 = 25).
- Compare: If the last digits of the square match the original number, it prints that the number is automorphic. Otherwise, it prints that it's not.
Output
25 is an Automorphic number.
=== Code Execution Successful ===
Different Java Program to Check Automorphic Numbers
In this section, we will delve into different Java programs to check for automorphic numbers. We will explore various approaches, from basic iterations to more optimized solutions, showcasing how Java can be utilized to tackle this intriguing mathematical concept. With hands-on examples and code snippets, you’ll gain practical experience in checking automorphic numbers and enhancing your programming skills.
1. Java Program to Check Automorphic Numbers Using String Manipulation
Now, let’s write a Java program to check automorphic number:
Algorithm:
1. Create a Scanner object to take user input.
2. Prompt the user to enter a number and store it in the variable number.
3. Compute the square of the number: square = number * number.
4. Convert both number and square to strings: numStr = String.valueOf(number), squareStr = String.valueOf(square).
5. Check if squareStr ends with numStr:
- If true, print that the number is an Automorphic number.
- If false, print that the number is not an Automorphic number.
6. Close the scanner.
Code
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// Create a Scanner object to take user input
Scanner scanner = new Scanner(System.in);
// Ask the user to enter a number
System.out.print("Enter a number: ");
int number = scanner.nextInt();
// Step 1: Compute the square of the number
int square = number * number;
// Step 2: Convert both the number and its square to strings
String numStr = String.valueOf(number);
String squareStr = String.valueOf(square);
// Step 3: Check if the last digits of the square match the number
if (squareStr.endsWith(numStr)) {
System.out.println(number + " is an Automorphic number.");
} else {
System.out.println(number + " is not an Automorphic number.");
}
// Close the scanner
scanner.close();
}
}
How The Code Works
- Import Scanner: The program imports the Scanner class to take user input.
- Create Scanner Object: A Scanner object is created to read input from the user.
- Prompt User: It prompts the user to enter a number.
- Read Input: The entered number is stored in the number variable.
- Calculate Square: The square of the number is calculated.
- Convert to Strings: Both the number and its square are converted to strings.
- Check Automorphic: It checks if the square ends with the same digits as the number using endsWith().
- Display Result: If they match, it prints that the number is Automorphic; otherwise, it prints that it's not.
- Close Scanner: The Scanner object is closed to free resources.
Output
Enter a number: 65
65 is not an Automorphic number.
=== Code Execution Successful ===
2. Java Program to Check Automorphic Numbers Using Modulus Operator
The automorphic number in Java can be implemented using different approaches. One variation involves using the modulus operator. Here’s a program that checks if a number is automorphic using the modulus operator:
Algorithm
1.Create a Scanner object to take user input.
2. Prompt the user to enter a number and store it in the variable number.
3. Compute the square of the number: square = number * number.
4. Find the number of digits in number using Math.log10 and add 1: digits = Math.log10(number) + 1.
5. Get the last digits number of digits of square using modulus: lastDigits = square % Math.pow(10, digits).
6. Check if lastDigits equals number:
- If true, print that the number is an Automorphic number.
- If false, print that the number is not an Automorphic number.
6. Close the scanner.
Code
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// Create a Scanner object to take user input
Scanner scanner = new Scanner(System.in);
// Ask the user to enter a number
System.out.print("Enter a number: ");
int number = scanner.nextInt();
// Step 1: Compute the square of the number
int square = number * number;
// Step 2: Find the number of digits in the original number
int digits = (int) Math.log10(number) + 1;
// Step 3: Get the last digits of the square using modulus
int lastDigits = square % (int) Math.pow(10, digits);
// Step 4: Check if the last digits match the original number
if (lastDigits == number) {
System.out.println(number + " is an Automorphic number.");
} else {
System.out.println(number + " is not an Automorphic number.");
}
// Close the scanner
scanner.close();
}
}
How The Code Works
- User Input: The program asks the user to input a number, which is stored in the variable number.
- Square Calculation: It calculates the square of the number (number * number) and stores it in the square variable.
- Find Number of Digits: The number of digits in the input is calculated using Math.log10(number) + 1.
- Extract Last Digits: Using the modulus operator, the program extracts the last digits of the square based on the input's digit count.
- Comparison: It checks if the extracted last digits match the original number. If they match, the number is automorphic; otherwise, it is not.
- Output: The program prints whether the number is automorphic or not.
Output
Enter a number: 85
85 is not an Automorphic number.
=== Code Execution Successful ===
3. Java Program to Check Automorphic Numbers using For Loop
In this program we check whether a number is automorphic using a for loop. It iterates through the digits of the number and compares them with the last digits of its square.
Algorithm
1. Create a Scanner object to take user input.
2. Prompt the user to enter a number and store it in the variable number.
3. Compute the square of number and store it in square.
4. Initialize a temporary variable temp with the value of number and set a Boolean variable isAutomorphic to true.
5. Use a for loop to check each digit:
- In each iteration, compare the last digit of temp and square:
- If the last digits do not match, set isAutomorphic to false and exit the loop.
- If the digits match, move to the next digit by dividing both temp and square by 10.
6. After the loop, check the value of isAutomorphic:
- If true, print that the number is an Automorphic number.
- If false, print that the number is not an Automorphic number.
7. Close the scanner.
Code
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// Create a Scanner object for user input
Scanner scanner = new Scanner(System.in);
// Ask the user to enter a number
System.out.print("Enter a number: ");
int number = scanner.nextInt();
// Compute the square of the number
int square = number * number;
int temp = number;
boolean isAutomorphic = true;
// Check each digit using a for loop
for (; temp > 0; temp /= 10, square /= 10) {
if (temp % 10 != square % 10) {
isAutomorphic = false;
break;
}
}
// Print the result
if (isAutomorphic) {
System.out.println(number + " is an Automorphic number.");
} else {
System.out.println(number + " is not an Automorphic number.");
}
// Close the scanner
scanner.close();
}
}
How the code works
1. Take User Input: The program uses Scanner to take a number as input from the user.
2. Compute the Square: The square of the number is calculated and stored.
3. Initialize Variables: A temporary variable temp holds the original number and a boolean flag isAutomorphic is set to true.
4. Use a For Loop to Check Digits: The loop iterates while temp > 0, extracting the last digits of both temp and square in each step.
5. Compare Last Digits: If any digit of temp does not match the corresponding digit in square, the flag isAutomorphic is set to false, and the loop breaks.
6. Print the Result: Based on the flag, the program prints whether the number is automorphic or not.
7. Close the Scanner: The scanner is closed to prevent resource leaks.
Output
Enter a number: 376
376 is an Automorphic number.
=== Code Execution Successful ===
4. Java Program to Check Automorphic Numbers Using While Loop
In this program, we’ll use a while loop to check for automorphic numbers:
Algorithm:
1. Create a Scanner object to take user input.
2. Prompt the user to enter a number and store it in the variable number.
3. Compute the square of number and store it in square.
4. Initialize a temporary variable temp with the value of number and a boolean variable isAutomorphic to true.
5. Use a while loop to check the last digits of temp and square:
In each iteration, compare the last digit of temp and square:
If they do not match, set isAutomorphic to false and exit the loop.
If they match, divide both temp and square by 10 to remove the last digits.
6. After the loop, check the value of isAutomorphic:
- If true, print that the number is an Automorphic number.
- If false, print that the number is not an Automorphic number.
7. Close the scanner.
Code
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// Create a Scanner object for user input
Scanner scanner = new Scanner(System.in);
// Ask the user to enter a number
System.out.print("Enter a number: ");
int number = scanner.nextInt();
// Compute the square of the number
int square = number * number;
// Initialize a temporary variable to store the number
int temp = number;
// Check if the number is Automorphic
boolean isAutomorphic = true;
// While loop to check the last digits
while (temp > 0) {
if (temp % 10 != square % 10) {
isAutomorphic = false;
break;
}
temp /= 10;
square /= 10;
}
// Print the result
if (isAutomorphic) {
System.out.println(number + " is an Automorphic number.");
} else {
System.out.println(number + " is not an Automorphic number.");
}
// Close the scanner
scanner.close();
}
}
How the Code Works:
- Take User Input: The program takes an integer input using Scanner.
- Compute the Square: The square of the input number is calculated.
- Initialize Variables: A temporary variable temp stores the number, and a boolean flag isAutomorphic is set to true.
- Use While Loop to Check Digits: The loop runs while temp > 0, comparing the last digits of both temp and square at each step.
- Compare Last Digits: If any last digit does not match, isAutomorphic is set to false, and the loop breaks.
- Print the Result: Based on the flag, the program prints whether the number is automorphic or not.
- Close the Scanner: The scanner is closed to prevent resource leaks.
Output
Enter a number: 625
625 is an Automorphic number.
=== Code Execution Successful ===
Java Program to Check Automorphic Numbers in a Range (0-10,000)
Here’s a program to check for automorphic numbers in the range of 0-10,000:
Algorithm:
1. Print the header message "Automorphic numbers between 0 and 10000:".
2. Loop through numbers from 0 to 10000:
- For each number, check if it is an Automorphic number using the isAutomorphic function.
- If the number is Automorphic, print it.
3. Define the isAutomorphic function to check if a number is Automorphic:
- Compute the square of the number and store it in square.
- Initialize a temporary variable temp with the value of the number.
- Use a while loop to check the last digits of temp and square:
- If the last digits do not match, return false.
- If they match, divide both temp and square by 10 to remove the last digits.
- If all digits match, return true.
4. The program will print all Automorphic numbers between 0 and 10000.
Code
public class Main {
public static void main(String[] args) {
System.out.println("Automorphic numbers between 0 and 10000:");
// Loop through numbers from 0 to 10000
for (int number = 0; number <= 10000; number++) {
if (isAutomorphic(number)) {
System.out.print(number + " ");
}
}
}
// Function to check if a number is Automorphic
static boolean isAutomorphic(int number) {
int square = number * number;
int temp = number;
// Check if last digits of square match the number
while (temp > 0) {
if (temp % 10 != square % 10) {
return false;
}
temp /= 10;
square /= 10;
}
return true;
}
}
How the Code Works:
1. Loop Through the Range: The program iterates from 0 to 10,000, checking each number.
2. Check for Automorphic Property: The isAutomorphic() function determines if a number is automorphic.
3. Compute Square: The square of the number is calculated.
4. Use a While Loop to Compare Digits: The last digits of the number and its square are compared. If they match for all digits, the number is automorphic.
5. Print the Automorphic Numbers: If a number is automorphic, it gets printed.
Output
Automorphic numbers between 0 and 10000:
0 1 5 6 25 76 376 625 9376
=== Code Execution Successful ===
Complexity of Automorphic Number Programs
Understanding the complexity of automorphic number programs is crucial because it helps us evaluate the efficiency of the code. Now, let’s look at the time and space complexity of these.
Time Complexity
The time complexity of automorphic number programs that use digit-by-digit comparison like the modulus operator method is O(log₁₀N). Here, N is the input number. This is because the program processes each digit of N, and the number of digits in N is proportional to log₁₀N. The loop runs once for each digit of N, which makes it logarithmic in nature.
Space Complexity
The space complexity of the discussed programs is O(1). The program uses a fixed amount of memory to store variables like N, sq, and intermediate values, regardless of the size of the input. No additional memory is allocated based on the input size, which makes the space usage constant.
Common Errors and Debugging Tips
1. Incorrect Square Calculation
Error: Sometimes the square of the number might be calculated wrong by the user. Then, the program gives the wrong result.
Tip: Make sure you're correctly squaring the number and checking it by printing the value to see if it's correct. Also, remember that the number should be positive before squaring it.
2. Digit Mismatch
Error: The program may fail to correctly match the number's digits and its square, which means it won’t give the right answer.
Tip: Add print statements to check which digits are being compared. The code should show you're comparing the number's last digit with the square's last digit. Both should be updated correctly in each step.
3. Overflow Errors
Error: Squaring a large number can sometimes cause an overflow, where the result is too big for the program to handle which can give errors.
Tip: Use a larger data type, like long, if the number is too big for an int. Print the squared value to ensure it doesn’t exceed the maximum allowed value.
4. Off-By-One Errors in Loops
Error: Sometimes, loops may go one step too far or not far enough, which can cause the program to compare the wrong digits.
Tip: Check the loop conditions and make sure they are set up correctly. Print out the digits you’re comparing so everything is being checked properly.
5. Incorrect Handling of Negative Numbers
Error: Negative numbers might cause problems when squaring and comparing digits.
Tip: Always use the absolute value of the number (positive version) before squaring it. This will prevent issues with negative inputs.
6. Not Handling Edge Cases
Error: Some small numbers like 0 or 1 might not be handled correctly, leading to unexpected results.
Tip: Test your program with edge cases such as 0 and 1 to make sure it works in all situations.
Conclusion
Learning to write an automorphic number program is super important. It helps you understand how algorithms work, how to compare digits, and how to solve problems step by step. This problem builds your coding skills, sharpens your logical thinking, and prepares you for tough challenges. It’s not just about checking if a number is automorphic but learning how to break down problems into smaller parts, which is all about coding. Plus, mastering such problems prepares you for coding competitions and even job interviews. To get even better, enroll in the CCBP 4.0 Academy Program.
Frequently Asked Questions
1. What is an automorphic number?
An automorphic number is a number whose square ends with the same digits as the number itself. Simple example? 25, because 25² = 625, and 25 is at the end!
2. Why should I learn about automorphic numbers?
Learning this helps you understand how to deal with numbers, use loops, and practice comparisons in coding. It’s a solid skill for interviews and programming contests.
3. Can automorphic numbers be negative?
No negative numbers won’t work when negative. You need to take the absolute value first. For example, -25 becomes 25, and we check its square then.
4. Where will I use automorphic numbers in the real world?
You won’t use it much in daily life, but learning such problems improves your problem-solving skills. It helps in coding interviews and competitions where thinking sharp matters most.
5. What if my program is giving the wrong result?
Check if you're squaring the number correctly or if you’re comparing the digits in the right way. Debug step by step and add print statements for help.