{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

hw3 - CS 61A Homework Solutions Week 3 1 SICP exercises...

Info iconThis preview shows pages 1–3. Sign up to view the full content.

View Full Document Right Arrow Icon
Sheet1 Page 1 CS 61AHomework SolutionsWeek 3 1. SICP exercises. 1.16: The goal is to use the algorithm of fast-exp on page 45, but avoid using the recursive call as an argument to something else. The hint tells us to use an extra variable, a, which will contain part of the result. (define (fast-exp b n) (define (iter a b n) (cond ((= n 0) a) ((even? n) (iter a (square b) (/ n 2))) (else (iter (* a b) b (- n 1))))) (iter 1 b n)) We're supposed to keep the quantity a*b^n constant in all the invocations of ITER for any specific problem. If n is even, we square b and divide n by 2, so we have a * (b^2)^(n/2) which is indeed equal to a*b^n. If n is odd, we have (a * b) * b^(n-1) which is also equal to a*b^n. So each invocation does keep the overall value constant. When we get to n=0, therefore, the value of a must be the original value of b^n. It's important to pay attention to what the problem says about invariants that's what this problem is about! 1.35: The definition of a fixed point is that it satisfies the equation f(x)=x. In this case, f(x)=1 + (1/x), so we are looking for a number that satisfies 1 + (1/x) = x Multiply both sides by x and you get x + 1 = x^2 which is the definition of the golden ratio on page 38. Therefore we can compute phi by calling (fixed-point (lambda (x) (+ 1 (/ 1 x))) 1) 1.37. The simplest solution is probably the following, which uses a helper function but generates a recursive process: (define (cont-frac n d k) (define (helper i) (if (> i k) 0 (/ (n i) (+ (d i) (helper (+ i 1)))))) (helper 1))
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full Document Right Arrow Icon
Sheet1 Page 2 This says that helper(1) = N(1)/[D(1)+helper(2)] helper(2) = N(2)/[D(2)+helper(3)] and so on, until we reach the Kth term: helper(K) = N(K)/[D(K)+0] In the iterative version, we first compute x = N(k)/D(k), then use that to compute N(k-1)/[D(k-1)+x], and so on until we reach the outermost fraction.
Background image of page 2
Image of page 3
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}