简体   繁体   中英

prime number checker java

I'm wrote a program to check if a number is a prime. I wanted to use the following method for checking to see if a number is prime: for number P take the factorial of p-1 then add 1 to your result. Finally divid the result by p. for dose of you that don't know, if the result is a whole number then its a prime.

anyways my code works up to prime number 167 but the gives me an NaN error for any number greater than 167.

can any body spot whats wrong?

import java.util.Scanner;

public class work {
    public static void main(String arg[]) {
        System.out.println("Please enter a number to check if its a prime");
        Scanner in = new Scanner( System.in );
        int num = in.nextInt();
        double t = 1;
        for (int i=1; i<num; i++){
            t = i * t;
        }
        t = t+1;
        t = t / num;
        System.out.println(t%1);

        if ((t%1 ==0.0) && (t!= 2)){
            System.out.println("it is prime");

        }
         else{
            System.out.println("it is not a prime");

        }
    }
}

Well, there a limit to the numbers that a double variable can hold. 166! is a large number. The largest double is 1.7976931348623157E308 . 170! is 7.257415615307994E306 .

You could use BigInteger instead.

static boolean isPrime(long n) {
    BigInteger num = BigInteger.valueOf(n);
    BigInteger t = BigInteger.ONE;
    for (BigInteger i = BigInteger.ONE; i.compareTo(num) < 0; i = i.add(BigInteger.ONE))
        t = t.multiply(i);
    t = t.add(BigInteger.ONE);
    return t.mod(num).equals(BigInteger.ZERO);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM