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:

  1. static void Main(string[] args)
  2. {
  3.     bool isFound = false;
  4.     bool isPrime = false;
  5.     int limit = 10001;
  6.     int count = 0;
  7.     int val = 1;
  8.     while (isFound == false)
  9.     {
  10.         if (val == 2)
  11.         {
  12.             count++;
  13.         }
  14.         else
  15.         {
  16.             for (int i = 2; i < val; i++)
  17.             {
  18.                 if (val % i != 0 && val != i)
  19.                 {
  20.                     isPrime = true;
  21.                 }
  22.                 else
  23.                 {
  24.                     isPrime = false;
  25.                     break;
  26.                 }
  27.             }
  28.             if (isPrime)
  29.             {
  30.                 count++;
  31.                 if (count == limit)
  32.                 {
  33.                     Console.WriteLine("The" + limit + " th prime number is : " + val);
  34.                 }
  35.             }
  36.         }
  37.         val++;
  38.     }
  39.     Console.ReadLine();
  40. }
Note: You can simplifies the coding :)

No comments:

Post a Comment