Skip to content

Instantly share code, notes, and snippets.

@mnp
Last active June 3, 2022 18:13
Show Gist options
  • Save mnp/4a43d40e3a5a4d075e06ecdf7356eaaf to your computer and use it in GitHub Desktop.
Save mnp/4a43d40e3a5a4d075e06ecdf7356eaaf to your computer and use it in GitHub Desktop.
(intern ":fact")
(intern ":expt")
(defun sp/fact (n) ; n!
(if (> n 1)
(* n (sp/fact (- n 1)))
1))
(defun sp/term(op &rest rest)
(cond ((eq op :fact) (cons 'sp/fact rest)) ; a!
((eq op :expt) (cons 'expt rest)) ; a^b
t (error "bad op")))
(defun sp/poly (&rest terms)
terms)
(defun sp/eval-term (term)
(eval term))
(defun sp/eval-poly (poly)
(apply '+ (mapcar 'sp/eval-term poly)))
(defun sp/show-poly (poly)
poly)
; (sp/eval-poly (sp/poly (sp/term :fact 5) (sp/term :expt 3 4) (sp/term :expt 2 5)))
;-> 233
; (sp/show-poly (sp/poly (sp/term :fact 5) (sp/term :expt 3 4) (sp/term :expt 2 5)))
; -> ((sp/fact 5) (expt 3 4) (expt 2 5))
; nearest power of k nearest n
(defun sp/nearest-power-of-k(n k)
(let* ((lg (log n k))
;; two possible nearest values
(a (expt k (floor lg)))
(b (expt k (ceiling lg))))
;; pick the closest one
(if (< (- n a) (- b n))
a
b)))
;; ;; expected
;; 5, 3 -> 3
;; 32, 7 -> 49
;; 6, 3 -> 9
;; (sp/nearest-power-of-k 5 3)
;; 3
;; (sp/nearest-power-of-k 6 3)
;; 9
;; (sp/nearest-power-of-k 32 7)
;; 49
(defun sp/primes-below(n)
)
(defun sp/nearest-prime-power-below-n(n)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment