Project Euler Problems

First time I came across a project-euler problem was at Stack Overflow. While answering an algorithm question, I found the Project Euler provides a fun way to learn new concepts and keep my problem solving and mathematics skills sharp.

Project Euler is a series of challenging mathematical/computer programming problems that will require more than just mathematical insights to solve. Although mathematics will help you arrive at elegant and efficient methods, the use of a computer and programming skills will be required to solve most problems.

So I decide to solve one problem a day and keep my solutions here. To spice things up, I want to solve each problem with two different languages. One imperative language that I am already comfortable with, such as C#, ruby, java, javascript. Another one, I would use a functional language.

Problem 1: Multiples of 3 and 5

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.

Solution 1

C#

It could be something like this

var result = 0;

for(var i =1; i < 1000; i ++) {
  if (i % 3 == 0 || 1 % 5 ==0 ) {
    result += i;
  }
}

But NO, I really don’t want to see any for-loop or while-loop here. Using C# doesn’t mean you cannot do it in a concise, declarative style. Here you go:

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

Solution 2

Lets do it in a real functional language.

F#

[1..999] |> List.filter (fun n -> (n % 5) * (n % 3) = 0 ) |> List.sum