patternMinor
GCD - is this solution iterative?
Viewed 0 times
thisgcdsolutioniterative
Problem
Using the property that GCD(a, b) = GCD(b, r) where r is the remainder when you compute (a / b), you can write a recursive function as follows:
I also tried to write the following as an iterative function, but it still looks very similar to the recursive solution to my eye. Is this a correct, iterative solution?
EDIT: It appears that the first solution was actually iterative, and in fact very similar to the solution written in SICP (http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-11.html). What would a recursive solution to this problem look like?
(define (gcd a b)
; recursive
(if (= 0 b) a
(gcd b (remainder a b))))I also tried to write the following as an iterative function, but it still looks very similar to the recursive solution to my eye. Is this a correct, iterative solution?
(define (i-gcd a b)
; is this iterative?
(i-gcd-iter (remainder a b) b))
(define (i-gcd-iter acc b)
(if (= 0 b) acc
(gcd b (remainder acc b))))EDIT: It appears that the first solution was actually iterative, and in fact very similar to the solution written in SICP (http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-11.html). What would a recursive solution to this problem look like?
Solution
Indeed, both versions you have are iterative. I'm not actually sure that a recursive solution makes sense in this case---usually a recursive approach is for the classical pattern of holding the result of operating on the first item, then recursing into the remaining items. Calculating the GCD doesn't fit that pattern.
One small suggestion: you can use
One small suggestion: you can use
(zero? b) instead of (= 0 b).Context
StackExchange Code Review Q#1517, answer score: 4
Revisions (0)
No revisions yet.