1

I'm trying to make an application to check if a specific number is a prime. Since the number is bigger than value of int or long, I had to use BigInteger, but I've slim knowledge about it so I'm hitting the wall. What I'm doing is checking if n is dividable by odd numbers(i) until i reaches root of the n. the value of n(10^24+7) is a prime number and I want to check bigger numbers such as 10^128+7. I'd appreciate any help.

import javax.swing.*;
import java.math.*;

public class prime {
    public static void main(String[] args) {
        BigInteger n = new BigInteger("1000000000000000000000007");
        BigInteger h = new BigInteger("2");
        int r;

        for(BigInteger i = new BigInteger("3");n.compareTo(i.multiply(BigInteger.valueOf(i)))>=0;i.add(BigInteger.valueOf(h))) {
            if(n.divideAndRemainder(i)==0){
                r=0;
                }else{
                        r=1;}
        }
        if(r=0){
            System.out.println("not prime");}else{
                System.out.println("prime");}
    }       
}
Jerry Dark
  • 11
  • 1
  • I think that checking if `10^128 + 7` is prime would take you a long time using this method. It's a number with 128 zeros after a 1. By the way, what's the problem you're having? You have just described what you want to do, and not your problem. – nbro Feb 02 '16 at 03:47
  • Do _not_ trial divide; it will take forever. Instead use the `BigInteger.isProbablePrime` method. – user448810 Feb 02 '16 at 04:23

1 Answers1

1

The correct operation is BigInteger.mod(BigInteger) (you only care about the remainder); or use BigInteger.isProbablePrime(int). It's also better to extract your logic into a method. Something like,

static boolean isPrime(BigInteger n) {
    BigInteger TWO = BigInteger.ONE.add(BigInteger.ONE);
    if (n.mod(TWO).equals(BigInteger.ZERO)) {
        return false;
    }
    BigInteger h = TWO.add(BigInteger.ONE);
    // for (; h * h < n; h += 2)
    for (; h.multiply(h).compareTo(n) < 0; h = h.add(TWO)) {
        if (n.mod(h).equals(BigInteger.ZERO)) {
            return false;
        }
    }
    return true;
}
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249