Reputation: 23
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
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