user8928280
user8928280

Reputation:

Scheme Lisp program for the sum of n even numbers

I need to make a function that computes the sum of the first n even numbers starting with 0 (i.e (even-sum 4) would return 12).

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

This is what I have thus far, it works for (even-sum 4) but not other cases, (even-sum 6) should be 30 but comes out to 24, (even-sum 2) should be 2 but comes out to 4.

Upvotes: 0

Views: 962

Answers (2)

coredump
coredump

Reputation: 38809

You can compute the sum of the first n numbers of an arithmetic progression by applying this formula (see Wikipedia):

(define (arithmetic-series step n)
  (let ((an (+ 2 (* step (- n 1)))))
    (/ (* (+ 2 an) n) 2)))

(arithmetic-series 2 20)
=> 420

However, if you substitute d by 2, the formula is simpler.

(edit: see comment from Will Ness)

Upvotes: 2

Barmar
Barmar

Reputation: 781004

You should only be subtracting 1 in the recursion step.

And you need to subtract 1 from n when multiplying by 2. The first 4 even numbers are 0, 2, 4, 6, so to get 6 you need (* (- 4 1) 2).

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

Upvotes: 1

Related Questions