Hi all,

I'm checking for primality in BigInteger type.

I'm using isProbablePrime with certainty 15. I would like to know how to test if a BigInteger is really a prime number.

Thanks in advance.

Recommended Answers

All 4 Replies

import java.math.BigInteger;

public class BigIntegerisProbablePrime {

	public static void main(String[] args) {
		BigInteger num1 = new BigInteger("3511");
		isPrime(num1);
		
		BigInteger num2 = new BigInteger("3512");
		isPrime(num2);
	}

	static void isPrime(BigInteger bi) {
		if (bi.isProbablePrime(15)) {
			System.out.println(bi.toString() + " is a prime number");
		}
		else
		{
			System.out.println(bi.toString() + " is not a prime number");
		}
	}

}

output

3511 is a prime number
3512 is not a prime number

hope this helps

don't just hand out code. checking whether or not a number is a prime number is very easy, and there are tons of threads about this already, not to mention the milions of examples online.

giving him the code when he's not even doing the effort to try, or even to google for it, won't teach him to improve his development skills.

Hi, Thanks, it helps but, I was thinking of doing one more test to be sure it is a prime number. I've tried a Fermat's test:

while (!(BigInteger.ONE.compareTo(b) <= 0 && b.compareTo(n) < 0))
		        {
		            b = new BigInteger (n.bitLength(), rand);
		        
		        	
		        }
			
			
 BigInteger expResult  =b.modPow(n.subtract(BigInteger.ONE), n);
		     
		     if (!expResult.equals(BigInteger.ONE))
		         return false;
		

		 return true;

However, for example if I test number 10 when I get a random b with the value '1' I always get this 'expResult.equals(BigInteger.ONE)' as true considering it as not composite and possible prime.

So i'm not understanding why the base range in Fermat's test includes [1,n-1].

am I doing anything wrong? (1^9)%10 = 1...

don't just hand out code. checking whether or not a number is a prime number is very easy, and there are tons of threads about this already, not to mention the milions of examples online.

giving him the code when he's not even doing the effort to try, or even to google for it, won't teach him to improve his development skills.

Sorry to disappoint you but that's not the case :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.