0

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"); } } } 
2
  • 2
    You do realise that there's a limit on how big a double can be, right? Commented Jun 28, 2015 at 6:40
  • 1
    The whole point is to see whether t / num is whole or not. This method will fall over completely if t is an integral type - not just for very large numbers. Commented Jun 28, 2015 at 6:43

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

meaning? any suggestions for a fix ?
1
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); } 

1 Comment

this will work, but i want to use the factorial method!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.