Trial Division
October 25, 2016
Here is our solution:
(define (factors n) (let loop ((n n) (f 2) (fs (list))) (if (< n (* f f)) (reverse (cons n fs)) (if (zero? (modulo n f)) (loop (/ n f) f (cons f fs)) (loop n (+ f 1) fs)))))
There’s no simpler way to factor integers. Here are some examples:
> (factors 16) (2 2 2 2) > (factors 17) (17) > (factors 13290059) (3119 4261) > (factors 600851475143) (71 839 1471 6857)
You can run the program at http://ideone.com/r2xHK0, where you will also see the primality checker from the previous exercise, which has exactly the same form and structure.
Very basic Python 3 solution that divides out by 2 and then by each odd number until the reduced n becomes less than the square of the factor to be tested.
I used Python’s builtin divmod instead of separate modulo and division.
Here’s another Python solution, to make things more interesting, it factorizes Gaussian integers (ie. integral complex numbers):