Project Euler - Problem 001

The first problem is really easy to solve, especially with LINQ extension methods.

For starters, I decided to use the BigInteger class from System.Numerics. And since the each problem build on previous problems, I should wind up with a lot of reusable code.

            private static BigInteger SumOfNaturalsLessThan1000()
            {
                return BigInteger.One.To(1000)
                                 .Where(IsDivisibleByThreeOrFive)
                                 .Sum();
            }
            
            private static bool IsDivisibleByThreeOrFive(BigInteger number)
            {
                return number.IsEvenlyDivisible(3) || number.IsEvenlyDivisible(5);
            }
          

So already we have three methods that need a definition: To, IsEvenlyDivisible, and Sum.

The To method will be a simple iterator extension method. The IsEvenlyDivisible method is another extension method that can be easily implemented using modulus or with the BigInteger.Remainder method. And Sum extension method will use LINQ aggregation to do the summation.

            public static IEnumerable<BigInteger> To(
                this BigInteger start, 
                BigInteger end)
            {
                for (BigInteger x = start; x <= end; x++)
                {
                    yield return x;
                }

                yield break;
            }

            public static bool IsEvenlyDivisible(
                this BigInteger dividend, 
                BigInteger divisor)
            {
                BigInteger remainder = BigInteger.Remainder(dividend, divisor);
                return remainder.IsZero;
            }

            public static BigInteger Sum(this IEnumerable<BigInteger> source)
            {
                if (source == null)
                {
                    throw new ArgumentNullException("source");
                }

                return source.Aggregate(BigInteger.Zero, BigInteger.Add);
            }
          


Tags

  • .NET
  • Project Euler

Revisions

  • 1/23/2012 - Article published.