使用筛法打印质数

public static void main(String[] args) {
        
        //范围:2到多少
        int maxfanwei = 20;
        
        boolean[] bolist = new boolean[maxfanwei+1];
        
        for (int i = 2; i < bolist.length; i++) {
            boolean isnotsushu = bolist[i];//不是素数true,是素数false
            if(!isnotsushu){
                int xiabiao = i;
                //这个数的倍数设置为true
                while (true) {
                    xiabiao+=i;
                    if (xiabiao>=(maxfanwei+1)) {
                        break;//超过范围退出设置
                    }
                    bolist[xiabiao] = true;
                }
            }
            
        }
        //打印质数
        for (int i = 2; i < bolist.length; i++) {
            if (!bolist[i]) {
                System.out.println(i+"    ");
            }
            
        }
        
        
    }

猜你喜欢

转载自www.cnblogs.com/RivenLw/p/10008939.html