Write a Program in Java to input a number and check whether it is an Automorphic Number or not.
Note: An automorphic number is a number which is present in the last digit(s) of its square.
Example: 25 is an automorphic number as its square is 625 and 25 is present as the last digits
Example: 25 is an automorphic number as its square is 625 and 25 is present as the last digits
import
java.io.*;
class
Automorphic
{
public
static
void
main(String args[])
throws
IOException
{
BufferedReader br=
new
BufferedReader(
new
InputStreamReader(System.in));
System.out.print(
"Enter a Number : "
);
// Inputting the number
int
n = Integer.parseInt(br.readLine());
int
sq = n*n;
// Finding the square
String num = Integer.toString(n);
// Converting the number to String
String square = Integer.toString(sq);
// Converting the square to String
if
(square.endsWith(num))
// If the square ends with the number then it is Automorphic
System.out.print(n+
" is an Automorphic Number."
);
else
System.out.print(n+
" is not an Automorphic Number."
);
}
}
Working:
We have made use of the String function “endsWith()” to solve this program. This program could be done in other ways but, using Strings and its functions, we have tried to simplify it as much as we can.
The “endsWith()” function checks whether a String ends with a given String or a character or not.
In the above program we have accepted the number from the user and then found its square. We then converted both of them to String types. then using the endsWith() function we checked whether the square ends with the number or not (i.e. whether the square of the number has the number as its last digits or not). If the square ends with the number then the number is an Automorphic number otherwise not.
Alternate Method (Without using Strings):
import
java.io.*;
class
Automorphic
{
public
static
void
main(String args[])
throws
IOException
{
BufferedReader br=
new
BufferedReader(
new
InputStreamReader(System.in));
System.out.print(
"Enter a Number : "
);
// Inputting the number
int
n = Integer.parseInt(br.readLine());
int
sq = n*n;
// Finding the square
int
c =
0
, copy = n;
// While loop for counting the number of digits in the number
while
(copy >
0
)
{
c++;
copy = copy/
10
;
}
/* Finding the end digits of the square.
* If the number has 2 digits, then we need to find last 2 digits of square
* i.e. do a 'sq % 100' operation
*/
int
end = sq % (
int
)Math.pow(
10
,c);
if
(n == end)
// If the square ends with the number then it is Automorphic
System.out.print(n+
" is an Automorphic Number."
);
else
System.out.print(n+
" is not an Automorphic Number."
);
}
}
Output:
Enter a Number : 25
25 is an Automorphic Number.
Enter a Number : 6
6 is an Automorphic Number.
Enter a Number : 9
9 is not an Automorphic Number.
No comments:
Post a Comment