8.29.2012

Project Euler Problem 7: Find the 10001st prime number

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 10 001st prime number?
The answer is 104743.

            List listPrime = new List {3, 5, 7, 11, 13};

            bool flagPrime = true;
            int num = listPrime.ElementAt(listPrime.Count - 1);

            while (listPrime.Count < 10000)
            {                
                num = num + 2;
                flagPrime = true;
                foreach (int j in listPrime) 
                {
                    if (num % j == 0)
                    {
                        flagPrime = false;
                        break;
                    }
                }

                if (flagPrime == true)  listPrime.Add(num);
            }

            Console.WriteLine("10001st Prime number = {0}", listPrime.Last();


No comments:

Post a Comment