Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 23s
Newton's method on integers, converging when y >= x:
let isqrt n =
if n < 2 then n
else
let x = ref n in
let y = ref ((!x + 1) / 2) in
while !y < !x do
x := !y;
y := (!x + n / !x) / 2
done;
!x
Test cases:
isqrt 144 = 12 (perfect square)
isqrt 200 = 14 (floor of sqrt(200) ~= 14.14)
isqrt 1000000 = 1000
isqrt 2 = 1
sum = 1027
Companion to newton_sqrt.ml (iter 124, float Newton). Tests integer
division semantics from iter 94 and a while-until-convergence loop.
88 baseline programs total.
15 lines
229 B
OCaml
15 lines
229 B
OCaml
let isqrt n =
|
|
if n < 2 then n
|
|
else
|
|
let x = ref n in
|
|
let y = ref ((!x + 1) / 2) in
|
|
while !y < !x do
|
|
x := !y;
|
|
y := (!x + n / !x) / 2
|
|
done;
|
|
!x
|
|
|
|
;;
|
|
|
|
isqrt 144 + isqrt 200 + isqrt 1000000 + isqrt 2
|