Created
July 15, 2020 00:36
-
-
Save justinmeiners/cd324d61e14584ceccb7b1e9e8b67419 to your computer and use it in GitHub Desktop.
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
; code translated from | |
; https://en.wikipedia.org/wiki/Integer_square_root | |
; note that theirs actually has an off by one error | |
(defun integer-sqrt (n) | |
(prog ((shift 2) (result 0)) | |
(declare (fixnum n shift result)) | |
(if (< n 2) (return n)) | |
shifting | |
(if (not (= (ash n (- shift)) 0)) | |
(progn | |
(incf shift) | |
(incf shift) | |
(go shifting) | |
)) | |
unroll | |
(setf result (ash result 1)) | |
(let ((larger (+ result 1))) | |
(declare (fixnum larger)) | |
(if (<= (* larger larger) (ash n (- shift))) | |
(setf result larger) | |
) | |
(decf shift) | |
(decf shift) | |
) | |
(if (>= shift 0) | |
(go unroll) | |
) | |
(return result) | |
)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment