To be noted: the drawing in exercise 1.14 is unfinished. I did it in a notebook, but haven't yet had the time to put it in a txt file.
52 lines
2 KiB
Text
52 lines
2 KiB
Text
(gcd 206 40)
|
|
; 40 != 0
|
|
(gcd 40 (remainder 206 40))
|
|
; in the if, remainder is computed and it isn't zero - 1c
|
|
; but I'm pretty sure this doesn't mean the remainder as the
|
|
; argument to gcd is evaluated, so we get:
|
|
(gcd (remainder 206 40) (remainder 40 (remainder 206 40)))
|
|
; in the next if, the two nested remainders must be computed - 2c
|
|
; and we're left with
|
|
(gcd (remainder 40 (remainder 206 40))
|
|
(remainder (remainder 206 40)
|
|
(remainder 40 (remainder 206 40))))
|
|
; in the next, the nested 4 are computed - 4c
|
|
; and we have:
|
|
(gcd (remainder (remainder 206 40)
|
|
(remainder 40 (remainder 206 40)))
|
|
(remainder (remainder 40 (remainder 206 40))
|
|
(remainder (remainder 206 40)
|
|
(remainder 40 (remainder 206 40)))))
|
|
; and the nested 7 must be computed. This will actually return 0, and then the
|
|
; first arg (4 nested remainder calls) must be evaluated, and that's it, but
|
|
; let's generalize.
|
|
|
|
; counting n from 0:
|
|
; notice in each n-th recursive pass, we evaluate remainder G(n+1) times.
|
|
; But also our arguments (a, b) end up having G(n+1)-level and G(n+2)-level
|
|
; indented applications of remainder, respectively, previously they had G(n)
|
|
; and G(n+1)
|
|
|
|
; here G(0)=G(1)=0, and for n>1 G(n) = G(n-1) + G(n-2) + 1
|
|
; so: G | n
|
|
----+---
|
|
; 0 | 0
|
|
; 0 | 1
|
|
; 1 | 2
|
|
; 2 | 3
|
|
; 4 | 4
|
|
; 7 | 5
|
|
|
|
; this happens until n=4, which is the last function call because that's when
|
|
; the right hand (G(5) calls) will evaluate to zero. And the final result, the
|
|
left hand, (G(4) calls) will be evaluated, and return 2.
|
|
|
|
So ultimately, the number of calls that must happen is:
|
|
G(1) + G(2) + ... + G(5) + G(4) (again)
|
|
or, more generally, if it takes n steps to compute the GCD:
|
|
Sum(G(1)..G(n+1)) + G(n) calls to remainder will be required.
|
|
|
|
In out situation, this will be 0+1+2+4+7+4 = 18 calls.
|
|
|
|
In the applicative order, the situation is far simpler, every recursive pass,
|
|
except the last, requires 1 call to remainder, so 4 calls.
|