Reputation: 305
I have a function which decides whether a given BigInteger is a prime number or not. In the main class I made a call to that function with an argument passed. Now when I try to compile, I get the following error.
C:\Users\me\Downloads>java RSA_n_prime2_using_int
Exception in thread "main" java.lang.ArithmeticException: BigInteger: modulus not positive
at java.math.BigInteger.mod(Unknown Source)
at RSA_n_prime2_using_int.prime_check(RSA_n_prime2_using_int.java:92)
at RSA_n_prime2_using_int.main(RSA_n_prime2_using_int.java:20)
My code looks something like this
public static boolean prime_check(BigInteger val)
{
BigInteger prime_chk=new BigInteger("0");
//System.out.println("in the function");
boolean isprime=true;
BigInteger prime_value=val.add(BigInteger.ZERO);
if(val.equals(BigInteger.ZERO)||val.equals(BigInteger.ONE))
return false;
for(prime_chk.valueOf(2);prime_chk.compareTo(prime_value)<0;prime_chk.add(BigInteger.ONE))
{
if((prime_value.mod(prime_chk)).equals(BigInteger.ZERO))
{
isprime=false;
break;
}
}
return isprime;
}
In the main function, the call is made as follows
s1 = new BigInteger("1021");//s1=(int)Math.round(Math.random()*1000)%30;
if(prime_check(p1))
{
System.out.println(p1+" is prime");
}
Please help me in finding, where I have went wrong.
Upvotes: 1
Views: 913
Reputation: 881293
Having set prime_chk
to zero at the start of the function, you then do:
for (prime_chk.valueOf(2); blah; blah ) {
if((prime_value.mod(prime_chk)) {
blah;
}
}
That first part of the if
statement (prime_chk.valueOf(2)
) doesn't actually change prime_chk
, it simply evaluates the 2
and creates a big integer of that value (which you appear to then throw away). Thus, when you execute prime_value.mod(prime_chk)
, prime_chk
is still set to zero, hence your exception (some may argue the case but zero is neither negative nor positive - in any case, x mod 0
is a problematic operation regardless of the arguments raised).
Perhaps you might want to change the initial part of the if
to something like:
for (prime_chk = BigInteger.valueOf(2); blah; blah ) {
This will actually change prime_chk
to be 2
and hence avoid your exception.
One other point, you may be able to save a lot of cycles if you limit prime_chk
to between 2
and the square root of the test number. If you haven't found a divisor below that, it's mathematically guaranteed you won't find one above. The normal method would be along the lines of (pseudo-code, obviously):
def isPrime (val):
for (chk = 2; chk * chk <= val; chk++):
if (val % chk) == 0:
return false
return true
Upvotes: 1