interplane.Get Omega
Read in your language

omega-rosetta

aien-dev/omega-rosetta

Brought by drakestapleton

branch main Branches Tags History

omega-rosetta / tasks / primality-by-trial-division / primality-by-trial-division.om

80 lines · 1408 bytes Raw Blame History
1note Rosetta Code task "Primality by trial division": https://rosettacode.org/wiki/Primality_by_trial_division
2note SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
3om2
4text nl "\n"
5text sp " "
6text hdr "primes below 100:"
7text yes " is prime\n"
8text no " is not prime\n"
9note emit writes every byte of a to stdout; a short write is retried, an error exits 1
10fn emit a view uchar * to void
11o = ulong 0
12while lt o len a bound 4096
13k = write 1 a o sub len a o
14if le k 0
15exit 1
16end
17o = add o ulong k
18end
19end
20note emitu writes n in decimal; 20 digits hold every ulong
21fn emitu n ulong to void
22d = new uchar 20 0
23i = ulong 20
24v = n
25while true bound 20
26i = sub i 1
27put d i uchar add rem v 10 48
28v = div v 10
29if eq v 0
30break
31end
32end
33emit part d i sub 20 i
34end
35note trial division by 2, then by odd d while d * d <= n
36note 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
37fn prime n ulong to bool
38if lt n 2
39ret false
40end
41if eq rem n 2 0
42ret eq n 2
43end
44d = ulong 3
45while le mul d d n bound 999999
46if eq rem n d 0
47ret false
48end
49d = add d 2
50end
51ret true
52end
53fn tell n ulong to void
54emitu n
55if prime n
56emit yes
57else
58emit no
59end
60end
61fn main to int
62emit hdr
63for i ulong 100
64if prime i
65emit sp
66emitu i
67end
68end
69emit nl
70tell 1
71tell 2
72tell 9
73tell 561
74tell 7919
75tell 2147483647
76tell 999999999989
77tell 999999999999
78tell 1000000000039
79ret 0
80end