查找素数的程序

在csdn上看亡灵法师的帖子,突然找到一个好点的,如何找到素数。看了大家的讨论,参照registered等的算法,用.net写了一个。原帖连接在这里
我运行后,效果如下:
1到200,000,000,一共找到了11078933个素数,花时间20秒(PIII 1G/512M)。代码如下,哪位有兴趣,可以对它进行优化。

using System;
using System.Collections;

namespace PrimerFind
{
    
class Class1
    
{        
        
private static bool[] storedprimes;
        [STAThread]
        
static void Main(string[] args)
        
{
            System.DateTime dt1 
= DateTime.Now;
            Console.WriteLine(dt1.ToLongTimeString());

            
int MAX = Convert.ToInt32(args[0]);
            storedprimes 
= new bool[MAX];
            storedprimes[
0= false;
            storedprimes[
1= false;
            storedprimes[
2= true;
            
for(int i=3;i<MAX;i+=2)storedprimes[i] = true;
            
int counter = MAX/2-2;

            
int limit = (int)Math.Sqrt(MAX)+1;

            
for(int prime = 3; prime < limit;) 
            
{
                
// Filter non prime number.
                int product = 0;
                
for (int factor = prime; (product = factor * prime) < MAX; factor += 2
                
{
                    
if (false != storedprimes[product]) 
                    
{
                        storedprimes[product] 
= false;
                        counter
--;
                    }

                }

                
// Skip non prime number.
                do 
                
{
                    prime 
+= 2;
                }
 while (false == storedprimes[prime]);
            }


            
// TODO : 如果要输出,就把注释去掉
//            for(int i=0;i<MAX;i++)
//            {
//
//                //if(0 != storedprimes[i])Console.WriteLine(storedprimes[i]);
//            }

            System.DateTime dt2 
= DateTime.Now;
            Console.WriteLine(dt2.ToLongTimeString());
            Console.WriteLine((dt2.Ticks
-dt1.Ticks)/10000);//毫秒
            Console.WriteLine(counter-2);
        }

    }

}

posted @ 2004-08-26 11:52  鞠强  阅读(1280)  评论(2编辑  收藏  举报

hello

world