Project Euler: Problem 1
I am starting a new series. A friend recently pointed me at the Project Euler problems. You can see the project here: http://projecteuler.net/
As I finish them, I'll post an explanation of the problem and the code here. I've also posted the code on MSDN Code Gallery. As I finish a week's worth of code, I'll post a new release of source code there.
A few ground rules:
- I'm not going for the 'best' or 'most efficient' solution. I'm using this to demonstrate significant C# 3.0 features. If you have a different preferred algorithm, post it yourself. In fact, you can register at Project Euler and post your own code.
- I will post blog entries more or less at the same time I update the code. You might see the code before I discuss it. If you don't want spoilers, don't do it.
- I will discuss the algorithms and the answers freely. If you want to figure out the problems yourself, don't read too far before you try it yourself. Or, once again, signup at Project Euler and try yourself before I post my answers.
- I will do the problems in order, so if you're interested in avoiding spoilers, you can work in order, and stay ahead of where I'm at. (The first three problems took me less than 2 hours from start to finish).
Ok, with that out of the way, here's the code for the first problem. (Really, it's not that hard. I'm not giving much away here). In the first problem, you need to find the sum of all natural numbers below 1000 that are multiple of 3 and 5.
It's one (or two) lines of code in C# 3.0:
var nums = from n in
Generators.NumberSequence(0, 1000)
where ((n % 3 == 0) || (n % 5 == 0))
select n;
var answer = nums.Sum();
I should also show you the code for NumberSequence. I figure I'll need sequences of numbers fairly often in this projecxt, so I pulled that into a library:
public static IEnumerable<int> NumberSequence(int from, int to)
{
do
{
yield return from++;
} while (from < to);
}
Yes, this method assumes that from is less than to. Seems like a reasonable assumption at this time.
You can download the code for the first three problems here: http://code.msdn.microsoft.com/EulerCSharp
Note that I said 3 problems. I uploaded the code for the first three problems on Project Euler, so you may want to wait if you want to avoid spoilers.