# Modulus with BigIntegers

• March 24th, 2012, 07:30 PM
JDreben
Modulus with BigIntegers
Hey, so I'm trying to make a method that checks if a BigInteger is prime, but I'm running into an issue in doing the modulus. Below is the whole method.

public static boolean isPrimeItself(BigInteger input)
{
BigInteger zero = new BigInteger(""+0+"");
for(int i=2;i<100/*I wasn't sure what to make this because I want it to be input but input is a BigInt...*/;i++) {
BigInteger temp = new BigInteger(""+i+"");
System.out.println(temp);
if (temp.remainder(input)==zero)
{
System.out.println("Success!");
}
}
}

I included the print lines to see where it was going wrong, and the if test [if (temp.remainder(input)==zero)] is never being activated. Did I make a mistake in using the remainder method? Upon researching I know there seems to be a premade method that does this, but I'm really just trying to practice using BigIntegers. Thanks for any comments / help you can provide!
• March 24th, 2012, 08:12 PM
JDreben
Re: Modulus with BigIntegers
Got it! Silly mistake. I should have used compareTo instead of ==. My current issue is that I need to use BigIntegers in the conditions of the for loop, is that not allowed? Because my method seems to get stuck in a loop when I try it.
• March 24th, 2012, 10:00 PM
helloworld922
Re: Modulus with BigIntegers
You'll have to convert everything to a BigInteger, then use the compareTo method.

Code java:

`for(BigInteger i = new BigInteger("2"); i.compareTo(input) < 0; i = i.add(BigInteger.ONE))`

However, I would strongly advise against writing a naive primality test for BigInteger numbers. There are much faster statistical methods for checking if a number is prime.

One of these is built into the BigInteger class: isProbablyPrime.

There is also another method I implemented here. This uses a "better" method for checking if a number is prime for twice the statistical accuracy. This is because this test always reports composite numbers as composite and prime numbers as probably prime, but the built-in method reports both probably prime and probably composite.