Construction and interpretation exercises computer program 1.20

Euclidean algorithm process:

(define (gcd a b))
	(if(= b 0))
			a
			(gcd b (remainder a b))

Now we have to follow the regular sequence to show the calculation process (gcd 206 40) generated;

(gcd 206 40)=(gcd 40 (remainder 206 40))
              =(gcd(remainder 206 40) (remainder 40 (remainder 206 40)))
              =(gcd(remainder 40 (remainder 206 40)) (remainder (remainder 206 40)(remainder 40 (remainder 206 40))))
              =(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)))))

The above calculation seems too complicated, we use him in order to simplify
M0 = (remainder 206 40) is to calculate a remainder of the results of
M1 = (remainder 40 M0) is counted twice remainder of the results of
M2 = (remainder M0 M1) four the results of the secondary remainder, M0 once, M1 twice, once during its own remainder, so the four
M3 = (remainder M1 M2) is the result of seven remainder of the calculation, M1 twice, M2 four times its own process there is a remainder, so seven times
and then we will simplify the process

(gcd 206 40)=(gcd 40 M0)
              =(gcd M0 M1)
              =(gcd M1 M2)
              =(gcd M2 M3)

// Then there are the students must think the number is the final calculation of M2 + M3 = number of 11 times, here is definitely wrong.

// let's review process gcd of each execution of the process step if gcd are conditional, we do not consider the above-mentioned process conditional.

(define (gcd a b))
	(if(= b 0))
			a
			(gcd b (remainder a b))

In addition, conditional only the last step is to perform a true statement, others are executed else statement, so we add the number to determine the conditions.

(gcd 206 40)=(gcd 40 M0)//条件判断 if(= M0 0),多执行一次
              =(gcd M0 M1)//条件判断 if(= M1 0),多执行两次
              =(gcd M1 M2)//条件判断 if(= M2 0),多执行四次
              =(gcd M2 M3)//条件判断 if(= M3 0),多执行七次,最后一次比较特殊,条件为true,还会执行一次M2,所以是11次

Finally, we added result 1 + 2 + 4 + 11 = 18 times, so regular calculation sequence is 18

Application of the order is adopted every time the results are passed, if conditional statement comparative figures only, and will not trigger the remainder calculation, so the result will be much simpler, each gcd calculation will only trigger a remainder computing, so a total of 4 times.

(gcd 206 40)=(gcd 40 6)
              =(gcd 6 4)
              =(gcd 4 2)
              =(gcd 2 0)
Published 27 original articles · won praise 1 · views 485

Guess you like

Origin blog.csdn.net/holybird0213/article/details/104580858