Solution to SICP Exercise 1.33

Structure and Interpretation of Computer Programs

Solution to Exercise 1.33:

(define (filtered-accumulate predicate combiner null-value term a next b)
(define (iter a result)
(if (> a b)
result
(iter (next a) (if (predicate a)
(combiner (term a) result)
result))))
(iter a null-value))

; part a
(define (square x) (* x x))

(define (sum-of-squared-primes a b)
(define (square-and-add i result) (+ (square i) result))
(filtered-accumulate prime? square-and-add 0 identity a inc b))

; part b
(define (product-of-positives-relatively-prime-to n)
(define (relatively-prime? i)
(= 1 (gcd i n)))
(filtered-accumulate relatively-prime? * 1 identity 1 inc (- n 1)))

Solution to SICP Exercise 1.32

Structure and Interpretation of Computer Programs

Solution to Exercise 1.32:

; part a (recursive process)

(define (accumulate-r combiner null-value term a next b)
(if (> a b)
null-value
(combiner (term a)
(accumulate-r combiner null-value term (next a) next b))))

(define (sum-r term a next b)
(accumulate-r + 0 term a next b))

(define (product-r term a next b)
(accumulate-r * 1 term a next b))

; part b (iterative process)

(define (accumulate-i combiner null-value term a next b)
(define (iter a result)
(if (> a b)
result
(iter (next a) (combiner result (term a)))))
(iter a null-value))

Solution to SICP Exercise 1.31

Structure and Interpretation of Computer Programs

Solution to Exercise 1.31:

; part a (recursive process)
(define (product-r term a next b)
(if (> a b)
1
(* (term a)
(product-r term (next a) next b))))

(define (identity i) i)
(define (inc i) (+ i 1))

(define (factorial n)
(product-r identity 1 inc n))

(define (pi-approximator terms)
(define (numerator i)
(+ i (if (odd? i) 1 2)))
(define (denominator i)
(+ i (if (odd? i) 2 1)))
(define (pi-term i)
(/ (numerator i) (denominator i)))
(* 4.0 (product-r pi-term 1 inc terms)))

; part b (iterative process)
(define (product-i term a next b)
(define (iter a result)
(if (> a b)
result
(iter (next a) (* result (term a)))))
(iter a 1))