欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > 文章正文

《Core Java》里给出的算法,效率比较高。 统计2000000以内的所有的素数。,,import java.

来源: javaer 分享于  点击 38523 次 点评:218

《Core Java》里给出的算法,效率比较高。 统计2000000以内的所有的素数。,,import java.


import java.util.*;/**     This program runs the Sieve of Erathostenes benchmark.    It computes all primes up to 2,000,000. */public class Sieve{     public static void main(String[] s)   {        int n = 2000000;      long start = System.currentTimeMillis();      BitSet b = new BitSet(n + 1);      int count = 0;      int i;      for (i = 2; i <= n; i++)         b.set(i);      i = 2;      while (i * i <= n)      {           if (b.get(i))         {              count++;            int k = 2 * i;            while (k <= n)            {                 b.clear(k);               k += i;            }         }         i++;      }      while (i <= n)      {           if (b.get(i))            count++;         i++;      }      long end =  System.currentTimeMillis();      System.out.println(count + " primes");      System.out.println((end - start) + " milliseconds");   }}//该片段来自于http://byrx.net
相关栏目:

用户点评