Thursday, May 10, 2007

Project Euler

At work we are always discussing programming languages. Grant Challenged James to write some Haskell code and somehow they got to talking about Project Euler problem one. You can see in James' post more information on how he solved the problem. I will add Dan's, Geoff's, and Grant's answers once they post them.

Since his solution was one line, I decided that he is just like the old Perl hackers of the 90's. :) Just kidding James.

Anyways I decide to make my example complex. Overkill is never good, but hey I was on a roll. First I created a console application. In the solution I created a class called Calculator. This class had a public method that took two int types and a List. The first was a lower limit and the second was the top limit. It also took a List which are the multiples the user wants to sum for. This method then did the work and returned the sum of multiples.

Here is what the total class looks like....
using System.Collections.Generic;

namespace ProjectEuler
{
class Calculator
{
private int lower;
private int upper;
private List multiples;

///
/// This method will calculate the sum of multiples below the toplimit, but starting at the lower limit.
///

/// the starting number
/// the top limit
/// the multiples to sum
/// the sum of multiples
public double GetMultiplesSum(int lowerLimit, int topLimit, List passedMultiples)
{
lower = lowerLimit;
upper = topLimit;
multiples = passedMultiples;
return CalculateMultiples();
}

private double CalculateMultiples()
{
int curNumber;
double sum = 0;
for (curNumber = lower; curNumber <>
{
if (IsMultipleOfList(multiples, curNumber))
{
sum += curNumber;
}
}
return sum;
}

private bool IsMultipleOfList(List multiples, int currentNumber)
{
foreach (int multiple in multiples)
{
if (currentNumber % multiple == 0)
return true;
}
return false;
}

}
}

The console app then just created a calculator and then called the GetMultipleSum method. the app then displays the answer.

Here is that code....

using System;
using System.Collections.Generic;

namespace Projec
tEuler
{
class Program
{
static void Main(string[] args)
{
double sum = RunCalculation();

Console.WriteLine("sum = " + sum.ToString());
Console.WriteLine("Please hit a key");
Console.Read();

}

private static double RunCalculation()
{
Calculator calc = new Calculator();
List multiples = new List();
multiples.Add(3);
multiples.Add(5);
return calc.GetMultiplesSum(0,1000, multiples);
}

}
}


I could take this the next step and add a gui or ask the user to add multiples and ranges, but I really don't have the time.

No comments: