尔冬橙

博客园 首页 新随笔 联系 订阅 管理

The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.

Find the sum of all the primes below two million.

        static void Main(string[] args)
        {
            long startTime, endTime;
            startTime = DateTime.Now.Ticks;
            bool[] p = new bool[2000000];
            Int64 a, t, max,sum = 0;
            max = 2000000;
            for (a = 0; a < max; a++)
            {
                p[a] = false;
            }
            p[2] = true;
            for (a = 3; a < max; a += 2)
            {
                p[a] = true;
            }
            t=3;
            do
            {
                for (a = 3 * t; a < max; a += 2 * t)
                {
                    p[a] = false;
                }
                t = t + 2;
            }while(t<max);
            t = 1;
            a = 1;
            sum = 2;
            for (a = 3; a < max; a+=2)
            {
                if (p[a] == true) sum += a;
            }
            endTime = DateTime.Now.Ticks;
            Console.WriteLine("Result:{0} runtime:{1}ms",sum,(endTime-startTime)/10000.0);
            Console.ReadLine();
        }

 

posted on 2012-05-15 21:49  尔冬橙  阅读(347)  评论(0编辑  收藏  举报