interplane.Get Omega
Read in your language

omega-rosetta

aien-dev/omega-rosetta

Brought by drakestapleton

branch main Branches Tags History

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

137 lines · 2265 bytes Raw Blame History
1note Rosetta Code task "Cuban primes": https://rosettacode.org/wiki/Cuban_primes
2note SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
3om2
4text nl "\n"
5text sp " "
6text first "first 200 cuban primes:\n"
7text th "the 100000th cuban prime: "
8note emit writes every byte of a to stdout; a short write is retried, an error exits 1
9fn emit a view uchar * to void
10o = ulong 0
11while lt o len a bound 4096
12k = write 1 a o sub len a o
13if le k 0
14exit 1
15end
16o = add o ulong k
17end
18end
19note emitu writes n in decimal; 20 digits hold every ulong
20fn emitu n ulong to void
21d = new uchar 20 0
22i = ulong 20
23v = n
24while true bound 20
25i = sub i 1
26put d i uchar add rem v 10 48
27v = div v 10
28if eq v 0
29break
30end
31end
32emit part d i sub 20 i
33end
34note cuban primes here are the primes (n+1)^3 - n^3 = 3n^2 + 3n + 1; the 100000th, 1792617147127, is below 2^41
35note mulm is a * b mod m for m < 2^42: b splits into 21-bit halves so each product stays below 2^63
36fn mulm a ulong b ulong m ulong to ulong
37h = mul a shr b 21
38h = rem h m
39h = rem shl h 21 m
40l = rem mul a and b 0x1fffff m
41r = add h l
42if ge r m
43r = sub r m
44end
45ret r
46end
47fn powm b ulong e ulong m ulong to ulong
48r = ulong 1
49x = rem b m
50v = e
51while gt v 0 bound 64
52if eq and v 1 1
53r = mulm r x m
54end
55x = mulm x x m
56v = shr v 1
57end
58ret r
59end
60fn sprp n ulong a ulong to bool
61d = sub n 1
62s = ulong 0
63while eq and d 1 0 bound 64
64d = shr d 1
65s = add s 1
66end
67x = powm a d n
68if or eq x 1 eq x sub n 1
69ret true
70end
71for i ulong sub s 1
72x = mulm x x n
73if eq x sub n 1
74ret true
75end
76end
77ret false
78end
79note trial division by 2..49 first, then Miller-Rabin to bases 2, 3, 5, 7, 11, 13, which is exact below 3.47 * 10^12
80fn isprime n ulong to bool
81p = ulong 2
82while lt p 50 bound 50
83if eq rem n p 0
84ret eq n p
85end
86p = add p 1
87end
88for k ulong 6
89a = ulong 13
90if eq k 0
91a = 2
92end
93if eq k 1
94a = 3
95end
96if eq k 2
97a = 5
98end
99if eq k 3
100a = 7
101end
102if eq k 4
103a = 11
104end
105if not sprp n a
106ret false
107end
108end
109ret true
110end
111note bound: the 100000th cuban prime is reached at n = 773019
112fn main to int
113emit first
114c = ulong 0
115n = ulong 1
116while lt c 100000 bound 999999
117v = add mul mul 3 n add n 1 1
118if isprime v
119c = add c 1
120if le c 200
121emitu v
122if eq rem c 10 0
123emit nl
124else
125emit sp
126end
127end
128if eq c 100000
129emit th
130emitu v
131emit nl
132end
133end
134n = add n 1
135end
136ret 0
137end