***LANGUAGE IS SCHEME (R5RS)**** Recall from class the definition of number-sum,
ID: 3886126 • Letter: #
Question
***LANGUAGE IS SCHEME (R5RS)****
Recall from class the definition of number-sum, which computes the sum of the first n numbers: (define (number-sum n) (if (= n 0) 0 (+n (number - sum (-n 1))))) (a) Adapt the function to one named (odd-sum n) that computes the sum of the first n odd numbers. (So (odd-sum 4) should return 16, the sum of the first 4 odd numbers: 1+3+5+7.) (b) Evaluate your function at 1, 2, 3, 4, 5, 6, and 7. What does this sequence of numbers look like, and does that make sense? (c) Adapt the function into (sum-from-to a b) that it computes the sum of the all integers from a to b, so (sum-from-to 3 5) should evaluate to 12. If a is greater that b, it should evaluate to 0.Explanation / Answer
a)
(define (odd-sum n) (if (= n 1) 1 (+ (- (* 2 n) 1) (odd-sum (- n 1) ) ) ))
b) 1,4,9,16,25,36,49 => sequence of perfect squares
c)
(define (sum-from-to a b) (if (= b a) a (+ b (sum-from-to a (- b 1) ) ) ) ))
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.