I was writing a program to check if a number is automorphic or not. I decided to test the program. But somehow, when I entered a number greater than 9376, it said that it was not an automorphic number.
Link for automorphic number: Automorphic number
import java.util.Scanner;
public class test{
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int copy=n,ex=0;
while(n!=0){
n/=10;
ex ;
}
if((copy*copy)%(Math.pow(10,ex))==copy){
System.out.println(copy " is an automorphic number.");
}
else{
System.out.println(copy " is not an automorphic number.");
}
}
}
I tried it with 5, 25, 76, 376 and it gave me the correct response. But when I entered 90625 or other numbers, it replied in negative.
Output for reference:
90625
90625 is not an automorphic number.
9376
9376 is an automorphic number.
CodePudding user response:
For large integers (like 90625), squaring it (copy * copy
) will result in an integer overflow.
If you print the value of copy * copy
for 90625, you'll get -377043967.
To fix this, you can make the variable copy
of type long
.
However, you have to decide what is the maximum or largest number you'll ever want this to work for. If the square of that number won't fit within the bounds of a long
, then you'd have to use a BigInteger. Since you had the input as an int
, using a long
should be good enough for you (A long
can hold the result of Integer.MAX_VALUE * Integer.MAX_VALUE
).