RosettaCodeData/Task/Arithmetic-numbers/Ballerina/arithmetic-numbers.ballerina
2025-06-11 20:16:52 -04:00

98 lines
2.6 KiB
Text

import ballerina/io;
function divisors(int n) returns int[] {
if n < 1 { return []; }
int[] divisors = [];
int[] divisors2 = [];
int i = 1;
int k = n % 2 == 0 ? 1 : 2;
while i * i <= n {
if n % i == 0 {
divisors.push(i);
int j = n / i;
if j != i { divisors2.push(j); }
}
i += k;
}
if divisors2.length() > 0 {
divisors.push(...divisors2.reverse());
}
return divisors;
}
function findNearest(int[] a, int value) returns int {
int count = a.length();
int low = 0;
int high = count - 1;
while low <= high {
int mid = (low + high) / 2;
if a[mid] >= value {
high = mid - 1;
} else {
low = mid + 1;
}
}
return low < count ? low : count;
}
function commatize(int n) returns string {
string s = n.toString();
if n < 0 { s = s.substring(1); }
int le = s.length();
foreach int i in int:range(le - 3, 0, -3) {
s = s.substring(0, i) + "," + s.substring(i);
}
if n >= 0 { return s; }
return "-" + s;
}
function isPrime(int n) returns boolean {
if n < 2 { return false; }
if n % 2 == 0 { return n == 2; }
if n % 3 == 0 { return n == 3; }
int d = 5;
while d * d <= n {
if n % d == 0 { return false; }
d += 2;
if n % d == 0 { return false; }
d += 4;
}
return true;
}
public function main() {
int[] arithmetic = [1];
int[] primes = [];
final int lim = <int>1e6;
int n = 3;
while arithmetic.length() < lim {
int[] divs = divisors(n);
int len = divs.length();
if len == 2 {
primes.push(n);
arithmetic.push(n);
} else {
int sum = int:sum(...divs);
if sum % len == 0 { arithmetic.push(n); }
}
n += 1;
}
io:println("The first 100 arithmetic numbers are:");
foreach int i in 0...99 {
io:print(arithmetic[i].toString().padStart(4));
if (i + 1) % 10 == 0 { io:println(); }
}
foreach float f in [1e3, 1e4, 1e5, 1e6] {
int x = <int>f;
int last = arithmetic[x - 1];
string xc = commatize(x);
string lastc = commatize(last);
io:println("\nThe ", xc, "th arithmetic number is: ", lastc);
int pcount = findNearest(primes, last) + 1;
if !isPrime(last) { pcount -= 1; }
int comp = x - pcount - 1; // 1 is not composite
string compc = commatize(comp);
io:println(`"The count of such numbers <= ${lastc} which are composite is ${compc}.`);
}
}