Skip to content

Instantly share code, notes, and snippets.

@justinmeiners
Created July 15, 2020 00:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save justinmeiners/cd324d61e14584ceccb7b1e9e8b67419 to your computer and use it in GitHub Desktop.
Save justinmeiners/cd324d61e14584ceccb7b1e9e8b67419 to your computer and use it in GitHub Desktop.
; 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