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.
The solution in Scheme:
(define (remainder x y) (- x (* y (truncate (/ x y)))))
;x is start value, y is limit
(define (main x y) (
if (< x y)
(cond ((= (remainder x 3) 0)
(+ x (main (+ x 1) y)))
((= (remainder x 5) 0)
(+ x (main (+ x 1) y)))
(else (main (+ x 1) y)))
0))
(display (main 1 1000))
This could be a lot better if we use the functional programming paradigms that Scheme is so good at:
(also, scheme (well at least DrRacket) has a modulo function, you don’t need to define one yourself)
(define (euler1 n) (foldl + 0 (filter (λ (x) (or (= (modulo x 3) 0) (= (modulo x 5) 0))) (cdr (build-list n values)))))
(euler1 1000)