namekuseijin

complexity of whole number

Mar 28th, 2012
164
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scheme 1.68 KB | None | 0 0
  1. ; for http://www.reddit.com/r/dailyprogrammer/comments/rg25w/3272012_challenge_31_intermediate/
  2.  
  3. (define (prime-factors n)
  4.   (let ((max (+ 1 (sqrt n))) (% modulo))
  5.     (let fs ((n n) (x 2))
  6.       (if (= 1 n) '()
  7.           (cond
  8.             ((zero? (% n x)) (cons x (fs (/ n x) x)))
  9.             ((> x max)       (list n))
  10.             (else                    (fs n (+ 1 x))))))))
  11.  
  12. (define (c n)
  13.   (lambda (small + *)
  14.     (if (<= n small) n
  15.         (let ((fs (prime-factors n)))
  16.           (if (= 1 (length fs))             ; is prime
  17.               (if (<= (car fs) small)           ; is small
  18.                   (car fs)                      ; return it
  19.                   (+ 1 ((c (- n 1)) small + *))) ; else, rest+decompose
  20.               (apply * (map (lambda (n)     ; apply to * c of factors
  21.                               ((c n) small + *))
  22.                             fs)))))))
  23.  
  24. ; checking it works for the provided data
  25. ; check complexity
  26. (map (lambda (n) ((c n) 5 + +)) '(9 11 154 446 956 6458))
  27. ; check reconstruction from decomposed numbers
  28. (map (lambda (n) ((c n) 5 + *)) '(9 11 154 446 956 6458))
  29. ; check formulas
  30. '(map (lambda (n) ((c n) 5 list list)) '(9 11 154 446 956 6458))
  31. (map (lambda (n)
  32.        ((c n) 5
  33.               (lambda (a b) (list '+ a b))
  34.               (lambda ls (cons '* ls))))
  35.      '(9 11 154 446 956 6458))
  36. ; check that formulas actually work
  37. (let ((eval (lambda (x) (eval x (scheme-report-environment 5)))))
  38.   (map (lambda (n)
  39.          (eval
  40.           ((c n) 5
  41.                  (lambda (a b) (list '+ a b))
  42.                  (lambda ls (cons '* ls)))))
  43.        '(9 11 154 446 956 6458)))
  44.  
  45. ; formulas in lisp's native prefix format, obviously :)
Add Comment
Please, Sign In to add comment