Project Euler is an ongoing series of math/programming problems. I’m going to try to go through as many of these as I can this year, post the code for them, and talk about anything interesting that I learn in the process.
You can follow my progress by checking out a CodePlex repository for Project Euler that I’ve set up. If you have a Project Euler account, you should be able to see my progress on the mgroves Project Euler profile page.
The first problem was pretty easy: “Find the sum of all the multiples of 3 or 5 below 1000.” To do this, I just loop through each number from 3 to 999, and take the modulus 3 and 5 of that number. If either modulus is 0, add it to a list. When done, sum up the list:
for (int i = 3; i < x; i++)
{
if (((i%3) == 0) || ((i%5 == 0)))
{
list.Add(i);
}
}
The second problem is slightly more difficult: Find the sum of all even numbers in the Fibbonaci sequence which do not exceed 4,000,000. My code takes a straightforward approach; I'm sure the math majors out there can think of a better way:
public static IList FibonacciAllEvenValueTermsLessThan(int x)
{
var list = new List();
int term1 = 1;
int term2 = 2;
list.Add(term2);
while(term2 < x)
{
var newterm1 = term2;
var newterm2 = term1 + term2;
if((newterm2 % 2) == 0)
{
list.Add(newterm2);
}
term1 = newterm1;
term2 = newterm2;
}
return list;
}
For both problems, I take the result and use the Linq Sum() extension method, because I'm a total Linq junky these days. I also started out using longs instead of ints, before I realized that, hey, 32-bit numbers go up to around 4 billion (232), not 4 million.
Fun stuff. I’ve been fooling around with Python (thanks to XBMC), and decided to take a crack at these with it. I did 1 and 2, then 54 since it sounded fun. I’ll probably work at some more later, though I doubt I’ll bother doing them in order.
54 does look like a lot of fun, but I think I’ll go in numerical order, and build up an arsenal of helper methods as I need them.