简体   繁体   中英

Sum of Multiples in Scheme

so I am very new to Scheme and functional programming as a whole. I am trying to write a program that finds the sum of all the multiples of 3 or 5 below 1000. This is my attempt so far :

(define (sum-of-multiples n)
; Start = 0, End = n, Sum = 0.
(get-sum 0 n 0)
)

; A recursive loop that starts at 0 and ends with given n (1000).
(define (get-sum start end sum)
   (cond
   ; Stopping case.
   ((= start end) sum)
   ; If start counter is divisible by 3, add to sum.
   ((= (remainder start 3) 0) (get-sum (+ start 1) end (+ start sum)))
   ; If start counter is divisible by 5, add to sum.
   ((= (remainder start 5) 0) (get-sum (+ start 1) end (+ start sum)))
   ; Otherwise just increment start counter.
   (get-sum (+ start 1) end sum))
)

(display (sum-of-multiples 1000))
(display " ")

I am not sure if the thing wrong with my code at the moment is because of Scheme syntax issues or my attempt at recursion to solve the problem. As I am not great at either of those things.

When I run this code I just get '0' displayed.

Any help with finding and fixing my errors would be great.

Thanks!

You left out the else on the "all other cases" case; it should be

(else (get-sum (+ start 1) end sum))

An attempt at explaining where you got 0 from:

A cond clause has the form (condition expression) , so your condition is get-sum .
Just like else , this condition is never false.

There is also an implicit begin after the condition, so what you have is equivalent to

(else (begin (+ start 1) end sum))

And the result of that is the value of the last expression in the begin block, which is sum .

Since sum is 0 when you reach that condition for the first time, the result is 0.

cond format is:

(cond (<condition> <expr>)
       .
       .
      (else <expr>))

In your code there is no else . get-sum function (with some reformatting) should be:

(define (get-sum start end sum)
   (cond
      ((= start end) sum)
      ((= (remainder start 3) 0)
       (get-sum (+ start 1) end (+ start sum)))
      ((= (remainder start 5) 0)
       (get-sum (+ start 1) end (+ start sum)))
      (else
       (get-sum (+ start 1) end sum))))

With this fix, your code displays 233168 . I didn't check your algorithm, but this result looks better than 0 :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM