omega-rosetta
aien-dev/omega-rosetta
Brought by drakestapleton
omega-rosetta / drafts / rosettacode / isqrt-integer-square-root-of-x.wiki
| 1 | =={{header|Omegese}}== |
| 2 | {{works with|omc|sha256 2c824805, aien-dev/omega-mv e5b32567, Linux AArch64}} |
| 3 | Omega has no imports, so the small output helpers (<code>emit</code> and friends) are part of the program. |
| 4 | <syntaxhighlight lang="text"> |
| 5 | om2 |
| 6 | text nl "\n" |
| 7 | text sp " " |
| 8 | text small "isqrt of 0..65:" |
| 9 | text pre "isqrt(7^" |
| 10 | text eqs ") = " |
| 11 | note emit writes every byte of a to stdout; a short write is retried, an error exits 1 |
| 12 | fn emit a view uchar * to void |
| 13 | o = ulong 0 |
| 14 | while lt o len a bound 4096 |
| 15 | k = write 1 a o sub len a o |
| 16 | if le k 0 |
| 17 | exit 1 |
| 18 | end |
| 19 | o = add o ulong k |
| 20 | end |
| 21 | end |
| 22 | note emitu writes n in decimal; 20 digits hold every ulong |
| 23 | fn emitu n ulong to void |
| 24 | d = new uchar 20 0 |
| 25 | i = ulong 20 |
| 26 | v = n |
| 27 | while true bound 20 |
| 28 | i = sub i 1 |
| 29 | put d i uchar add rem v 10 48 |
| 30 | v = div v 10 |
| 31 | if eq v 0 |
| 32 | break |
| 33 | end |
| 34 | end |
| 35 | emit part d i sub 20 i |
| 36 | end |
| 37 | note the task's quadratic residue method: q is the least power of 4 above x, then one result bit per step |
| 38 | note bound: inputs here are below 2^60, so q stays at most 2^60 (30 doublings of the exponent) and never wraps; |
| 39 | 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) |
| 40 | fn isqrt x ulong to ulong |
| 41 | q = ulong 1 |
| 42 | while le q x bound 31 |
| 43 | q = shl q 2 |
| 44 | end |
| 45 | z = x |
| 46 | r = ulong 0 |
| 47 | while gt q 1 bound 31 |
| 48 | q = shr q 2 |
| 49 | s = add r q |
| 50 | r = shr r 1 |
| 51 | if ge z s |
| 52 | z = sub z s |
| 53 | r = add r q |
| 54 | end |
| 55 | end |
| 56 | ret r |
| 57 | end |
| 58 | fn main to int |
| 59 | emit small |
| 60 | for x ulong 66 |
| 61 | emit sp |
| 62 | emitu isqrt x |
| 63 | end |
| 64 | emit nl |
| 65 | p = ulong 7 |
| 66 | n = ulong 1 |
| 67 | while le n 21 bound 11 |
| 68 | emit pre |
| 69 | emitu n |
| 70 | emit eqs |
| 71 | emitu isqrt p |
| 72 | emit nl |
| 73 | p = mul p 49 |
| 74 | n = add n 2 |
| 75 | end |
| 76 | ret 0 |
| 77 | end |
| 78 | </syntaxhighlight> |
| 79 | {{out}} |
| 80 | <pre> |
| 81 | isqrt of 0..65: 0 1 1 1 2 2 2 2 2 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 4 5 5 5 5 5 5 5 5 5 5 5 6 6 6 6 6 6 6 6 6 6 6 6 6 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 8 8 |
| 82 | isqrt(7^1) = 2 |
| 83 | isqrt(7^3) = 18 |
| 84 | isqrt(7^5) = 129 |
| 85 | isqrt(7^7) = 907 |
| 86 | isqrt(7^9) = 6352 |
| 87 | isqrt(7^11) = 44467 |
| 88 | isqrt(7^13) = 311269 |
| 89 | isqrt(7^15) = 2178889 |
| 90 | isqrt(7^17) = 15252229 |
| 91 | isqrt(7^19) = 106765608 |
| 92 | isqrt(7^21) = 747359260 |
| 93 | </pre> |