Solution to Problem 1 on ProjectEuler Using Scheme


Improve your writing skills in 5 minutes a day with the Daily Writing Tips email newsletter.

The problem:

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))

One thought on “Solution to Problem 1 on ProjectEuler Using Scheme

  1. kronicmage

    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)

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *