divide by zero error

David picture David · Mar 10, 2010 · Viewed 21.8k times · Source

here is the code (java):

class prime
{

    public static boolean prime (int a, int b) 
    { 
        if (a == 0) 
        {
            return false; 
        }
        else if ((a%(b-1) == 0) && (b>2))
        {
            return false; 
        }
        else if (b>1) 
        {
            return (prime (a, b-1)) ;
        }
        else
        {
            return true; 
        }

    }

    public static void main (String[] arg) 
    {
        System.out.println (prime (7, 7)) ; 
    }
}

This is the error message i get when i try to run it (it compiles fine):

Exception in thread "main" java.lang.ArithmeticException: / by zero
    at prime.prime(prime.java:10)
    at prime.prime(prime.java:16)
    at prime.prime(prime.java:16)
    at prime.prime(prime.java:16)
    at prime.prime(prime.java:16)
    at prime.prime(prime.java:16)
    at prime.prime(prime.java:16)
    at prime.main(prime.java:27)

So this means i devided by zero some how right? or does it mean something else? I don't see how i'm dividing by zero. What went wrong?

Answer

Tom picture Tom · Mar 10, 2010

Try turning this around

if ((a%(b-1) == 0) && (b>2))

to

   if ((b>2) && a%(b-1)==0)

What's happening is that the a%(b-1) operation is being executed before the b>2 test.

After the switch, you are taking advantage of short-circuit evaluation. Once the b>2 test returns false, then there's no need to calculate the modulus (hence avoiding the division)