简体   繁体   English

素数检查器Java

[英]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. 我想使用以下方法检查数字是否为质数:对于数字P,请使用p-1的阶乘,然后将1加到结果中。 Finally divid the result by p. 最后将结果除以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. 无论如何,我的代码可以处理的最大质数为167,但是对于任何大于167的数字,我都会遇到NaN错误。

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! 166! is a large number. 是大量的。 The largest double is 1.7976931348623157E308 . 最大的两倍是1.7976931348623157E308 170! 170! is 7.257415615307994E306 . 7.257415615307994E306

You could use BigInteger instead. 您可以改用BigInteger。

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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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