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 / twin-primes / twin-primes.om
| 1 | note Rosetta Code task "Twin primes": https://rosettacode.org/wiki/Twin_primes |
| 2 | note SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
| 3 | om2 |
| 4 | text nl "\n" |
| 5 | text pre "twin prime pairs below " |
| 6 | text colon ": " |
| 7 | note odd-only bit sieve below 10^8: odd q is bit q >> 1, set when q is composite; 5 * 10^7 bits in 6250000 bytes |
| 8 | global cb uchar 6250000 |
| 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 | fn mark q ulong to void |
| 36 | b = shr q 1 |
| 37 | put cb shr b 3 or get cb shr b 3 shl uchar 1 and b 7 |
| 38 | end |
| 39 | note isp is for odd q below 10^8 only (3, 5, 7, ...) |
| 40 | fn isp q ulong to bool |
| 41 | b = shr q 1 |
| 42 | ret eq and get cb shr b 3 shl uchar 1 and b 7 0 |
| 43 | end |
| 44 | note bound: odd p with p * p < 10^8 means p < 10^4; an odd prime p marks at most 10^8 / (2p) < 1.7 * 10^7 multiples, |
| 45 | note done as up to 1000 chunks of 999990 marks each |
| 46 | fn sieve to void |
| 47 | mark 1 |
| 48 | p = ulong 3 |
| 49 | while lt mul p p 100000000 bound 5000 |
| 50 | if isp p |
| 51 | s = mul p 2 |
| 52 | m = mul p p |
| 53 | while lt m 100000000 bound 1000 |
| 54 | c = ulong 0 |
| 55 | while and lt m 100000000 lt c 999990 bound 999999 |
| 56 | mark m |
| 57 | m = add m s |
| 58 | c = add c 1 |
| 59 | end |
| 60 | end |
| 61 | end |
| 62 | p = add p 2 |
| 63 | end |
| 64 | end |
| 65 | note a pair (p, p + 2) counts below lim when p + 2 < lim; p = 2j + 3 walks every odd p from 3 |
| 66 | fn main to int |
| 67 | sieve |
| 68 | lim = ulong 10 |
| 69 | cnt = ulong 0 |
| 70 | for j ulong 50000000 |
| 71 | p = add mul j 2 3 |
| 72 | while ge add p 2 lim bound 9 |
| 73 | emit pre |
| 74 | emitu lim |
| 75 | emit colon |
| 76 | emitu cnt |
| 77 | emit nl |
| 78 | lim = mul lim 10 |
| 79 | end |
| 80 | if gt lim 100000000 |
| 81 | break |
| 82 | end |
| 83 | if and isp p isp add p 2 |
| 84 | cnt = add cnt 1 |
| 85 | end |
| 86 | end |
| 87 | ret 0 |
| 88 | end |