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 / primality-by-trial-division / primality-by-trial-division.om
| 1 | note Rosetta Code task "Primality by trial division": https://rosettacode.org/wiki/Primality_by_trial_division |
| 2 | note SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
| 3 | om2 |
| 4 | text nl "\n" |
| 5 | text sp " " |
| 6 | text hdr "primes below 100:" |
| 7 | text yes " is prime\n" |
| 8 | text no " is not prime\n" |
| 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 trial division by 2, then by odd d while d * d <= n |
| 36 | note bound: the largest input is below 10^12 + 40, so d stays below 10^6 + 2 (at most 500001 odd values) and mul d d does not wrap |
| 37 | fn prime n ulong to bool |
| 38 | if lt n 2 |
| 39 | ret false |
| 40 | end |
| 41 | if eq rem n 2 0 |
| 42 | ret eq n 2 |
| 43 | end |
| 44 | d = ulong 3 |
| 45 | while le mul d d n bound 999999 |
| 46 | if eq rem n d 0 |
| 47 | ret false |
| 48 | end |
| 49 | d = add d 2 |
| 50 | end |
| 51 | ret true |
| 52 | end |
| 53 | fn tell n ulong to void |
| 54 | emitu n |
| 55 | if prime n |
| 56 | emit yes |
| 57 | else |
| 58 | emit no |
| 59 | end |
| 60 | end |
| 61 | fn main to int |
| 62 | emit hdr |
| 63 | for i ulong 100 |
| 64 | if prime i |
| 65 | emit sp |
| 66 | emitu i |
| 67 | end |
| 68 | end |
| 69 | emit nl |
| 70 | tell 1 |
| 71 | tell 2 |
| 72 | tell 9 |
| 73 | tell 561 |
| 74 | tell 7919 |
| 75 | tell 2147483647 |
| 76 | tell 999999999989 |
| 77 | tell 999999999999 |
| 78 | tell 1000000000039 |
| 79 | ret 0 |
| 80 | end |