interplane.Get Omega
Read in your language

omega-rosetta

aien-dev/omega-rosetta

Brought by drakestapleton

branch main Branches Tags History

omega-rosetta / tasks / kaprekar-numbers / kaprekar-numbers.om

71 lines · 1295 bytes Raw Blame History
1note Rosetta Code task "Kaprekar numbers": https://rosettacode.org/wiki/Kaprekar_numbers
2note SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
3om2
4text nl "\n"
5text sp " "
6text hdr "Kaprekar numbers below 10000:"
7text cnt "count of Kaprekar numbers below 1000000: "
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 n is Kaprekar when n * n splits as a * 10^k + b with b > 0 and a + b = n (1 counts by definition)
35note bound: n < 10^6, so n * n < 10^12 and p walks at most 12 powers of ten
36fn kap n ulong to bool
37if eq n 1
38ret true
39end
40sq = mul n n
41p = ulong 10
42while le p sq bound 20
43b = rem sq p
44if gt b 0
45if eq add div sq p b n
46ret true
47end
48end
49p = mul p 10
50end
51ret false
52end
53fn main to int
54emit hdr
55c = ulong 0
56for i ulong 999999
57n = add i 1
58if kap n
59c = add c 1
60if lt n 10000
61emit sp
62emitu n
63end
64end
65end
66emit nl
67emit cnt
68emitu c
69emit nl
70ret 0
71end