GCD By Factoring
November 3, 2017
We begin with this function that extracts common items from two sorted lists by simply walking down the lists:
(define (common lt? xs ys) (let loop ((xs xs) (ys ys) (zs (list))) (cond ((or (null? xs) (null? ys)) (reverse zs)) ((lt? (car xs) (car ys)) (loop (cdr xs) ys zs)) ((lt? (car ys) (car xs)) (loop xs (cdr ys) zs)) (else (loop (cdr xs) (cdr ys) (cons (car xs) zs))))))
For instance, (common < '(2 3 4 5 6) '(1 3 5 7 9))
returns the list (3 5)
. Then it’s easy to compute the greatest common divisor of two numbers:
(define (gcd-by-factoring m n) (apply * (common < (factors m) (factors n))))
This reads just as the english-language description of the problem; take the product of the common prime factors of the two numbers. Here are some examples:
> (gcd-by-factoring 24 60) 12 > (gcd-by-factoring 11111111 13290059) 1
You can run the program at https://ideone.com/v4xIrv, where you will also find a simple factoring program, suitable for finding small factors of not-too-large numbers.
When programming, either for myself or for the blog, I often look for reusable functions that I can extract from a program. For example, I could have written gcd-by-factoring
with the code for common
embedded within it, but separating the code yields a function that is useful in other contexts.
Two functions in Python. The first looks at the common factors of the 2 numbers. The second first gets the factors of the first number and then tries these factors on the second number.
In Java
long version:
Java short version: