繁体   English   中英

我的程序应计算素数,但在第一个数之后停止

[英]My program should calculate prime numbers, but stops after the first number

因此,我编写了这个小程序,该程序应该检查数字是否为质数,如果是这种情况,应将其添加到arraylist中。 问题在于它只将数字3加起来然后停止。 有人可以解释一下为什么会这样吗?

import java.util.ArrayList;
public class main{
    public static void main(String args[]){
        ArrayList Primzahlen=new ArrayList();
        int current=1;
        boolean prim=true;
        for(int a=0;a<100;a++){
            for(int b=2;b<current;b++){
                if(current%b==0){
                    prim=false;
                }
                if(b==current-1){
                    if(prim==true){
                        Primzahlen.add(current);
                    }
                }
            }
            current++;
        }
        System.out.println(Primzahlen);
    }
}

检查完当前值后,需要将prim重置为true。

public static void main(String args[]){
        ArrayList Primzahlen=new ArrayList();
        int current=1;
        boolean prim=true;
        Primzahlen.add(2);
        for(int a=3;a<100;a++){
            for(int b=2;b<current;b++){
                if(current%b==0){
                    prim=false;
                }
                if(b==current-1){
                    if(prim==true){
                        Primzahlen.add(current);
                    }
                }
            }
            prim=true;
            current++;
        }
        System.out.println(Primzahlen);
    }

注意当前++附近的prim = true

暂无
暂无

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

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