Ken Dyck gives a more complete solution set.
Comment: Rather than finding the larger two explicitly, I find the smallest and use a simple mathematical identity.
My solutions:
Exercise 1.3. Define a procedure that takes three numbers as arguments and returns the sum of the squares of the two larger numbers.
(define (f a b c)Comment: Rather than finding the larger two explicitly, I find the smallest and use a simple mathematical identity.
(define (lt a b) (if (> a b) b a))
(define (least a b c) (lt a (lt b c)))
(define (square x) (* x x))
(+ (square a)
(square b)
(square c)
(- (square (least a b c)))))
Exercises 1.17 & 1.18: Devise recursive and iterative algorithms for multiplication that take a logarithmic number of steps.
(define (mul-recursive a b)Comments: Observe how similar the two solutions are. The iterative solution is especially easy to follow if you expand out an example.
(cond ((= b 0) 0)
((even? b) (mul-recursive (double a) (halve b)))
(else (+ a (mul-recursive a (- b 1))))))
(define(* a b)
(define (mul-iterative r a b)
(cond ((= b 0) r)
((even? b) (mul-iterative r (double a) (halve b)))
(else (mul-iterative (+ r a) a (- b 1)))))
(mul-iterative 0 a b))
3 comments:
Clever! I would never have thought of solving it that way.
Thanks for sharing your solution.
Thanks Ken.
(Perils of a mathematical education.)
And thank-you for making your solutions available online!
I've also started to share my solutions, together with my friends. We've created SICP wiki, which can be found here:
http://sicp.org.ua
Solutions in Scheme, Haskell and Oberon are available, as long as its discussions and comments.
Post a Comment