Search code examples
javabluej

Error says it's dividing by zero while it's not initialised as zero


Im trying to find if the number is automorphic, the code compiles fine but it says there is divide by zero on the line where i've marked it

import java.util.Scanner;
class AutoLoop
{
    public static void main()
    {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter a number to check if it's automorphic or not");
        int num = sc.nextInt();
        int sqr = num*num;
        int sqrSave=sqr;
        int divisor = 10;
        int counter = 1;
        while (counter<=100)
        {
            sqr = sqr%divisor;  //It says there is divide by zero error on this line
            if (sqr==num)
            {
                System.out.println("Number is an automorphic number");
                break;
            }
            sqr=sqrSave;
            divisor*=10;
            counter++;
            if (counter == 100)
                 System.out.println("Number is not an automorphic number till the 100th digit.");
        }
    }
}

i've already tried making it sqr%=divisor; still doesn't work.


Solution

  • I've tested your code and it seems to be that you try to multiply the divisor variable past the 32 bit integer limit, and since that is not possible, it becomes some other numbers, and after a while it turns into a zero. This happens every time you enter an non-automorphic number

    This is the value of the divisor every time your code loops around:

    10
    
    100
    
    1000
    
    10000
    
    100000
    
    1000000
    
    10000000
    
    100000000
    
    1000000000
    
    1410065408
    
    1215752192
    
    -727379968
    
    1316134912
    
    276447232
    
    -1530494976
    
    1874919424
    
    1569325056
    
    -1486618624
    
    -1981284352
    
    1661992960
    
    -559939584
    
    -1304428544
    
    -159383552
    
    -1593835520
    
    1241513984
    
    -469762048
    
    -402653184
    
    268435456
    
    -1610612736
    
    1073741824
    
    -2147483648
    
    0
    

    A fix for this may be to make the divisor an double or float instead of an integer