猿问

JAVA的一道习题:找出五个大于Long.MAX_VALUE的素数

在素数判断方法isPrime处不知道该怎么写才能让程序跑出结果而不用等到天长地久...


public static void main(String[] args) {

        long startTime = System.currentTimeMillis();



        BigInteger bigNum = new BigInteger(Long.MAX_VALUE + "");


        bigNum = bigNum.add(BigInteger.ONE);


        int count = 1;

        while (count <= 5) {

            if (isPrime(bigNum)) {

                System.out.println(bigNum);

                count++;

            }


            bigNum = bigNum.add(BigInteger.ONE);

        }

        System.out.println(bigNum.toString());

        long endTime = System.currentTimeMillis();

        System.out.println("Time spent is " +

            (endTime - startTime) + " milliseconds");

    }


    public static boolean isPrime(BigInteger num) {

        

        

        return true;

    }


叮当猫咪
浏览 1148回答 1
1回答

慕桂英3389331

java的BigInteger有自带的isProbablePrime函数,把参数设置大一点,结果就几乎不会出错。public static boolean isPrime(BigInteger num) {&nbsp; &nbsp; &nbsp; &nbsp; return num.isProbablePrime(50);&nbsp; &nbsp; }
随时随地看视频慕课网APP

相关分类

Java
我要回答