Project Euler and functional C#

I think I already talked (a long time ago) about Project Euler: a set of problems, mainly math oriented, keen to be solved with a computer program. To be sure, it's not particularly deep math, but the problems posed go fairly quickly from really easy, to hmm, to challenging. In this sense, they are good programming calisthenics, and may also be a good way of learning a new language. For example, Chris Smith has solved some Project Euler problems using F#, I find the idea intriguing, so I'll try to do the same thing, only that I'll be using C#, but not your plain old C# mind you, as I'll do my best to use in as much as possible the functional facilities of C# 3.0. Let's see for example Problem 1:

Add all the natural numbers below one thousand that are multiples of 3 or 5.

Ok, ok, the problem is silly trivial, but wait until you get to Problem 10 ;-). One C# 3.0 functional solution is:

    Enumerable.Range(1, 999).Where(n => n % 3 == 0 || n % 5 == 0).Sum()

Range() generates the sequence from 1 to 999, and then Where() filters it leaving just the numbers multiples of 3 or 5, finally Sum() adds up these numbers. Easy, isn't it? And without loops or ifs.

Obviously, not all problems lend so naturally to be solved in a functional way, and we'll find out step by step how useful is the functional paradigm in Project Euler.

2 Comments

  • I am a programmer from India.

  • I disected the method, however it is not entirely as I had expected. In your example depicted above I tried the following:
    Enumerable.Range(12, 12).Where(n => n % 3 == 0 || n % 5 == 0).Sum()
    Where I would expect it to return 12 it returns 66.
    So it does not seem to be associative as I expected a range method to be. Hence I do not fully understand what the range function returns. When I start at 1 it always seems to work:
    Enumerable.Range(1, 3).Where(n => n % 3 == 0 || n % 5 == 0).Sum() returns 3 and Enumerable.Range(1, 5).Where(n => n % 3 == 0 || n % 5 == 0).Sum() returns 8 etc. When I start at some other value I cannot use the principle in similar situations, where i think functional use of ranges is excellent in combination with lambdas...

Comments have been disabled for this content.