interplane.Get Omega
Read in your language

omega-rosetta

aien-dev/omega-rosetta

Brought by drakestapleton

branch main Branches Tags History

omega-rosetta / tasks / perfect-totient-numbers / perfect-totient-numbers.om

75 lines · 1441 bytes Raw Blame History
1note Rosetta Code task "Perfect totient numbers": https://rosettacode.org/wiki/Perfect_totient_numbers
2note SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
3om2
4text nl "\n"
5text sp " "
6text first "first 20 perfect totient numbers:"
7note ph n is Euler's totient for n below 6000 (the 20th perfect totient number is 5571)
8global ph ulong 6000
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 sieve to void
36for i ulong 6000
37put ph i i
38end
39p = ulong 2
40while lt p 6000 bound 6000
41if eq get ph p p
42j = p
43while lt j 6000 bound 6000
44put ph j sub get ph j div get ph j p
45j = add j p
46end
47end
48p = add p 1
49end
50end
51note n is perfect totient when phi(n) + phi(phi(n)) + ... down to 1 adds up to n; each step at least halves
52note an even value, so 64 steps are plenty
53fn main to int
54sieve
55emit first
56c = ulong 0
57n = ulong 2
58while lt c 20 bound 5999
59s = ulong 0
60v = get ph n
61while gt v 1 bound 64
62s = add s v
63v = get ph v
64end
65s = add s 1
66if eq s n
67emit sp
68emitu n
69c = add c 1
70end
71n = add n 1
72end
73emit nl
74ret 0
75end