简体   繁体   English

Java的第一个10000素数错误

[英]java first 10000 prime numbers error

I have a method that is supposed to display all the prime numbers 0-10000 recursively, but if I try to make it print the 10000th prime number a stack overflow exception is thrown. 我有一种方法应该以递归方式显示所有素数0-10000 ,但是如果我尝试使其显示第0-10000素数,则会引发堆栈溢出异常。

public void One(int i) {
    int n;
    if(i<10000){
        One(i+1);
    }
    for(n=2;n<i;n++) {
        if(i%n==0){
            break; 
        }
    }
    if(i==n){
        System.out.print(i+","); 
    }
}

What am I doing wrong here? 我在这里做错了什么?

You can change your if statement where it says 您可以在以下位置更改if语句

if(i < 10000){...}

to: 至:

if(i < 10001){...}

or: 要么:

if(i <= 10000){...}

I fixed it all i had to do was switch 我解决了所有要做的就是切换

if(i<10000){
One(i+1);
}

to the bottom instead of being in the top. 而不是放在顶部

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

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