There are several articles on "how to check in Java whether a number is Automorphich or not" which you can find on the Internet including some from popular websites like GeeksforGeeks and JavaTpoint. But they all have a similar problem. They are not beginners friendly.
In this article, I will show you a beginner-friendly approach to find whether a number is Automorphic or not in Java.
An Automorphic Number is a number whose square has the exact number as its last digit. For example, 25 which is the square of 5 contains 5 as its last digit. An example of a two-digit number is 5776 which is the square of 76 and ends with 76. Some other examples are 625 which is the square of 25 and ends with 25.
Let's take a look at the easy approach to solving the problem first.
(n % 10 == sq % 10)
![Screenshot of the Automorphic Number Program in Java](https://cdn.hashnode.com/res/hashnode/image/upload/v1670005718985/9a8c69ff-af3a-40ea-a637-aba9bdc87560.jpeg align="center")
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int i, n, sq, c=0;
System.out.println("Enter a number to check for Automorphic Number");
n = in.nextInt();
sq = n * n;
for (i = n; n > 0; n = n / 10) {
if (n % 10 == sq % 10)
c++;
sq = sq / 10;
}
if (c > 0)
System.out.println("Automorphic Number");
else
System.out.println("Not an Automorphic Number");
}
}
import java.util.Scanner;
class Main
{
public static void main (String[]args)
{
Scanner in = new Scanner (System.in);
int n, sq, p, c = 0;
System.out.println ("Enter a number to check for Automorphic Number");
n = in.nextInt();
p = n;
sq = n * n;
while (n > 0)
{
if (n % 10 == sq % 10)
c++;
n = n / 10;
sq = sq / 10;
}
if (c > 0)
System.out.println ("Automorphic Number");
else
System.out.println ("Not an Automorphic Number");
}
}
The program is simple. We just have to check if the last digits of a number's square are equal to the number or not.
I have taken five variables:
for (i = n; n > 0; n = n / 10) { if (n % 10 == sq % 10) c++; sq = sq / 10;
The For Loop condition 'i=n' can be replaced with a semi-colon (;).
for (; n > 0; n = n / 10)
The condition inside the for loop is used to check whether the last digit of the variable n is equal to the last digit of variable sq or not. At the last of the loop, both the variables sq and n are divided by 10.
In While Loop, n = n / 10 is at the last with sq = sq / 10.
This loop continues till the value of n becomes 0. This is why previously the value of n is stored in the variable p.
Edit: There is no need for the variable p.
If the last digit of both the variables is the same, the counter variable c will be increased by 1.
After the loop is completed and n has become 0, the control will move outside the loop and then with an if-else condition we will check if the counter variable c is greater than 0 or not. If it is then the sq contains n as its last digit.
Also Published here