Sunday, May 8, 2011

Project Euler - Problem 7

Welcome to week 7 of Project Euler.

Problem 7:
Find the 10001st prime.

Details:
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?


Code:
// Find the 10001st prime.
class Problem0007
{
static void Main(string[] args)
{
List primes = new List();
int number = 2;
while (primes.Count() != 10001)
{
bool isPrime = true;
for (var j = 2; j < number; j++)
{
if (number % j == 0)
{
isPrime = false;
break;
}
}
if (isPrime)
{
primes.Add(number);
primes.Sort();
}
number++;
}
primes.Sort();
Console.WriteLine(primes.Last());
Console.ReadLine();
}
}



Solution:
This one is pretty similar to Problem 3 except that instead of making a list of primes of a certain number, we are making a list of primes until the list has a certain number of entries. That, however, is pretty much where the differences end.  I start off my search for primes with the number two (one is not technically a prime number) and go from there. I have a list that is collecting all the primes that are found along the journey.  As soon as a number is found to not be prime, I break out of that iteration of the loop and try again with the next number.  A bool helps me keep track of whether or not it is actually a prime and at the end, if it is, then I add it to my list.  At the end all that needs to be done is sort the list and display the last one.  Done!

Up next week will be problem 8 which is another brute force solution.  The next prime number problem (number 10 I believe), however, is shaping up to be pretty interesting. Until then...

Enjoy!

0 comments:

Post a Comment