Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@codekansas
Created September 18, 2017 19:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save codekansas/1496aa8f93ace62983a2034af7518f20 to your computer and use it in GitHub Desktop.
Save codekansas/1496aa8f93ace62983a2034af7518f20 to your computer and use it in GitHub Desktop.
Program for finding all the factors of a number in Scheme.
; Finds all factors of a number in O(sqrt n) time.
(define (factors n)
(define (@factors n i a)
(cond ((= (modulo n i) 0) (@factors (quotient n i) i (cons i a)))
((>= (* i i) n) (if (= 1 n) a (cons n a)))
(else (@factors n (+ i 1) a))))
(@factors n 2 `()))
; Multiples all the elements in a list.
(define (mult l)
(define (@mult l i)
(if (null? l) i (@mult (cdr l) (* (car l) i))))
(@mult l 1))
; Tests all numbers between "start" and "end" (e.g. (test 10 100)).
(define (test start end)
(if (>= start end) #t
(let ((f (factors start)))
(begin
(display "Factors of ")
(display start)
(display ": ")
(display f)
(display "\n")
(if (= (mult f) start)
(test (+ start 1) end)
(errorf `test "error on ~s" start))))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment