I'm doing Project Euler to learn Clojure.
The purpose of this function is to calculate the lcm of the set of integers from 1
to m
.
(lcm 10)
returns 2520
This is a rather brute-force way of doing this. In theory, we go through each number from m
to infinity and return the first number for which all values 1
through m
divide that number evenly.
If I understand what 'lazy' means correctly (and if I am truly being lazy here), then this should run in constant space. There's no need to hold more than the list of numbers from 1
to m
and 1 value from the infinite set of numbers that we're looping through.
I am, however, getting a java.lang.OutOfMemoryError: Java heap space
at m
values greater than 17.
(defn lcm [m]
(let [xs (range 1 (+ m 1))]
(first (for [x (iterate inc m) :when
(empty?
(filter (fn [y] (not (factor-of? y x))) xs))] x))))
Thanks!