Saturday, May 10, 2014

Project Euler - Problem 1 in C#

Multiples of 3 and 5

Problem 1

If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.

Here is my solution

For this problem, either we can create list of int or array of int values up to 1000 like this

// generate the list of numbers from lower bound to upper down
private static IList<int> GenerateNumberList(int upperBound, int lowerBound = 0)
{
 var numberList = new List<int>();

 for (var i = lowerBound; i < upperBound; i++)
 {
  numberList.Add(i);
 }

 return numberList;
}

// generate the array of numbers from lower bound to upper down
private static int[] GenerateNumberArray(int upperBound, int lowerBound = 0)
{
 var arrLength = upperBound - lowerBound;

 var numberArr = new int[arrLength];

 for (var i = 0; i < arrLength; i++)
 {
  numberArr[i] = lowerBound + i;
 }

 return numberArr;
}


Using LINQ for the declarative approach to find the sum of all the numbers either divisible by 3 or 5

// OPTION 1
stopwatch.Start();

var listSum = GenerateNumberList(1000)
   .Where(x => x % 3 == 0 || x % 5 == 0)
   .Sum();

stopwatch.Stop();

Console.WriteLine (listSum);

// OPTION 2
stopwatch.Reset ();
stopwatch.Start ();

var arrSum = GenerateNumberArray (1000)
   .Where (x => x % 3 == 0 || x % 5 == 0)
   .Sum ();

stopwatch.Stop();

Console.WriteLine (arrSum);


With imperative way of programming without using LINQ, we can run the for loop from 0 to 1000 and keep adding all number which meet the criteria.

// OPTION 3
stopwatch.Reset ();
stopwatch.Start ();

var sum = 0;

for(var i = 0; i < 1000000; i++) {
 if (i % 3 == 0 || i % 5 == 0) {
  sum += i;
 }
}

stopwatch.Stop ();

Console.WriteLine (sum);


Click here to next problem

Have fun solving problems ...

No comments:

Post a Comment