Well, here's one answer a mathematician would give: the sum of all integers from a
to b
is half of the sum of integers from a
to b
plus the sum of all integers from b
to a
. And this is a + b + a + 1 + b - 1 + ... + b + a
which is a + b + a + b + ... + a + b
. And this in turn is (a + b) * (b - a + 1)
. So the final sum is (a + b) * (a - b + 1) / 2
therefore. So just write that in Lisp, with the additional condition specified that for b < a
:
(define (sum-a-b a b)
(if (> a b)
0
(/ (* (+ a b) (+ (- b a) 1)) 2)))
Of course, what is probably being looked for is either a recursive or an iterative answer. Either of those is a terrible solution to the problem: the recursive answer is terrible in both time & space complexity while the iterative one is merely terrible in terms of time complexity.
People who teach Lisp should stop actively trying to teach people to program badly.