Add integer square root

This commit is contained in:
Nathan McCarty 2023-06-23 02:24:58 -04:00
parent 00740bb311
commit a3d54c59df
Signed by: thatonelutenist
SSH Key Fingerprint: SHA256:hwQEcmak9E6sdU9bXc98RHw/Xd1AhpB5HZT7ZSVJkRM
2 changed files with 19 additions and 0 deletions

View File

@ -16,6 +16,7 @@ license = "Parity Public License 7.0.0"
-- modules to install
modules = PrimeSieve
, PrimeSieve.Util
-- main file (i.e. file to load at REPL)
main = PrimeSieve

18
src/PrimeSieve/Util.idr Normal file
View File

@ -0,0 +1,18 @@
module PrimeSieve.Util
%default total
||| Integer square root
export
isqrt : (Integral t, Ord t) => t -> t
isqrt n = sqrt' n
where
sqrt' : t -> t
sqrt' a =
let b = (a + (n `div` a)) `div` 2
in if a > b then sqrt' (assert_smaller a b) else a
||| Nat square root
export
sqrtNat : Nat -> Nat
sqrtNat = integerToNat . isqrt . natToInteger