Last active
May 11, 2020 08:01
-
-
Save oantolin/6073417 to your computer and use it in GitHub Desktop.
Code for this SO question: http://stackoverflow.com/questions/17838611/what-is-the-easiest-way-to-promise-a-common-lisp-compiler-that-the-result-of-an
This file contains 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
(declaim (optimize (speed 3) (safety 0))) | |
(defmacro with-type (type expr) | |
(if (atom expr) | |
expr | |
(let ((op (car expr))) | |
(reduce | |
(lambda (x y) | |
`(the ,type | |
(,op ,@(if x (list x) '()) | |
(with-type ,type ,y)))) | |
(cdr expr) | |
:initial-value nil)))) | |
(defun layer (x y z n) | |
(declare (fixnum x y z n)) | |
; (with-type fixnum | |
(logand #.(1- (ash 1 (integer-length most-positive-fixnum))) | |
(+ (* 2 (+ (* x y) (* y z) (* x z))) | |
(* 4 (+ x y z n -2) (1- n))))) | |
(defun cubes (n) | |
(declare (fixnum n)) | |
(let ((count (make-array (+ n 1) :element-type 'fixnum))) | |
(loop for x of-type fixnum from 1 while (<= (layer x x x 1) n) do | |
(loop for y of-type fixnum from x while (<= (layer x y y 1) n) do | |
(loop for z of-type fixnum from y while (<= (layer x y z 1) n) do | |
(loop for k of-type fixnum from 1 while (<= (layer x y z k) n) do | |
(incf (elt count (layer x y z k))))))) | |
count)) | |
(defun first-time (x) | |
(declare (fixnum x)) | |
(loop for n of-type fixnum = 1000 then (* 2 n) | |
for k = (position x (cubes n)) | |
until k | |
finally (return k))) | |
(time (print (first-time 1000))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment