interplane.Get Omega
Read in your language

omega-rosetta

aien-dev/omega-rosetta

Brought by drakestapleton

branch main Branches Tags History

omega-rosetta / tasks / twin-primes / twin-primes.om

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