I did complete Problem 4 already, but the write up will take a bit of time. So I went ahead and did Problem 5, in a very quick and dirty way.
Problem 5 – “What is the smallest number that is evenly divisible by all of the numbers from 1 to 20?”
The total elapsed time from reading the problem to having the answer was less than 10 minutes. The first instinct is to just brute force the thing, and that’s what I did.
I did make some small optimizations, things that occurred to me in the couple of minutes I spent thinking about it.
1 – There’s no point in testing divisibility by numbers 1-10, since anything that’s divisible by 11-20 will of necessity by divisible by 1-10. (ie each of the numbers 1-10 are factors of at least one of the numbers 11-20).
2- There’s no point in testing divisibility by 20, since we’re starting with 20 and incrementing by 20. All candidates will be divisible by 20.
I have no doubt that this can be optimized considerably. It takes 22 seconds to complete on my netbook, an eternity! But this code makes me laugh, so here it is.
Called by euler5:lowest(20).
Brutish code -
-module(euler5).
-export([lowest/1]).
lowest(N) ->
if
N rem 19 == 0,
N rem 18 == 0,
N rem 17 == 0,
N rem 16 == 0,
N rem 15 == 0,
N rem 14 == 0,
N rem 13 == 0,
N rem 12 == 0,
N rem 11 == 0 ->
N;
true ->
lowest(N+20)
end.

Post a Comment