Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ; for http://www.reddit.com/r/dailyprogrammer/comments/rg25w/3272012_challenge_31_intermediate/
- (define (prime-factors n)
- (let ((max (+ 1 (sqrt n))) (% modulo))
- (let fs ((n n) (x 2))
- (if (= 1 n) '()
- (cond
- ((zero? (% n x)) (cons x (fs (/ n x) x)))
- ((> x max) (list n))
- (else (fs n (+ 1 x))))))))
- (define (c n)
- (lambda (small + *)
- (if (<= n small) n
- (let ((fs (prime-factors n)))
- (if (= 1 (length fs)) ; is prime
- (if (<= (car fs) small) ; is small
- (car fs) ; return it
- (+ 1 ((c (- n 1)) small + *))) ; else, rest+decompose
- (apply * (map (lambda (n) ; apply to * c of factors
- ((c n) small + *))
- fs)))))))
- ; checking it works for the provided data
- ; check complexity
- (map (lambda (n) ((c n) 5 + +)) '(9 11 154 446 956 6458))
- ; check reconstruction from decomposed numbers
- (map (lambda (n) ((c n) 5 + *)) '(9 11 154 446 956 6458))
- ; check formulas
- '(map (lambda (n) ((c n) 5 list list)) '(9 11 154 446 956 6458))
- (map (lambda (n)
- ((c n) 5
- (lambda (a b) (list '+ a b))
- (lambda ls (cons '* ls))))
- '(9 11 154 446 956 6458))
- ; check that formulas actually work
- (let ((eval (lambda (x) (eval x (scheme-report-environment 5)))))
- (map (lambda (n)
- (eval
- ((c n) 5
- (lambda (a b) (list '+ a b))
- (lambda ls (cons '* ls)))))
- '(9 11 154 446 956 6458)))
- ; formulas in lisp's native prefix format, obviously :)
Add Comment
Please, Sign In to add comment