integer-sqrt ( x -- n ) (original) (raw)

integer-sqrt ( x -- n )
Factor handbook » The language » Numbers » Mathematical functions » Integer functions

Prev: integer-log10 ( x -- n )

Vocabulary
math.functions

Inputs

x a non-negative rational number

Outputs

n an integer

Word description
Outputs the largest integer that is less than or equal to the sqrt of m.

Errors
Throws an error if m is negative.

Examples

USING: prettyprint math.functions ; 15 integer-sqrt .
3

Definition

USING: kernel math sequences ;

IN: math.functions

:: integer-sqrt ( x -- n )
x
[ 0 ] [
assert-non-negative bit-length 1 - 2 /i
:> c 1 :> a! 0 :> d! c bit-length [| s
|
d :> e c s neg shift d! a d e - 1 - shift x 2 c *
e - d - 1 + neg shift a /i + a!
] each a a sq x > [ 1 - ] when
] if-zero ;