Created
September 18, 2017 19:52
-
-
Save codekansas/1496aa8f93ace62983a2034af7518f20 to your computer and use it in GitHub Desktop.
Program for finding all the factors of a number in Scheme.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
; 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