首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

1-n 之内的素数

2012-11-17 
1-n 以内的素数static void ListPrime(int n) {/*** false为质数,true为合数*/boolean[] primeList new

1-n 以内的素数
static void ListPrime(int n) { 
        /**
         * false为质数,true为合数
         */ 
        boolean[] primeList = new boolean[n + 1]; 
 
        for (int i = 2; i <= n; i++) { 
            if (!primeList[i]) { 
                int j = i * i; 
                if (j > n) 
                    break; 
                if (i > 2) { 
                    while (j <= n) { 
                        primeList[j] = true; 
                        j = j + i + i; 
                    } 
                } else { 
                    while (j <= n) { 
                        primeList[j] = true; 
                        j = j + i; 
                    } 
                } 
            } 
        } 
        List<Integer> ret = new ArrayList<Integer>(10000); 
        ret.add(2); 
        for (int i = 3; i <= n;) { 
            if (!primeList[i]) { 
                //System.out.print(i + " ");   
                ret.add(i); 
            } 
            i += 2; 
        } 
        System.out.println(ret.size());
    } 

热点排行