Project Euler 007 – C#

15 03 2011

Problem 7

By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.

What is the 10001st prime number?

Solution

//By listing the first six prime numbers:

//2, 3, 5, 7, 11, and 13, we can see that

//the 6th prime is 13.

 

//What is the 10001st prime number?

 

 

using System.Collections.Generic;

namespace ProjectEulerCSharp_007

{

    class Program

    {

        static void Main(string[] args)

        {

            List<long> primes = new List<long>(10) { 2, 3 };

            while (primes.Count < 10001)

            {

                bool isPrime = false;

                long candidate = primes[primes.Count – 1] + 2;

                while (!isPrime)

                {

                    isPrime = true;

                    foreach (long prime in primes)

                    {

                        if (candidate % prime == 0)

                        {

                            isPrime = false;

                            break;

                        }

                    }

                    if (!isPrime) { candidate += 2; }

                    else { primes.Add(candidate); }

                }

            }

            System.Console.WriteLine(primes[primes.Count-1]);

        }

    }

}

 

Discussion

Getting back to my imperative roots, this problem was pretty easy to solve.

If you have any questions, leave a comment, find me on Twitter (@azzlsoft) or email (rich@azzlsoft.com).