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?
IFERROR is the simplest solution. For example if your formula was =A1/A2 you would enter =IFERROR(A1/A2,“”) to return a blank or =IFERROR(A1/A2,0) to return a zero in place of the error.
The short answer is that 0 has no multiplicative inverse, and any attempt to define a real number as the multiplicative inverse of 0 would result in the contradiction 0 = 1.
Definition of divide (Entry 1 of 2) transitive verb. 1a : to separate into two or more parts, areas, or groups divide the city into wards. b : to separate into classes, categories, or divisions divide history into epochs. c : cleave, part a ship dividing the waves.
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)
Because of your recursive call:
return (prime (a, b-1)) ;
You will at some point be calling prime with a value for b of 1. Which means on your second condition you will be testing a%0
. Since the modulo operator (%) is essentially a divide, that is bringing your divide by zero issue.
The solution is probably to catch this case to enforce b > 2 in your condition before doing the %.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With