interplane.Get Omega
Read in your language

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

branch main Branches Tags History

omega-mv / si / rosetta / tasks / lucas-lehmer-test / lucas-lehmer-test.om

111 lines · 2340 bytes Raw Blame History
1note Rosetta Code task "Lucas-Lehmer test": https://rosettacode.org/wiki/Lucas-Lehmer_test
2note SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
3om2
4text nl "\n"
5text sp " "
6text em "M"
7text hdr "Mersenne primes 2^p - 1 for p <= 63, by the Lucas-Lehmer test:"
8note w 0 and w 1 hold the high and low 64 bits of the last 128-bit product
9global w ulong 2
10note emit writes every byte of a to stdout; a short write is retried, an error exits 1
11fn emit a view uchar * to void
12o = ulong 0
13while lt o len a bound 4096
14k = write 1 a o sub len a o
15if le k 0
16exit 1
17end
18o = add o ulong k
19end
20end
21note emitu writes n in decimal; 20 digits hold every ulong
22fn emitu n ulong to void
23d = new uchar 20 0
24i = ulong 20
25v = n
26while true bound 20
27i = sub i 1
28put d i uchar add rem v 10 48
29v = div v 10
30if eq v 0
31break
32end
33end
34emit part d i sub 20 i
35end
36note mul128 forms a * b exactly from four 32 x 32 -> 64-bit partial products
37fn mul128 a ulong b ulong to void
38al = and a 0xffffffff
39ah = shr a 32
40bl = and b 0xffffffff
41bh = shr b 32
42ll = mul al bl
43lh = mul al bh
44hl = mul ah bl
45hi = add mul ah bh shr lh 32
46hi = add hi shr hl 32
47mid = add shr ll 32 and lh 0xffffffff
48mid = add mid and hl 0xffffffff
49put w 1 add and ll 0xffffffff shl mid 32
50put w 0 add hi shr mid 32
51end
52note sqm is s * s mod m for m = 2^p - 1, 2 < p <= 63,, s < m: the product x = q * 2^p + r folds to q + r
53note x < 2^(2p), so q < 2^p and q + r < 2^64; a second fold and one subtraction finish it
54fn sqm s ulong p ulong m ulong to ulong
55mul128 s s
56q = or shl get w 0 sub 64 p shr get w 1 p
57t = add q and get w 1 m
58t = add and t m shr t p
59if ge t m
60t = sub t m
61end
62ret t
63end
64note p is prime by trial division (p <= 63)
65fn smallp p ulong to bool
66if lt p 2
67ret false
68end
69d = ulong 2
70while le mul d d p bound 8
71if eq rem p d 0
72ret false
73end
74d = add d 1
75end
76ret true
77end
78note Lucas-Lehmer for odd prime p: s = 4, then p - 2 times s = s^2 - 2 mod M; M is prime iff s ends at 0
79fn lltest p ulong to bool
80m = sub shl ulong 1 p 1
81s = ulong 4
82for i ulong sub p 2
83s = sqm s p m
84if ge s 2
85s = sub s 2
86else
87s = sub add s m 2
88end
89end
90ret eq s 0
91end
92fn main to int
93emit hdr
94emit nl
95note M2 = 3 is prime by definition; the test as stated covers odd prime p
96emit em
97emitu 2
98p = ulong 3
99while le p 63 bound 61
100if smallp p
101if lltest p
102emit sp
103emit em
104emitu p
105end
106end
107p = add p 2
108end
109emit nl
110ret 0
111end