In trying to learn Clojure and wrap my head around good functional programming, and hoping to learn more idiomatic Clojure, I have started working through the Project Euler problems. In doing this, I have also setup a repository on github.com to keep track of my progress, which can be found at https://github.com/stevenproctor/project-euler-clojure. My approach to Problem 4 can be found here.
Problem 5 of Project Euler is described as:
What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
In reading this problem I realized that this is just another way to state:
Find the Least Common Multiple of all of the numbers between 1 and 20.
The solution I came up with is:
(ns project-euler.core (:require [clojure.string :as string] clojure.math.numeric-tower)) (defn problem5 ([] (problem5 20)) ([n] (reduce lcm 1 (range 2 (inc n)))))
I found that previous to Clojure 1.2 there was a math library in Clojure-Contrib, which after 1.2 is now been moved to clojure.math.numeric-tower, so that now gets included in the vector of libraries in the :require of the ns function.
Once I had this, it was now just as simple as calling the reduce function with the function lcm, feeding it a initialization value of 1 to the reduce function and having that operate on the range of numbers from 2 to the number bound to the var n, which when called without parameters will use the value of twenty as specified in the problem definition. By defining the different arities for the function problem5, it allowed me to call the function with different numbers to the results of the function, as the full description gave the solution for the numbers in the range of 1 through 10.
Again, I would love comments and suggestions on my solution to this problem, and if there are tweaks to make it more Clojure-ish.
**Update**
My solution to Problem 6 has been posted here.
–Proctor