Project Euler Problem 1
The idea here is to solve Problem 1 without using a modulus operator which I take to be more expensive than using addition and if. So it adds every multiple of 5 except every third multiple, e.g., 5 + 10 + skip + 20 + 25 + skip.
(defun problem1 ()
(+
(loop for i from 3 below 1000 by 3 sum i)
(loop for j from 5 below 1000 by 5
and k = 1 then (if (= k 3) 1 (1+ k))
unless (= k 3) sum j)))
There's a more efficient way to solve this without using a loop, but I didn't know about it until after I solved this, so at this point, for me, I consider it cheating.
Another solution avoiding a modulus operator but probably not any more efficient:
(defun problem1 ()
(reduce #'+
(union (loop for i below 1000 by 3 collect i)
(loop for i below 1000 by 5 collect i))))
No comments:
Post a Comment