欧拉计划 第10题

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

Find the sum of all the primes below two million.

 

            int[] numbers = Enumerable.Range(1, 2000000).ToArray();

            int prime = 2;

            int nextPrime = 2;

            int nextPrimePow2 = 2 * 2;

            for (int i = 1; nextPrimePow2 < 2000000; i++)

            {

                int n = numbers[i];

                if (n == 0) continue;

                for (int j = i + 1; j < numbers.Length; j++)

                {

                    int k = numbers[j];

                    if (k % prime == 0)

                    {

                        numbers[j] = 0;

                        continue;

                    }

                    if (prime == nextPrime) nextPrime = k;

                }

                prime = nextPrime;

                nextPrimePow2 = nextPrime * nextPrime;

            }

            long primeSum = 0;

            foreach (var item in numbers)

            {

                primeSum += item;

            }

            Console.WriteLine(primeSum - 1);

 

你可能感兴趣的:(欧拉计划)