Happy Programmer’s day!

Q7, 13.09.2013 by Ivan Inozemtsev View Comments

Congratulations to all programmers with programmer’s day!

Just for fun, I’ve decided to solve a few problems from Project Euler using ECL :)

I solved only two problems, because this idea came to mind only a hour ago, but so far I did not find obstacles to solve others. The results can be found on Github project – https://github.com/xored/q7.examples.euler.

Just one more note – because of current implementation details, which should be easy to fix, there is a limitation on stack depth in ECL calls. Since I intentionally I decided using ECL as is without introducing any new commands and altering implementation, in these tasks I reduced some requirements (i.e instead of iterating over 1000 numbers, iterating only over 100 numbers).

Let’s start.

The first problem is really trivial:

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.

All we need to do, is to iterate over numbers between 1 and 999 and take only those which are dividable on 3 or 5. So we need a ‘mod’ command, but there is no such in ECL! Let’s create a procedure instead:

proc mod [val a] [val b] {
    $a | minus [div $a $b | mult $b]
}

Here we use a simple fact that integer division ‘throws’ division module, so ‘a mod b == a – (a / b) * b’.

Now we are ready to move on. We need to iterate over numbers, but there’s no ‘for’ or ‘while’ loop. So, we need to use a recursion!

Here’s a sample, just to illustrate an idea:

proc iterate [int count] {
    if [$count | eq 0] {
        // we are done
    } -else {
        iterate [$count | minus 1]
    }
}

Now it is easy to solve the first problem (posting a screenshot, just because I’m bad in HTML code highlighting):

problem1

The second problem, count sum of even fibbonaci numbers, not exceeding some given number, can be solved in a similar way:

problem2

Thank you for reading and happy programmer’s day!

blog comments powered by Disqus

Functional and UI Testing for Eclipse-based Applications

Test automation solution, handcrafted for Eclipse. Modern and easy to learn IDE.

Product Health Analytics and Support Automation Platform

End-user and product analytics solution that gives you rich insights into your application health & performance.

Eclipse-based IDE for the Fantom Programming Language

Full-featured Integrated Development Environment for emerging Fantom programming language.