I have a question regarding a problem that is done in DrRack
I have a question regarding a problem that is done in DrRacket.
Question 1: The famous computer scientist, Edsger Dijkstra, made the following observations for m and n >= 1:
1. If m = n, then the greatest common divisor of m and n is m.
2. If m > n, then the greatest common divisor of m and n is the greatest divisor of m-n and n.
Based on these observations, implement a function to compute the greatest common divisor of two given numbers >= 1. Follow all the steps of the design recipe. and write the termination argument.
Below is what I have so far. But i\'m sure its wrong recording the questions above. can someone help please?
;1. If m = n, then the greatest common divisor of m and n is m.
;2. If m > n, then the greatest common divisor of m and n is
; the greatest divisor of m-n and n.
(define (greatest-common-divisor n m)
(local [(define (first-divisor-<= i)
(cond [(=i 1) 1]
[else (cond [(and (= (remainder n i) 0)
(= (remainder m i) 0))
i]
[else (first-divisor-<= (sub1 i))])]))]
(first-divisor-<= (min m n))))
;Termination Argument
;There are 2 positive numbers in and that is the largest integers
;When returning m n, assuming one of them is 0 but actually returning non zero
(check-expect (greatest-common-divisor 0) 0)
(check-expect (greatest-common-divisor 6 12 8) 2)
Solution
So, following is the recursive function to calculate the GCD of two numbers based on the observations of Edsger Dijkstra.
Python code:
def gcd(n,m):
if(n ==m):
return n
elif(n > m):
return gcd(n-m, m)
else:
return gcd(n,m-n)
Sample Output:
20
1
29
