Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/355.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java euler 7项目-我完全被卡住了,无法理解_Java - Fatal编程技术网

Java euler 7项目-我完全被卡住了,无法理解

Java euler 7项目-我完全被卡住了,无法理解,java,Java,我已经修改了这个代码好几个小时了,我就是不能让它输出正确的答案。谁能告诉我哪里出了问题?此版本正在输出104033 package Euler; public class prime100001 { private static boolean isPrime(long num) { if (num == 2 || num == 3){ return true; } if (num % 2 == 0){

我已经修改了这个代码好几个小时了,我就是不能让它输出正确的答案。谁能告诉我哪里出了问题?此版本正在输出104033

package Euler;

public class prime100001 {

    private static boolean isPrime(long num) {
        if (num == 2 || num == 3){
           return true;
        }
        if (num % 2 == 0){ 
            return false;
        }
        for (int i = 3; i * i < num; i += 2){
            if (num % i == 0){ 
                return false;
            }
        }
        return true;
    }

    public static void main (String [] args){

        int counter = 0;
        int primenum = 1;

        while(counter < 10001){
            primenum += 2;
            if(isPrime(primenum)){
                counter ++;
            }
        }
        System.out.println(primenum);
    }

}

只是想确定一下,你想打印第10001个素数吗

public class prime100001 {
    private static boolean isPrime(long num) {
        if (num == 2 || num == 3){
            return true;
        }
        if (num % 2 == 0){
            return false;
        }
        for (int i = 3; (i * i) <= num; i += 1){
            // Changed the condition from < to <=, as you need to capture squares 
            // (e.g. when num = 9, original method will return false as i * i = 9 < 9 is false.
            // Also changed the increment from 2 to 1.
            if (num % i == 0){
                return false;
            }
        }
        return true;
    }

    public static void main(String [] args){

        int counter = 0;

        int lastPrime = 1;
        while(counter < 10001){
            lastPrime += 1;
            // Changed increment to include 2 in the count, plus
            // not skipping any other ints to test.
            if (isPrime(lastPrime)){
                counter++;
            }
        }
        System.out.println(lastPrime);
        // Shows 104,743
        // 10,000th prime: https://primes.utm.edu/lists/small/10000.txt
    }
}

希望这有帮助

你跳过了2,这是第一个素数。另外,快速搜索也会得出这样的结论:也许这里的提示也能帮助你:我在问问题之前看过那篇帖子,但它并没有帮我解决问题。我正在寻找一个具体的解释,解释为什么我的代码没有达到我期望的效果。在我发布问题之前,我重写了6次,为什么在for循环中将增量改为1?你不需要检查偶数的素数。除此之外,还有很好的编辑。谢谢你的帮助