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