Euler Problem 7
Yes, it's true that I've been very lax in working on these problems. It's been a combination of the day job, finishing all the editing tasks on "More Effective C#", and actually trying to keep the personal life intact.
The 7th problem is quite straightforward: find the 10,001st prime number. The main program is just two lines:
1: static void Main(string[] args)
2: { 3: var numbers = Common.Primes.GeneratePrimes().Skip(10000).First();
4:
5: Console.WriteLine(numbers);
6: }
Simple LINQ stuff. The Skip() method skips the first N elements, and First() escapes the query and returns the first element.
Of course, the meat of the method is the GeneratePrimes() method:
1: private static List<int> knownPrimes = new List<int>();
2:
3: private static bool IsPrime(this int number)
4: { 5: bool isPrime = knownPrimes.TrueForAll(n => number % n != 0);
6: if (isPrime)
7: knownPrimes.Add(number);
8: return isPrime;
9: }
10:
11: public static IEnumerable<int> GeneratePrimes()
12: { 13: var range = Enumerable.Range(2, int.MaxValue-1);
14: var answers = from number in range
15: where number.IsPrime()
16: select number;
17:
18: return answers;
19: }
GeneratePrimes() returns the sequence of primes. It uses the IsPrime() method to determine if a number is prime. IsPrime() shows a couple of assumptions I've made to make this a reasonably simple method. First of all, it assumes that all primes up to the number being examine have been found. Therefore, if the number has no prime factors smaller than itself, it must be a prime number. That saves quite a bit of work, because the set of primes smaller than N is much smaller than the set of numbers less than N.
To make this work, note that when a prime is found, it is added to the list of known primes.