Mohammad Habib
Mohammad Habib

Reputation: 23

Scheme Function to sum even numbers

I need to create a recursive function in scheme to sum up the first n numbers of even numbers.

(define (even-sum n)
  (cond ((= n 0) 0)
        ((= (modulo n 2) 0) (+ n (even-sum (- n 2))))))

This is what I have so far but it only runs n number of times instead of summing the first n number of even numbers.

Upvotes: 2

Views: 792

Answers (1)

Óscar López
Óscar López

Reputation: 235994

You simply forgot to handle the case when n is odd:

(define (even-sum n)
  (cond ((<= n 0) 0)
        ((= (modulo n 2) 0)
         (+ n (even-sum (- n 2))))
        (else (even-sum (- n 1)))))

By the way: you can achieve the same result with a simple formula, assuming that n >= 0. There is no need to iterate!

(define (even-sum n)
  (let ((m (if (even? n) n (- n 1))))
    (* (+ m 2) (/ m 4))))

Either way, it works as expected:

(even-sum 1001)
=> 250500

Upvotes: 4

Related Questions