Saturday, July 27, 2013

Project Euler Solved using C# : 10001st prime


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?

what you have to do is traverse and check if the number is prime. The most important concept to remember is
  • 2 is the only EVEN prime number
  • 3 onwards all prime numbers are ODD
  • a number is considered to be prime if it is Divisible by any number Less Than or Equal To SQUAREROOT of (Suspected Number).
Answer to the Problem is : 104743

 
 using System;  
 using System.Collections.Generic;  
 using System.Linq;  
 using System.Text;  
 namespace ProjectEuler  
 {  
   class PrimeAtPlace  
   {  
     public PrimeAtPlace(int place)  
     {  
       getPrimeatPlace(place);  
     }  
     private void getPrimeatPlace(int Place)
        {
            int counter = 1;
            int suspectprime = 3;
            int tempprime = 0;
            while (counter <= Place)
            {
                if (checkIfPrime(suspectprime))
                {
                    tempprime = suspectprime;
                    counter++;
                }
                suspectprime = suspectprime + 2;
            }
            Console.WriteLine("Prime at " + counter + " is " + tempprime);
        }
     }  
     private Boolean checkIfPrime(int suspectprime)
        {
            for (int j = 3; j <= Math.Sqrt(suspectprime); j = j + 2)
            {
                if (suspectprime % j == 0) { return false; }
            }
            return true;
        } 
   }  
 }  

No comments:

Post a Comment