omega-rosetta
aien-dev/omega-rosetta
Brought by drakestapleton
omega-rosetta / tasks / stern-brocot-sequence / stern-brocot-sequence.om
| 1 | note Rosetta Code task "Stern-Brocot sequence": https://rosettacode.org/wiki/Stern-Brocot_sequence |
| 2 | note SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
| 3 | om2 |
| 4 | text nl "\n" |
| 5 | text sp " " |
| 6 | text minus "-" |
| 7 | text tfirst "first 15: " |
| 8 | text tat " first appears at " |
| 9 | text tgcd "gcd of each consecutive pair of the first 1000 is 1: " |
| 10 | text tyes "yes" |
| 11 | text tno "no" |
| 12 | global sb ulong 1200 |
| 13 | note emit writes every byte of a to stdout; a short write is retried, an error exits 1 |
| 14 | fn emit a view uchar * to void |
| 15 | o = ulong 0 |
| 16 | while lt o len a bound 4096 |
| 17 | k = write 1 a o sub len a o |
| 18 | if le k 0 |
| 19 | exit 1 |
| 20 | end |
| 21 | o = add o ulong k |
| 22 | end |
| 23 | end |
| 24 | note emitu writes n in decimal; 20 digits hold every ulong |
| 25 | fn emitu n ulong to void |
| 26 | d = new uchar 20 0 |
| 27 | i = ulong 20 |
| 28 | v = n |
| 29 | while true bound 20 |
| 30 | i = sub i 1 |
| 31 | put d i uchar add rem v 10 48 |
| 32 | v = div v 10 |
| 33 | if eq v 0 |
| 34 | break |
| 35 | end |
| 36 | end |
| 37 | emit part d i sub 20 i |
| 38 | end |
| 39 | note start 1, 1; for each k from 1 on, append sb[k] + sb[k-1] and then sb[k], until 1200 members |
| 40 | fn build to void |
| 41 | put sb 0 1 |
| 42 | put sb 1 1 |
| 43 | n = ulong 2 |
| 44 | k = ulong 1 |
| 45 | note each pass adds two members, so 600 passes fill 1200 |
| 46 | while lt n 1200 bound 600 |
| 47 | put sb n add get sb k get sb sub k 1 |
| 48 | put sb add n 1 get sb k |
| 49 | n = add n 2 |
| 50 | k = add k 1 |
| 51 | end |
| 52 | end |
| 53 | note find gives the 1-based position of v's first appearance, 0 if not within the 1200 |
| 54 | fn find v ulong to ulong |
| 55 | for i ulong 1200 |
| 56 | if eq get sb i v |
| 57 | ret add i 1 |
| 58 | end |
| 59 | end |
| 60 | ret 0 |
| 61 | end |
| 62 | fn gcd a ulong b ulong to ulong |
| 63 | note Euclid's remainders shrink at least as fast as Fibonacci numbers, so 100 steps cover any ulong |
| 64 | while ne b 0 bound 100 |
| 65 | t = rem a b |
| 66 | a = b |
| 67 | b = t |
| 68 | end |
| 69 | ret a |
| 70 | end |
| 71 | fn show v ulong to void |
| 72 | emitu v |
| 73 | emit tat |
| 74 | emitu find v |
| 75 | emit nl |
| 76 | end |
| 77 | fn main to int |
| 78 | build |
| 79 | emit tfirst |
| 80 | for i ulong 15 |
| 81 | if gt i 0 |
| 82 | emit sp |
| 83 | end |
| 84 | emitu get sb i |
| 85 | end |
| 86 | emit nl |
| 87 | for i ulong 10 |
| 88 | show add i 1 |
| 89 | end |
| 90 | show 100 |
| 91 | ok = true |
| 92 | for i ulong 999 |
| 93 | if ne gcd get sb i get sb add i 1 1 |
| 94 | ok = false |
| 95 | end |
| 96 | end |
| 97 | emit tgcd |
| 98 | if ok |
| 99 | emit tyes |
| 100 | else |
| 101 | emit tno |
| 102 | end |
| 103 | emit nl |
| 104 | ret 0 |
| 105 | end |