interplane.Get Omega
Read in your language

omega-mv

Omega: a language for verified programs, semantic identity and machine realization. Seed-born work and existing implementations have distinct provenance.

Brought by drakestapleton

branch main Branches Tags History

omega-mv / si / rosetta / tasks / isqrt-integer-square-root-of-x / isqrt-integer-square-root-of-x.om

75 lines · 1504 bytes Raw Blame History
1note Rosetta Code task "Isqrt (integer square root) of X": https://rosettacode.org/wiki/Isqrt_(integer_square_root)_of_X
2note SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
3om2
4text nl "\n"
5text sp " "
6text small "isqrt of 0..65:"
7text pre "isqrt(7^"
8text eqs ") = "
9note emit writes every byte of a to stdout; a short write is retried, an error exits 1
10fn emit a view uchar * to void
11o = ulong 0
12while lt o len a bound 4096
13k = write 1 a o sub len a o
14if le k 0
15exit 1
16end
17o = add o ulong k
18end
19end
20note emitu writes n in decimal; 20 digits hold every ulong
21fn emitu n ulong to void
22d = new uchar 20 0
23i = ulong 20
24v = n
25while true bound 20
26i = sub i 1
27put d i uchar add rem v 10 48
28v = div v 10
29if eq v 0
30break
31end
32end
33emit part d i sub 20 i
34end
35note the task's quadratic residue method: q is the least power of 4 above x, then one result bit per step
36note bound: inputs here are below 2^60, so q stays at most 2^60 (30 doublings of the exponent) and never wraps;
37note 7^n is shown for odd n up to 21, the largest odd power of 7 below 2^64 (the task goes on to 7^73 with bignums)
38fn isqrt x ulong to ulong
39q = ulong 1
40while le q x bound 31
41q = shl q 2
42end
43z = x
44r = ulong 0
45while gt q 1 bound 31
46q = shr q 2
47s = add r q
48r = shr r 1
49if ge z s
50z = sub z s
51r = add r q
52end
53end
54ret r
55end
56fn main to int
57emit small
58for x ulong 66
59emit sp
60emitu isqrt x
61end
62emit nl
63p = ulong 7
64n = ulong 1
65while le n 21 bound 11
66emit pre
67emitu n
68emit eqs
69emitu isqrt p
70emit nl
71p = mul p 49
72n = add n 2
73end
74ret 0
75end