Euler’s Problem 7 And A PrimeAt Extension Method For C#

By Anoop Madhusudanan

Vote on HN

This is one of those Back To Basics Post.

It is always interesting to work on Euler’s problems. Recently, Roman wanted to bring some fun, and asked us to implement Euler’s Problem 7 in C# in an effective way.

Euler’s problem 7 is pretty straight forward – Find the 10001st Prime Number :). So, here we go, here is a pretty minimal implementation with a bit of optimization.

public static class PrimeUtils
        /// <summary>
        /// An extension method to find the prime number at n'th position
        /// </summary>
        /// <param name="position"></param>
        /// <returns></returns>
        public static int PrimeAt(this int position) 
            var primes = new List<int>() { 2 }; var num = 1;
            while (primes.Count < position)
                bool isPrime = true; num += 2;
                foreach (int p in primes)
                    if (num % p == 0) { isPrime = false; break; }
                    if (p > (int)Math.Sqrt(num) + 1) break;
                if (isPrime) primes.Add(num); 
            return num;
And here is how you can use it.  


Read few other Back To Basics posts if you are interested

Shout it
© 2012. All Rights Reserved.