Monday, January 27, 2014

Project Euler Solution using C#: Problem 7: 10001st Prime

Problem:

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?
My Solution:

static void Main(string[] args)
{
    bool isFound = false;
    bool isPrime = false;
    int limit = 10001;
    int count = 0;
    int val = 1;
    while (isFound == false)
    {
        if (val == 2)
        {
            count++;
        }
        else
        {
            for (int i = 2; i < val; i++)
            {
                if (val % i != 0 && val != i)
                {
                    isPrime = true;
                }
                else
                {
                    isPrime = false;
                    break;
                }
            }
            if (isPrime)
            {
                count++;
                if (count == limit)
                {
                    Console.WriteLine("The" + limit + " th prime number is : " + val);
                }
            }
        }
        val++;
    }
    Console.ReadLine();
}
Note: You can simplifies the coding :)

No comments:

Post a Comment