For those of you that have been following Ola Bini’s work on Ioke, the dynamic language for the JVM, I am happy to report that the current release 0.1.1 is usable enough to solve Project Euler problems with. I wanted to learn more about Ioke and the best way to learn a new language is to use it on your own. So, here is some example Ioke code for some of the simpler Project Euler problems.
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.
Brute force version below.
Or, as a one-liner after a suggestion from Ola:
Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, … Find the sum of all the even-valued terms in the sequence which do not exceed four million.
The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143?
Using brute force for this one. Faster and more elegant would have been the Rho algorithm.
2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. What is the smallest number that is evenly divisible by all of the numbers from 1 to 20?
First, as the numbers 1 to 10 are factors in the numbers 11 to 20 we only need to check divisibility for the the latter. Starting of by setting up methods for greatest common divisor and least common multiple. Brute forcing this by looping over an incremented number will not work in the current version of Ioke (takes a couple of hours). Brute forcing it in Ruby took a couple of seconds.
Find the maximum total from top to bottom of the triangle below. This solution also works for problem 67 (a much bigger triangle).
By moving from bottom to top, calculating each cell’s maximum sum and replacing the value with it we’ll end up with the total in the first cell in the triangle.