BEGIN # find some Chowla numbers ( Chowla n = sum of divisors of n exclusing n and 1 ) #
    # returs the Chowla number of n #
    PROC chowla = ( INT n )INT:
         BEGIN
             INT sum := 0;
             FOR i FROM 2 WHILE i * i <= n DO
                 IF n MOD i = 0 THEN
                     INT j = n OVER i;
                     sum +:= i + IF i = j THEN 0 ELSE j FI
                 FI
             OD;
             sum
         END # chowla # ;

    FOR n TO 37 DO print( ( "chowla(", whole( n, 0 ), ") = ", whole( chowla( n ), 0 ), newline ) ) OD;

    INT count := 0, power := 100;
    FOR n FROM 2 TO 10 000 000 DO
        IF chowla( n ) = 0 THEN count +:= 1 FI;
        IF n MOD power = 0 THEN
            print( ( "There are ", whole( count, 0 ), " primes < ", whole( power, 0 ), newline ) );
            power *:= 10
        FI
    OD;
    count := 0;
    INT limit = 350 000 000;
    INT k    := 2, kk := 3;
    WHILE INT p = k * kk;
          p <= limit
    DO
        IF chowla( p ) = p - 1 THEN
            print( ( whole( p, 0 ), " is a perfect number", newline ) );
            count +:= 1
        FI;
        k := kk + 1; kk +:= k
    OD;
    print( ( "There are ", whole( count, 0 ), " perfect numbers < ", whole( limit, 0 ), newline ) )
END


chowla: function [n]-> sum remove remove factors n 1 n
countPrimesUpTo: function [limit][
    count: 1
    loop 3.. .step: 2 limit 'x [
        if zero? chowla x -> count: count + 1
    ]
    return count
]

loop 1..37 'i -> print [i "=>" chowla i]
print ""

loop [100 1000 10000 100000 1000000 10000000] 'lim [
    print ["primes up to" lim "=>" countPrimesUpTo lim]
]
print ""
print "perfect numbers up to 35000000:"
i: 2
while [i < 35000000][
    if (chowla i) = i - 1 -> print i
    i: i + 2
]


# syntax: GAWK -f CHOWLA_NUMBERS.AWK
# converted from Go
BEGIN {
    for (i=1; i<=37; i++) {
      printf("chowla(%2d) = %s\n",i,chowla(i))
    }
    printf("\nCount of primes up to:\n")
    count = 1
    limit = 1e7
    sieve(limit)
    power = 100
    for (i=3; i<limit; i+=2) {
      if (!c[i]) {
        count++
      }
      if (i == power-1) {
        printf("%10s = %s\n",commatize(power),commatize(count))
        power *= 10
      }
    }
    printf("\nPerfect numbers:")
    count = 0
    limit = 35000000
    k = 2
    kk = 3
    while (1) {
      if ((p = k * kk) > limit) {
        break
      }
      if (chowla(p) == p-1) {
        printf("  %s",commatize(p))
        count++
      }
      k = kk + 1
      kk += k
    }
    printf("\nThere are %d perfect numbers <= %s\n",count,commatize(limit))
    exit(0)
}
function chowla(n,  i,j,sum) {
    if (n < 1 || n != int(n)) {
      return sprintf("%s is invalid",n)
    }
    for (i=2; i*i<=n; i++) {
      if (n%i == 0) {
        j = n / i
        sum += (i == j) ? i : i + j
      }
    }
    return(sum+0)
}
function commatize(x,  num) {
    if (x < 0) {
      return "-" commatize(-x)
    }
    x = int(x)
    num = sprintf("%d.",x)
    while (num ~ /^[0-9][0-9][0-9][0-9]/) {
      sub(/[0-9][0-9][0-9][,.]/,",&",num)
    }
    sub(/\.$/,"",num)
    return(num)
}
function sieve(limit,  i,j) {
    for (i=1; i<=limit; i++) {
      c[i] = 0
    }
    for (i=3; i*3<limit; i+=2) {
      if (!c[i] && chowla(i) == 0) {
        for (j=3*i; j<limit; j+=2*i) {
          c[j] = 1
        }
      }
    }
}


#include <stdio.h>

unsigned chowla(const unsigned n) {
  unsigned sum = 0;
  for (unsigned i = 2, j; i * i <= n; i ++) if (n % i == 0) sum += i + (i == (j = n / i) ? 0 : j);
  return sum;
}

int main(int argc, char const *argv[]) {
  unsigned a;
  for (unsigned n = 1; n < 38; n ++) printf("chowla(%u) = %u\n", n, chowla(n));

  unsigned n, count = 0, power = 100;
  for (n = 2; n < 10000001; n ++) {
    if (chowla(n) == 0) count ++;
    if (n % power == 0) printf("There is %u primes < %u\n", count, power), power *= 10;
  }

  count = 0;
  unsigned limit = 350000000;
  unsigned k = 2, kk = 3, p;
  for ( ; ; ) {
    if ((p = k * kk) > limit) break;
    if (chowla(p) == p - 1) {
      printf("%d is a perfect number\n", p);
      count ++;
    }
    k = kk + 1; kk += k;
  }
  printf("There are %u perfect numbers < %u\n", count, limit);
  return 0;
}


using System;

namespace chowla_cs
{
    class Program
    {
        static int chowla(int n)
        {
            int sum = 0;
            for (int i = 2, j; i * i <= n; i++)
                if (n % i == 0) sum += i + (i == (j = n / i) ? 0 : j);
            return sum;
        }

        static bool[] sieve(int limit)
        {
            // True denotes composite, false denotes prime.
            // Only interested in odd numbers >= 3
            bool[] c = new bool[limit];
            for (int i = 3; i * 3 < limit; i += 2)
                if (!c[i] && (chowla(i) == 0))
                    for (int j = 3 * i; j < limit; j += 2 * i)
                        c[j] = true;
            return c;
        }

        static void Main(string[] args)
        {
            for (int i = 1; i <= 37; i++)
                Console.WriteLine("chowla({0}) = {1}", i, chowla(i));
            int count = 1, limit = (int)(1e7), power = 100;
            bool[] c = sieve(limit);
            for (int i = 3; i < limit; i += 2)
            {
                if (!c[i]) count++;
                if (i == power - 1)
                {
                    Console.WriteLine("Count of primes up to {0,10:n0} = {1:n0}", power, count);
                    power *= 10;
                }
            }

            count = 0; limit = 35000000;
            int k = 2, kk = 3, p;
            for (int i = 2; ; i++)
            {
                if ((p = k * kk) > limit) break;
                if (chowla(p) == p - 1)
                {
                    Console.WriteLine("{0,10:n0} is a number that is perfect", p);
                    count++;
                }
                k = kk + 1; kk += k;
            }
            Console.WriteLine("There are {0} perfect numbers <= 35,000,000", count);
            if (System.Diagnostics.Debugger.IsAttached) Console.ReadKey();
        }
    }
}


#include <vector>
#include <iostream>

using namespace std;

int chowla(int n)
{
	int sum = 0;
	for (int i = 2, j; i * i <= n; i++)
		if (n % i == 0) sum += i + (i == (j = n / i) ? 0 : j);
	return sum;
}

vector<bool> sieve(int limit)
{
	// True denotes composite, false denotes prime.
	// Only interested in odd numbers >= 3
	vector<bool> c(limit);
	for (int i = 3; i * 3 < limit; i += 2)
		if (!c[i] && (chowla(i) == 0))
			for (int j = 3 * i; j < limit; j += 2 * i)
				c[j] = true;
	return c;
}

int main()
{
	cout.imbue(locale(""));
	for (int i = 1; i <= 37; i++)
		cout << "chowla(" << i << ") = " << chowla(i) << "\n";
	int count = 1, limit = (int)(1e7), power = 100;
	vector<bool> c = sieve(limit);
	for (int i = 3; i < limit; i += 2)
	{
		if (!c[i]) count++;
		if (i == power - 1)
		{
			cout << "Count of primes up to " << power << " = "<< count <<"\n";
			power *= 10;
		}
	}

	count = 0; limit = 35000000;
	int k = 2, kk = 3, p;
	for (int i = 2; ; i++)
	{
		if ((p = k * kk) > limit) break;
		if (chowla(p) == p - 1)
		{
			cout << p << " is a number that is perfect\n";
			count++;
		}
		k = kk + 1; kk += k;
	}
	cout << "There are " << count << " perfect numbers <= 35,000,000\n";
	return 0;
}


% Chowla's function
chowla = proc (n: int) returns (int)
    sum: int := 0
    i: int := 2
    while i*i <= n do
        if n//i = 0 then
            sum := sum + i
            j: int := n/i
            if i ~= j then
                sum := sum + j
            end
        end
        i := i + 1
    end
    return(sum)
end chowla

% A number is prime iff chowla(n) is 0
prime = proc (n: int) returns (bool)
    return(chowla(n) = 0)
end prime

% A number is perfect iff chowla(n) equals n-1
perfect = proc (n: int) returns (bool)
    return(chowla(n) = n-1)
end perfect

start_up = proc ()
    LIMIT = 35000000
    po: stream := stream$primary_output()

    % Show chowla(1) through chowla(37)
    for i: int in int$from_to(1, 37) do
        stream$putl(po, "chowla(" || int$unparse(i) || ") = "
                        || int$unparse(chowla(i)))
    end

    % Count primes up to powers of 10
    pow10: int := 2        % start with 100
    primecount: int := 1   % assume 2 is prime, then test only odd numbers
    candidate: int := 3
    while pow10 <= 7 do
        if candidate >= 10**pow10 then
            stream$putl(po, "There are "
                        ||  int$unparse(primecount)
                        ||  " primes up to "
                        ||  int$unparse(10**pow10))
            pow10 := pow10 + 1
        end
        if prime(candidate) then primecount := primecount + 1 end
        candidate := candidate + 2
    end

    % Find perfect numbers up to 35 million
    perfcount: int := 0
    k: int := 2
    kk: int := 3
    while true do
        n: int := k * kk
        if n >= LIMIT then break end
        if perfect(n) then
            perfcount := perfcount + 1
            stream$putl(po, int$unparse(n) || " is a perfect number.")
        end
        k := kk + 1
        kk := kk + k
    end
    stream$putl(po, "There are " || int$unparse(perfcount) ||
                    " perfect numbers < 35,000,000.")
end start_up


include "cowgol.coh";

sub chowla(n: uint32): (sum: uint32) is
    sum := 0;
    var i: uint32 := 2;

    while i*i <= n loop
        if n % i == 0 then
            sum := sum + i;
            var j := n / i;
            if i != j then
                sum := sum + j;
            end if;
        end if;
        i := i + 1;
    end loop;
end sub;

var n: uint32 := 1;
while n <= 37 loop
    print("chowla(");
    print_i32(n);
    print(") = ");
    print_i32(chowla(n));
    print("\n");
    n := n + 1;
end loop;

n := 2;
var power: uint32 := 100;
var count: uint32 := 0;
while n <= 10000000 loop
    if chowla(n) == 0 then
        count := count + 1;
    end if;
    if n % power == 0 then
        print("There are ");
        print_i32(count);
        print(" primes < ");
        print_i32(power);
        print_nl();
        power := power * 10;
    end if;
    n := n + 1;
end loop;

count := 0;
const LIMIT := 35000000;
var k: uint32 := 2;
var kk: uint32 := 3;
loop
    n := k * kk;
    if n > LIMIT then break; end if;
    if chowla(n) == n-1 then
        print_i32(n);
        print(" is a perfect number.\n");
        count := count + 1;
    end if;
    k := kk + 1;
    kk := kk + k;
end loop;

print("There are ");
print_i32(count);
print(" perfect numbers < ");
print_i32(LIMIT);
print_nl();


import std.stdio;

int chowla(int n) {
    int sum;
    for (int i = 2, j; i * i <= n; ++i) {
        if (n % i == 0) {
            sum += i + (i == (j = n / i) ? 0 : j);
        }
    }
    return sum;
}

bool[] sieve(int limit) {
    // True denotes composite, false denotes prime.
    // Only interested in odd numbers >= 3
    auto c = new bool[limit];
    for (int i = 3; i * 3 < limit; i += 2) {
        if (!c[i] && (chowla(i) == 0)) {
            for (int j = 3 * i; j < limit; j += 2 * i) {
                c[j] = true;
            }
        }
    }
    return c;
}

void main() {
    foreach (i; 1..38) {
        writefln("chowla(%d) = %d", i, chowla(i));
    }
    int count = 1;
    int limit = cast(int)1e7;
    int power = 100;
    bool[] c = sieve(limit);
    for (int i = 3; i < limit; i += 2) {
        if (!c[i]) {
            count++;
        }
        if (i == power - 1) {
            writefln("Count of primes up to %10d = %d", power, count);
            power *= 10;
        }
    }

    count = 0;
    limit = 350_000_000;
    int k = 2;
    int kk = 3;
    int p;
    for (int i = 2; ; ++i) {
        p = k * kk;
        if (p > limit) {
            break;
        }
        if (chowla(p) == p - 1) {
            writefln("%10d is a number that is perfect", p);
            count++;
        }
        k = kk + 1;
        kk += k;
    }
    writefln("There are %d perfect numbers <= 35,000,000", count);
}


func chowla(n) {
    var sum = 0
    var i = 2
    var j = 0
    while i * i <= n {
        if n % i == 0 {
            j = n / i
            var app = if i == j {
                0
            } else {
                j
            }
            sum += i + app
        }
        i += 1
    }
    return sum
}

func sieve(limit) {
    var c = Array.Empty(limit)
    var i = 3
    while i * 3 < limit {
        if !c[i] && (chowla(i) == 0) {
            var j = 3 * i
            while j < limit {
                c[j] = true
                j += 2 * i
            }
        }
        i += 2
    }
    return c
}

for i in 1..37 {
    print("chowla(\(i)) = \(chowla(i))")
}

var count = 1
var limit = 10000000
var power = 100
var c = sieve(limit)

var i = 3
while i < limit {
    if !c[i] {
        count += 1
    }
    if i == power - 1 {
        print("Count of primes up to \(power) = \(count)")
        power *= 10
    }
    i += 2
}

count = 0
limit = 35000000
var k = 2
var kk = 3
var p
i = 2

while true {
    p = k * kk
    if p > limit {
        break
    }
    if chowla(p) == p - 1 {
        print("\(p) is a number that is perfect")
        count += 1
    }
    k = kk + 1
    kk += k
}

print("There are \(count) perfect numbers <= 35,000,000")


func chowla n . sum .
  sum = 0
  i = 2
  while i * i <= n
    if n mod i = 0
      j = n div i
      if i = j
        sum += i
      else
        sum += i + j
      .
    .
    i += 1
  .
.
func sieve . c[] .
  i = 3
  while i * 3 < len c[]
    if c[i] = 0
      call chowla i h
      if h = 0
        j = 3 * i
        while j < len c[]
          c[j] = 1
          j += 2 * i
        .
      .
    .
    i += 2
  .
.
func commatize n . s$ .
  s$[] = strchars n
  s$ = ""
  l = len s$[]
  for i range len s$[]
    if i > 0 and l mod 3 = 0
      s$ &= ","
    .
    l -= 1
    s$ &= s$[i]
  .
.
print "chowla number from 1 to 37"
for i = 1 to 37
  call chowla i h
  print "  " & i & ": " & h
.
func main . .
  print ""
  len c[] 10000000
  count = 1
  call sieve c[]
  power = 100
  i = 3
  while i < len c[]
    if c[i] = 0
      count += 1
    .
    if i = power - 1
      call commatize power p$
      call commatize count c$
      print "There are " & c$ & " primes up to " & p$
      power *= 10
    .
    i += 2
  .
  print ""
  limit = 35000000
  count = 0
  i = 2
  k = 2
  kk = 3
  repeat
    p = k * kk
    until p > limit
    call chowla p h
    if h = p - 1
      call commatize p s$
      print s$ & " is a perfect number"
      count += 1
    .
    k = kk + 1
    kk += k
    i += 1
  .
  call commatize limit s$
  print "There are " & count & " perfect mumbers up to " & s$
.
call main


USING: formatting fry grouping.extras io kernel math
math.primes.factors math.ranges math.statistics sequences
tools.memory.private ;
IN: rosetta-code.chowla-numbers

: chowla ( n -- m )
    dup 1 = [ 1 - ] [ [ divisors sum ] [ - 1 - ] bi ] if ;

: show-chowla ( n -- )
    [1,b] [ dup chowla "chowla(%02d) = %d\n" printf ] each ;

: count-primes ( seq -- )
    dup 0 prefix [ [ 1 + ] dip 2 <range> ] 2clump-map
    [ [ chowla zero? ] count ] map cum-sum
    [ [ commas ] [email protected] "Primes up to %s: %s\n" printf ] 2each ;

: show-perfect ( n -- )
    [ 2 3 ] dip '[ 2dup * dup _ > ] [
        dup [ chowla ] [ 1 - = ] bi
        [ commas "%s is perfect\n" printf ] [ drop ] if
        [ nip 1 + ] [ nip dupd + ] 2bi
    ] until 3drop ;

: chowla-demo ( -- )
    37 show-chowla nl { 100 1000 10000 100000 1000000 10000000 }
    count-primes nl 35e7 show-perfect ;

MAIN: chowla-demo


' Chowla_numbers

#include "string.bi"

Dim Shared As Long limite
limite = 10000000
Dim Shared As Boolean c(limite)
Dim As Long count, topenumprimo, a
count = 1
topenumprimo = 100
Dim As Longint p, k, kk, limitenumperfect
limitenumperfect = 35000000
k = 2: kk = 3

Declare Function chowla(Byval n As Longint) As Longint
Declare Sub sieve(Byval limite As Long, c() As Boolean)

Function chowla(Byval n As Longint) As Longint
    Dim As Long i, j, r
    i = 2
    Do While i * i <= n
        j = n \ i
        If n Mod i = 0 Then
            r += i
            If i <> j Then r += j
        End If
        i += 1
    Loop
    chowla = r
End Function

Sub sieve(Byval limite As Long, c() As Boolean)
    Dim As Long i, j
    Redim As Boolean c(limite - 1)
    i = 3
    Do While i * 3 < limite
        If Not c(i) Then
            If chowla(i) = false Then
                j = 3 * i
                Do While j < limite
                    c(j) = true
                    j += 2 * i
                Loop
            End If
        End If
        i += 2
    Loop
End Sub

Print "Chowla numbers"
For a = 1 To 37
    Print "chowla(" & Trim(Str(a)) & ") = " & Trim(Str(chowla(a)))
Next a

' Si chowla(n) = falso and n > 1 Entonces n es primo
Print: Print "Contando los numeros primos hasta: "
sieve(limite, c())
For a = 3 To limite - 1 Step 2
    If Not c(a) Then count += 1
    If a = topenumprimo - 1 Then
        Print Using "########## hay"; topenumprimo;
        Print count
        topenumprimo *= 10
    End If
Next a

' Si chowla(n) = n - 1 and n > 1 Entonces n es un número perfecto
Print: Print "Buscando numeros perfectos... "
count = 0
Do
    p = k * kk : If p > limitenumperfect Then Exit Do
    If chowla(p) = p - 1 Then
        Print Using "##########,# es un numero perfecto"; p
        count += 1
    End If
    k = kk + 1 : kk += k
Loop
Print: Print "Hay " & count & " numeros perfectos <= " & Format(limitenumperfect, "###############################,#")

Print: Print "Pulsa una tecla para salir"
Sleep
End


package main

import "fmt"

func chowla(n int) int {
    if n < 1 {
        panic("argument must be a positive integer")
    }
    sum := 0
    for i := 2; i*i <= n; i++ {
        if n%i == 0 {
            j := n / i
            if i == j {
                sum += i
            } else {
                sum += i + j
            }
        }
    }
    return sum
}

func sieve(limit int) []bool {
    // True denotes composite, false denotes prime.
    // Only interested in odd numbers >= 3
    c := make([]bool, limit)
    for i := 3; i*3 < limit; i += 2 {
        if !c[i] && chowla(i) == 0 {
            for j := 3 * i; j < limit; j += 2 * i {
                c[j] = true
            }
        }
    }
    return c
}

func commatize(n int) string {
    s := fmt.Sprintf("%d", n)
    le := len(s)
    for i := le - 3; i >= 1; i -= 3 {
        s = s[0:i] + "," + s[i:]
    }
    return s
}

func main() {
    for i := 1; i <= 37; i++ {
        fmt.Printf("chowla(%2d) = %d\n", i, chowla(i))
    }
    fmt.Println()

    count := 1
    limit := int(1e7)
    c := sieve(limit)
    power := 100
    for i := 3; i < limit; i += 2 {
        if !c[i] {
            count++
        }
        if i == power-1 {
            fmt.Printf("Count of primes up to %-10s = %s\n", commatize(power), commatize(count))
            power *= 10
        }
    }

    fmt.Println()
    count = 0
    limit = 35000000
    for i := uint(2); ; i++ {
        p := 1 << (i - 1) * (1<<i - 1) // perfect numbers must be of this form
        if p > limit {
            break
        }
        if chowla(p) == p-1 {
            fmt.Printf("%s is a perfect number\n", commatize(p))
            count++
        }
    }
    fmt.Println("There are", count, "perfect numbers <= 35,000,000")
}


class Chowla {
    static int chowla(int n) {
        if (n < 1) throw new RuntimeException("argument must be a positive integer")
        int sum = 0
        int i = 2
        while (i * i <= n) {
            if (n % i == 0) {
                int j = (int) (n / i)
                sum += (i == j) ? i : i + j
            }
            i++
        }
        return sum
    }

    static boolean[] sieve(int limit) {
        // True denotes composite, false denotes prime.
        // Only interested in odd numbers >= 3
        boolean[] c = new boolean[limit]
        for (int i = 3; i < limit / 3; i += 2) {
            if (!c[i] && chowla(i) == 0) {
                for (int j = 3 * i; j < limit; j += 2 * i) {
                    c[j] = true
                }
            }
        }
        return c
    }

    static void main(String[] args) {
        for (int i = 1; i <= 37; i++) {
            printf("chowla(%2d) = %d\n", i, chowla(i))
        }
        println()

        int count = 1
        int limit = 10_000_000
        boolean[] c = sieve(limit)
        int power = 100
        for (int i = 3; i < limit; i += 2) {
            if (!c[i]) {
                count++
            }
            if (i == power - 1) {
                printf("Count of primes up to %,10d = %,7d\n", power, count)
                power *= 10
            }
        }
        println()

        count = 0
        limit = 35_000_000
        int i = 2
        while (true) {
            int p = (1 << (i - 1)) * ((1 << i) - 1) // perfect numbers must be of this form
            if (p > limit) break
            if (chowla(p) == p - 1) {
                printf("%,d is a perfect number\n", p)
                count++
            }
            i++
        }
        printf("There are %,d perfect numbers <= %,d\n", count, limit)
    }
}


*        Closest Pair Problem      10/03/2017
CLOSEST  CSECT
         USING  CLOSEST,R13        base register
         B      72(R15)            skip savearea
         DC     17F'0'             savearea
         STM    R14,R12,12(R13)    save previous context
         ST     R13,4(R15)         link backward
         ST     R15,8(R13)         link forward
         LR     R13,R15            set addressability
         LA     R6,1               i=1
         LA     R7,2               j=2
         BAL    R14,DDCALC         dd=(px(i)-px(j))^2+(py(i)-py(j))^2
         BAL    R14,DDSTORE        ddmin=dd; ii=i; jj=j
         LA     R6,1               i=1
       DO WHILE=(C,R6,LE,N)        do i=1 to n
         LA     R7,1                 j=1
       DO WHILE=(C,R7,LE,N)          do j=1 to n
         BAL    R14,DDCALC         dd=(px(i)-px(j))^2+(py(i)-py(j))^2
       IF CP,DD,GT,=P'0' THEN          if dd>0 then
       IF CP,DD,LT,DDMIN THEN            if dd<ddmin then
         BAL    R14,DDSTORE                ddmin=dd; ii=i; jj=j
       ENDIF    ,                        endif
       ENDIF    ,                      endif
         LA     R7,1(R7)               j++
       ENDDO    ,                    enddo j
         LA     R6,1(R6)             i++
       ENDDO    ,                  enddo i
         ZAP    WPD,DDMIN          ddmin
         DP     WPD,=PL8'2'        ddmin/2
         ZAP    SQRT2,WPD(8)       sqrt2=ddmin/2
         ZAP    SQRT1,DDMIN        sqrt1=ddmin
       DO WHILE=(CP,SQRT1,NE,SQRT2)  do while sqrt1<>sqrt2
         ZAP    SQRT1,SQRT2          sqrt1=sqrt2
         ZAP    WPD,DDMIN            ddmin
         DP     WPD,SQRT1            /sqrt1
         ZAP    WP1,WPD(8)           ddmin/sqrt1
         AP     WP1,SQRT1            +sqrt1
         ZAP    WPD,WP1              ~
         DP     WPD,=PL8'2'          /2
         ZAP    SQRT2,WPD(8)         sqrt2=(sqrt1+(ddmin/sqrt1))/2
       ENDDO    ,                  enddo while
         MVC    PG,=CL80'the minimum distance '
         ZAP    WP1,SQRT2          sqrt2
         BAL    R14,EDITPK         edit
         MVC    PG+21(L'WC),WC     output
         XPRNT  PG,L'PG            print buffer
         XPRNT  =CL22'is between the points:',22
         MVC    PG,PGP             init buffer
         L      R1,II              ii
         SLA    R1,4               *16
         LA     R4,PXY-16(R1)      @px(ii)
         MVC    WP1,0(R4)          px(ii)
         BAL    R14,EDITPK         edit
         MVC    PG+3(L'WC),WC      output
         MVC    WP1,8(R4)          py(ii)
         BAL    R14,EDITPK         edit
         MVC    PG+21(L'WC),WC     output
         XPRNT  PG,L'PG            print buffer
         MVC    PG,PGP             init buffer
         L      R1,JJ              jj
         SLA    R1,4               *16
         LA     R4,PXY-16(R1)      @px(jj)
         MVC    WP1,0(R4)          px(jj)
         BAL    R14,EDITPK         edit
         MVC    PG+3(L'WC),WC      output
         MVC    WP1,8(R4)          py(jj)
         BAL    R14,EDITPK         edit
         MVC    PG+21(L'WC),WC     output
         XPRNT  PG,L'PG            print buffer
         L      R13,4(0,R13)       restore previous savearea pointer
         LM     R14,R12,12(R13)    restore previous context
         XR     R15,R15            rc=0
         BR     R14                exit
DDCALC   EQU    *             ---- dd=(px(i)-px(j))^2+(py(i)-py(j))^2
         LR     R1,R6              i
         SLA    R1,4               *16
         LA     R4,PXY-16(R1)      @px(i)
         LR     R1,R7              j
         SLA    R1,4               *16
         LA     R5,PXY-16(R1)      @px(j)
         ZAP    WP1,0(8,R4)        px(i)
         ZAP    WP2,0(8,R5)        px(j)
         SP     WP1,WP2            px(i)-px(j)
         ZAP    WPS,WP1            =
         MP     WP1,WPS            (px(i)-px(j))*(px(i)-px(j))
         ZAP    WP2,8(8,R4)        py(i)
         ZAP    WP3,8(8,R5)        py(j)
         SP     WP2,WP3            py(i)-py(j)
         ZAP    WPS,WP2            =
         MP     WP2,WPS            (py(i)-py(j))*(py(i)-py(j))
         AP     WP1,WP2            (px(i)-px(j))^2+(py(i)-py(j))^2
         ZAP    DD,WP1             dd=(px(i)-px(j))^2+(py(i)-py(j))^2
         BR     R14           ---- return
DDSTORE  EQU    *             ---- ddmin=dd; ii=i; jj=j
         ZAP    DDMIN,DD           ddmin=dd
         ST     R6,II              ii=i
         ST     R7,JJ              jj=j
         BR     R14           ---- return
EDITPK   EQU    *             ----
         MVC    WM,MASK            set mask
         EDMK   WM,WP1             edit and mark
         BCTR   R1,0               -1
         MVC    0(1,R1),WM+17      set sign
         MVC    WC,WM              len17<-len18
         BR     R14           ---- return
N        DC     A((PGP-PXY)/16)
PXY      DC     PL8'0.654682',PL8'0.925557',PL8'0.409382',PL8'0.619391'
         DC     PL8'0.891663',PL8'0.888594',PL8'0.716629',PL8'0.996200'
         DC     PL8'0.477721',PL8'0.946355',PL8'0.925092',PL8'0.818220'
         DC     PL8'0.624291',PL8'0.142924',PL8'0.211332',PL8'0.221507'
         DC     PL8'0.293786',PL8'0.691701',PL8'0.839186',PL8'0.728260'
PGP      DC     CL80'  [+xxxxxxxxx.xxxxxx,+xxxxxxxxx.xxxxxx]'
MASK     DC     C' ',7X'20',X'21',X'20',C'.',6X'20',C'-'  CL18 15num
II       DS     F
JJ       DS     F
DD       DS     PL8
DDMIN    DS     PL8
SQRT1    DS     PL8
SQRT2    DS     PL8
WP1      DS     PL8
WP2      DS     PL8
WP3      DS     PL8
WPS      DS     PL8
WPD      DS     PL16
WM       DS     CL18
WC       DS     CL17
PG       DS     CL80
         YREGS
         END    CLOSEST


import Control.Concurrent       (setNumCapabilities)
import Control.Monad.Par        (runPar, get, spawnP)
import Control.Monad            (join, (>=>))
import Data.List.Split          (chunksOf)
import Data.List                (intercalate, mapAccumL, genericTake, genericDrop)
import Data.Bifunctor           (bimap)
import GHC.Conc                 (getNumProcessors)
import Math.NumberTheory.Primes (factorise, unPrime)
import Text.Printf              (printf)

chowla :: Word -> Word
chowla 1 = 0
chowla n = f n
  where
    f = (-) =<< pred . product . fmap sumFactor . factorise
    sumFactor (n, e) = foldr (\p s -> s + unPrime n^p) 1 [1..e]

chowlas :: [Word] -> [(Word, Word)]
chowlas [] = []
chowlas xs = runPar $ join <$>
  (mapM (spawnP . fmap ((,) <*> chowla)) >=> mapM get) (chunksOf (10^6) xs)

chowlaPrimes :: [(Word, Word)] -> (Word, Word) -> (Word, Word)
chowlaPrimes chowlas range = (count chowlas, snd range)
  where
    isPrime (1, n) = False
    isPrime (_, n) = n == 0
    count = fromIntegral . length . filter isPrime . between range
    between (min, max) = genericTake (max - pred min) . genericDrop (pred min)

chowlaPerfects :: [(Word, Word)] -> [Word]
chowlaPerfects = fmap fst . filter isPerfect
  where
    isPerfect (1, _) = False
    isPerfect (n, c) = c == pred n

commas :: (Show a, Integral a) => a -> String
commas = reverse . intercalate "," . chunksOf 3 . reverse . show

main :: IO ()
main = do
  cores <- getNumProcessors
  setNumCapabilities cores
  printf "Using %d cores\n" cores

  mapM_ (uncurry (printf "chowla(%2d) = %d\n")) $ take 37 allChowlas
  mapM_ (uncurry (printf "There are %8s primes < %10s\n"))
    (chowlaP
       [ (1, 10^2)
       , (succ $ 10^2, 10^3)
       , (succ $ 10^3, 10^4)
       , (succ $ 10^4, 10^5)
       , (succ $ 10^5, 10^6)
       , (succ $ 10^6, 10^7) ])

  mapM_ (printf "%10s is a perfect number.\n" . commas) perfects
  printf "There are %2d perfect numbers < 35,000,000\n" $ length perfects
  where
    chowlaP = fmap (bimap commas commas) . snd
      . mapAccumL (\total (count, max) -> (total + count, (total + count, max))) 0
      . fmap (chowlaPrimes $ take (10^7) allChowlas)
    perfects = chowlaPerfects allChowlas
    allChowlas = chowlas [1..35*10^6]


with Ada.Numerics.Generic_Elementary_Functions;
with Ada.Text_IO;

procedure Closest is
   package Math is new Ada.Numerics.Generic_Elementary_Functions (Float);

   Dimension : constant := 2;
   type Vector is array (1 .. Dimension) of Float;
   type Matrix is array (Positive range <>) of Vector;

   -- calculate the distance of two points
   function Distance (Left, Right : Vector) return Float is
      Result : Float := 0.0;
      Offset : Natural := 0;
   begin
      loop
         Result := Result + (Left(Left'First + Offset) - Right(Right'First + Offset))**2;
         Offset := Offset + 1;
         exit when Offset >= Left'Length;
      end loop;
      return Math.Sqrt (Result);
   end Distance;

   -- determine the two closest points inside a cloud of vectors
   function Get_Closest_Points (Cloud : Matrix) return Matrix is
      Result : Matrix (1..2);
      Min_Distance : Float;
   begin
      if Cloud'Length(1) < 2 then
         raise Constraint_Error;
      end if;
      Result := (Cloud (Cloud'First), Cloud (Cloud'First + 1));
      Min_Distance := Distance (Cloud (Cloud'First), Cloud (Cloud'First + 1));
      for I in Cloud'First (1) .. Cloud'Last(1) - 1 loop
         for J in I + 1 .. Cloud'Last(1) loop
            if Distance (Cloud (I), Cloud (J)) < Min_Distance then
               Min_Distance := Distance (Cloud (I), Cloud (J));
               Result := (Cloud (I), Cloud (J));
            end if;
         end loop;
      end loop;
      return Result;
   end Get_Closest_Points;

   Test_Cloud : constant Matrix (1 .. 10) := ( (5.0, 9.0),  (9.0, 3.0),
                                               (2.0, 0.0),  (8.0, 4.0),
                                               (7.0, 4.0),  (9.0, 10.0),
                                               (1.0, 9.0),  (8.0, 2.0),
                                               (0.0, 10.0), (9.0, 6.0));
   Closest_Points : Matrix := Get_Closest_Points (Test_Cloud);

   Second_Test : constant Matrix (1 .. 10) := ( (0.654682, 0.925557), (0.409382, 0.619391),
                                                (0.891663, 0.888594), (0.716629,   0.9962),
                                                (0.477721, 0.946355), (0.925092,  0.81822),
                                                (0.624291, 0.142924), (0.211332, 0.221507),
                                                (0.293786, 0.691701), (0.839186,  0.72826));
   Second_Points : Matrix := Get_Closest_Points (Second_Test);
begin
   Ada.Text_IO.Put_Line ("Closest Points:");
   Ada.Text_IO.Put_Line ("P1: " & Float'Image (Closest_Points (1) (1)) & " " & Float'Image (Closest_Points (1) (2)));
   Ada.Text_IO.Put_Line ("P2: " & Float'Image (Closest_Points (2) (1)) & " " & Float'Image (Closest_Points (2) (2)));
   Ada.Text_IO.Put_Line ("Distance: " & Float'Image (Distance (Closest_Points (1), Closest_Points (2))));
   Ada.Text_IO.Put_Line ("Closest Points 2:");
   Ada.Text_IO.Put_Line ("P1: " & Float'Image (Second_Points (1) (1)) & " " & Float'Image (Second_Points (1) (2)));
   Ada.Text_IO.Put_Line ("P2: " & Float'Image (Second_Points (2) (1)) & " " & Float'Image (Second_Points (2) (2)));
   Ada.Text_IO.Put_Line ("Distance: " & Float'Image (Distance (Second_Points (1), Second_Points (2))));
end Closest;


chowla=: >: -~ >:@#.~/.~&.q:     NB. sum of factors - (n + 1)

intsbelow=: (2 }. i.)"0
countPrimesbelow=: +/@(0 = chowla)@intsbelow
findPerfectsbelow=: (#~ <: = chowla)@intsbelow


public class Chowla {

    public static void main(String[] args) {
        int[] chowlaNumbers = findChowlaNumbers(37);
        for (int i = 0; i < chowlaNumbers.length; i++) {
            System.out.printf("chowla(%d) = %d%n", (i+1), chowlaNumbers[i]);
        }
        System.out.println();

        int[][] primes = countPrimes(100, 10_000_000);
        for (int i = 0; i < primes.length; i++) {
            System.out.printf(Locale.US, "There is %,d primes up to %,d%n", primes[i][1], primes[i][0]);
        }
        System.out.println();

        int[] perfectNumbers = findPerfectNumbers(35_000_000);
        for (int i = 0; i < perfectNumbers.length; i++) {
            System.out.printf("%d is a perfect number%n", perfectNumbers[i]);
        }
        System.out.printf(Locale.US, "There are %d perfect numbers < %,d%n", perfectNumbers.length, 35_000_000);
    }

    public static int chowla(int n) {
        if (n < 0) throw new IllegalArgumentException("n is not positive");
        int sum = 0;
        for (int i = 2, j; i * i <= n; i++)
            if (n % i == 0) sum += i + (i == (j = n / i) ? 0 : j);
        return sum;
    }

    protected static int[][] countPrimes(int power, int limit) {
        int count = 0;
        int[][] num = new int[countMultiplicity(limit, power)][2];
        for (int n = 2, i=0;  n <= limit; n++) {
            if (chowla(n) == 0) count++;
            if (n % power == 0) {
                num[i][0] = power;
                num[i][1] = count;
                i++;
                power *= 10;
            }
        }
        return num;
    }

    protected static int countMultiplicity(int limit, int start) {
        int count = 0;
        int cur = limit;
        while(cur >= start) {
            count++;
            cur = cur/10;
        }
        return count;
    }

    protected static int[] findChowlaNumbers(int limit) {
        int[] num = new int[limit];
        for (int i = 0; i < limit; i++) {
            num[i] = chowla(i+1);
        }
        return num;
    }

    protected static int[] findPerfectNumbers(int limit) {
        int count = 0;
        int[] num = new int[count];

        int k = 2, kk = 3, p;
        while ((p = k * kk) < limit) {
            if (chowla(p) == p - 1) {
                num = increaseArr(num);
                num[count++] = p;
            }
            k = kk + 1;
            kk += k;
        }
        return num;
    }

    private static int[] increaseArr(int[] arr) {
        int[] tmp = new int[arr.length + 1];
        System.arraycopy(arr, 0, tmp, 0, arr.length);
        return tmp;
    }
}


ClosestPair(points){
	if (points.count() <= 3)
		return bruteForceClosestPair(points)
	split := xSplit(Points)
	LP := split.1			; left points
	LD := ClosestPair(LP)		; recursion : left closest pair
	RP := split.2			; right points
	RD := ClosestPair(RP)		; recursion : right closest pair
	minD := min(LD, RD)		; minimum of LD & RD
	xmin := Split.3 - minD		; strip left boundary
	xmax := Split.3 + minD		; strip right boundary
	S := strip(points, xmin, xmax)
	if (s.count()>=2)
	{
		SD := ClosestPair(S)	; recursion : strip closest pair
		return min(SD, minD)
	}
	return minD
}
;---------------------------------------------------------------
strip(points, xmin, xmax){
	strip:=[]
	for i, coord in points
		if (coord.1 >= xmin) && (coord.1 <= xmax)
			strip.push([coord.1, coord.2])
	return strip
}
;---------------------------------------------------------------
bruteForceClosestPair(points){
	minD := []
	loop, % points.count()-1{
		p1 := points.RemoveAt(1)
		loop, % points.count(){
			p2 := points[A_Index]
			d := dist(p1, p2)
			minD.push(d)
		}
	}
	return min(minD*)
}
;---------------------------------------------------------------
dist(p1, p2){
	return Sqrt((p2.1-p1.1)**2 + (p2.2-p1.2)**2)
}
;---------------------------------------------------------------
xSplit(Points){
	xL := [], xR := []
	p := xSort(Points)
	Loop % Ceil(p.count()/2)
		xL.push(p.RemoveAt(1))
	while p.count()
		xR.push(p.RemoveAt(1))
	mid := (xL[xl.count(),1] + xR[1,1])/2
	return [xL, xR, mid]
}
;---------------------------------------------------------------
xSort(Points){
	S := [], Res :=[]
	for i, coord in points
		S[coord.1, coord.2] := true
	for x, coord in S
		for y, v in coord
			res.push([x, y])
	return res
}
;---------------------------------------------------------------


def add(stream): reduce stream as $x (0; . + $x);

# input should be an integer
def commatize:
  def digits: tostring | explode | reverse;
  if . == null then ""
  elif . < 0 then "-" + ((- .) | commatize)
  else [foreach digits[] as $d (-1; .+1;
          # "," is 44
          (select(. > 0 and . % 3 == 0)|44), $d)]
  | reverse
  | implode
  end;

def count(stream): reduce stream as $i (0; . + 1);

def lpad($len): tostring | ($len - length) as $l | (" " * $l)[:$l] + .;

# To take advantage of gojq's arbitrary-precision integer arithmetic:
def power($b): . as $in | reduce range(0;$b) as $i (1; . * $in);

# unordered
def proper_divisors:
  . as $n
  | if $n > 1 then 1,
      ( range(2; 1 + (sqrt|floor)) as $i
        | if ($n % $i) == 0 then $i,
            (($n / $i) | if . == $i then empty else . end)
         else empty
	 end)
    else empty
    end;

def chowla:
  if . == 1 then 0
  else add(proper_divisors) - 1
  end;

# Input: a positive integer
def is_chowla_prime:
  . > 1 and chowla == 0;

# In the interests of green(er) computing ...
def chowla_primes($n):
  2, range(3; $n; 2) | select(is_chowla_prime);

def report_chowla_primes:
  reduce range(2; 10000000) as $i (null;
    if $i | is_chowla_prime
    then if $i < 10000000 then .[7] += 1 else . end
    |    if $i <  1000000 then .[6] += 1 else . end
    |    if $i <   100000 then .[5] += 1 else . end
    |    if $i <    10000 then .[4] += 1 else . end
    |    if $i <     1000 then .[3] += 1 else . end
    |    if $i <      100 then .[2] += 1 else . end
    else . end)
  | (range(2;8) as $i
  |  "10 ^ \($i) \(.[$i]|commatize|lpad(16))") ;

def is_chowla_perfect:
  (. > 1) and (chowla == . - 1);

def task:
  "  n\("chowla"|lpad(16))",
  (range(1;38) | "\(lpad(3)): \(chowla|lpad(10))"),
  "\n  n          \("Primes < n"|lpad(10))",
  report_chowla_primes,
#  "\nPerfect numbers up to 35e6",
#  (range(1; 35e6) | select(is_chowla_perfect) | commatize)
""
;

task


using Primes, Formatting

function chowla(n)
    if n < 1
        throw("Chowla function argument must be positive")
    elseif n < 4
        return zero(n)
    else
        f = [one(n)]
        for (p,e) in factor(n)
            f = reduce(vcat, [f*p^j for j in 1:e], init=f)
        end
        return sum(f) - one(n) - n
    end
end

function countchowlas(n, asperfect=false, verbose=false)
    count = 0
    for i in 2:n  # 1 is not prime or perfect so skip
        chow = chowla(i)
        if (asperfect && chow == i - 1) || (!asperfect && chow == 0)
            count += 1
            verbose && println("The number $(format(i, commas=true)) is ", asperfect ? "perfect." : "prime.")
        end
    end
    count
end

function testchowla()
    println("The first 37 chowla numbers are:")
    for i in 1:37
        println("Chowla($i) is ", chowla(i))
    end
    for i in [100, 1000, 10000, 100000, 1000000, 10000000]
        println("The count of the primes up to $(format(i, commas=true)) is $(format(countchowlas(i), commas=true))")
    end
    println("The count of perfect numbers up to 35,000,000 is $(countchowlas(35000000, true, true)).")
end

testchowla()


// Version 1.3.21

fun chowla(n: Int): Int {
    if (n < 1) throw RuntimeException("argument must be a positive integer")
    var sum = 0
    var i = 2
    while (i * i <= n) {
        if (n % i == 0) {
            val j = n / i
            sum += if (i == j) i else i + j
        }
        i++
    }
    return sum
}

fun sieve(limit: Int): BooleanArray {
    // True denotes composite, false denotes prime.
    // Only interested in odd numbers >= 3
    val c = BooleanArray(limit)
    for (i in 3 until limit / 3 step 2) {
        if (!c[i] && chowla(i) == 0) {
            for (j in 3 * i until limit step 2 * i) c[j] = true
        }
    }
    return c
}

fun main() {
    for (i in 1..37) {
        System.out.printf("chowla(%2d) = %d\n", i, chowla(i))
    }
    println()

    var count = 1
    var limit = 10_000_000
    val c = sieve(limit)
    var power = 100
    for (i in 3 until limit step 2) {
        if (!c[i]) count++
        if (i == power - 1) {
            System.out.printf("Count of primes up to %,-10d = %,d\n", power, count)
            power *= 10
        }
    }

    println()
    count = 0
    limit = 35_000_000
    var i = 2
    while (true) {
        val p = (1 shl (i - 1)) * ((1 shl i) - 1) // perfect numbers must be of this form
        if (p > limit) break
        if (chowla(p) == p - 1) {
            System.out.printf("%,d is a perfect number\n", p)
            count++
        }
        i++
    }
    println("There are $count perfect numbers <= 35,000,000")
}


function chowla(n)
    local sum = 0
    local i = 2
    local j = 0
    while i * i <= n do
        if n % i == 0 then
            j = math.floor(n / i)
            sum = sum + i
            if i ~= j then
                sum = sum + j
            end
        end
        i = i + 1
    end
    return sum
end

function sieve(limit)
    -- True denotes composite, false denotes prime.
    -- Only interested in odd numbers >= 3
    local c = {}
    local i = 3
    while i * 3 < limit do
        if not c[i] and (chowla(i) == 0) then
            local j = 3 * i
            while j < limit do
                c[j] = true
                j = j + 2 * i
            end
        end
        i = i + 2
    end
    return c
end

function main()
    for i = 1, 37 do
        print(string.format("chowla(%d) = %d", i, chowla(i)))
    end
    local count = 1
    local limit = math.floor(1e7)
    local power = 100
    local c = sieve(limit)
    local i = 3
    while i < limit do
        if not c[i] then
            count = count + 1
        end
        if i == power - 1 then
            print(string.format("Count of primes up to %10d = %d", power, count))
            power = power * 10
        end
        i = i + 2
    end

    count = 0
    limit = 350000000
    local k = 2
    local kk = 3
    local p = 0
    i = 2
    while true do
        p = k * kk
        if p > limit then
            break
        end
        if chowla(p) == p - 1 then
            print(string.format("%10d is a number that is perfect", p))
            count = count + 1
        end
        k = kk + 1
        kk = kk + k
        i = i + 1
    end
    print(string.format("There are %d perfect numbers <= 35,000,000", count))
end

main()


            NORMAL MODE IS INTEGER

            INTERNAL FUNCTION(N)
            ENTRY TO CHOWLA.
            SUM = 0
            THROUGH LOOP, FOR I=2, 1, I*I.G.N
            J = N/I
            WHENEVER J*I.E.N
                SUM = SUM + I
                WHENEVER I.NE.J, SUM = SUM + J
            END OF CONDITIONAL
LOOP        CONTINUE
            FUNCTION RETURN SUM
            END OF FUNCTION

            VECTOR VALUES CHWFMT = $7HCHOWLA(,I2,4H) = ,I2*$
            THROUGH CH37, FOR CH=1, 1, CH.G.37
CH37        PRINT FORMAT CHWFMT, CH, CHOWLA.(CH)

            VECTOR VALUES PRIMES =
          0          $10HTHERE ARE ,I6,S1,13HPRIMES BELOW ,I8*$

            POWER = 100
            COUNT = 0
            THROUGH PRM, FOR CH=2, 1, CH.G.10000000
            WHENEVER CHOWLA.(CH).E.0, COUNT = COUNT + 1
            WHENEVER (CH/POWER)*POWER.E.CH
                PRINT FORMAT PRIMES, COUNT, POWER
                POWER = POWER * 10
PRM         END OF CONDITIONAL

            COUNT = 0
            LIMIT = 35000000
            VECTOR VALUES PERFCT = $I8,S1,20HIS A PERFECT NUMBER.*$
            VECTOR VALUES PRFCNT =
          0     $10HTHERE ARE ,I1,S1,22HPERFECT NUMBERS BELOW ,I8*$
            K = 2
            KK = 3
LOOP        CH = K * KK
            WHENEVER CH.G.LIMIT, TRANSFER TO DONE
            WHENEVER CHOWLA.(CH).E.CH-1
                 PRINT FORMAT PERFCT, CH
                 COUNT = COUNT + 1
            END OF CONDITIONAL
            K = KK + 1
            KK = KK + K
            TRANSFER TO LOOP

DONE        PRINT FORMAT PRFCNT, COUNT, LIMIT

            END OF PROGRAM


ChowlaFunction := n -> NumberTheory:-SumOfDivisors(n) - n - 1;

PrintChowla := proc(n::posint) local i;
printf("Integer : Chowla Number\n");
for i to n do
  printf("%d  :  %d\n", i, ChowlaFunction(i));
end do;
end proc:

countPrimes := n -> nops([ListTools[SearchAll](0, map(ChowlaFunction, [seq(1 .. n)]))]);

findPerfect := proc(n::posint) local to_check, found, k;
to_check := map(ChowlaFunction, [seq(1 .. n)]);
found := [];
for k to n do
  if to_check(k) = k - 1 then
    found := [found, k];
  end if;
end do;
end proc:

PrintChowla(37);
countPrimes(100);
countPrimes(1000);
countPrimes(10000);
countPrimes(100000);
countPrimes(1000000);
countPrimes(10000000);
findPerfect(35000000)


import strformat
import strutils

func chowla(n: uint64): uint64 =
  var sum = 0u64
  var i = 2u64
  var j: uint64
  while i * i <= n:
    if n mod i == 0:
      j = n div i
      sum += i
      if i != j:
        sum += j
    inc i
  sum

for n in 1u64..37:
  echo &"chowla({n}) = {chowla(n)}"

var count = 0
var power = 100u64
for n in 2u64..10_000_000:
  if chowla(n) == 0:
    inc count
  if n mod power == 0:
    echo &"There are {insertSep($count, ','):>7} primes < {insertSep($power, ','):>10}"
    power *= 10

count = 0
const limit = 350_000_000u64
var k = 2u64
var kk = 3u64
var p: uint64
while true:
  p = k * kk
  if p > limit:
    break
  if chowla(p) == p - 1:
    echo &"{insertSep($p, ','):>10} is a perfect number"
    inc count
  k = kk + 1
  kk += k
echo &"There are {count} perfect numbers < {insertSep($limit, ',')}"


class Segment
{
    public Segment(PointF p1, PointF p2)
    {
        P1 = p1;
        P2 = p2;
    }

    public readonly PointF P1;
    public readonly PointF P2;

    public float Length()
    {
        return (float)Math.Sqrt(LengthSquared());
    }

    public float LengthSquared()
    {
        return (P1.X - P2.X) * (P1.X - P2.X)
            + (P1.Y - P2.Y) * (P1.Y - P2.Y);
    }
}


program Chowla_numbers;

{$IFDEF FPC}
  {$MODE Delphi}
{$ELSE}
  {$APPTYPE CONSOLE}
{$ENDIF}

uses
  SysUtils
  {$IFDEF FPC}
    ,StrUtils{for Numb2USA}
  {$ENDIF}
;

{$IFNDEF FPC}
function Numb2USA(const S: string): string;
var
  I, NA: Integer;
begin
  I := Length(S);
  Result := S;
  NA := 0;
  while (I > 0) do
  begin
    if ((Length(Result) - I + 1 - NA) mod 3 = 0) and (I <> 1) then
    begin
      Insert(',', Result, I);
      Inc(NA);
    end;
    Dec(I);
  end;
end;
{$ENDIF}

function Chowla(n: NativeUint): NativeUint;
var
  Divisor, Quotient: NativeUint;
begin
  result := 0;
  Divisor := 2;
  while sqr(Divisor) < n do
  begin
    Quotient := n div Divisor;
    if Quotient * Divisor = n then
      inc(result, Divisor + Quotient);
    inc(Divisor);
  end;
  if sqr(Divisor) = n then
    inc(result, Divisor);
end;

procedure Count10Primes(Limit: NativeUInt);
var
  n, i, cnt: integer;
begin
  writeln;
  writeln(' primes til |     count');
  i := 100;
  n := 2;
  cnt := 0;
  repeat
    repeat
      // Ord (true) = 1 ,Ord (false) = 0
      inc(cnt, ORD(chowla(n) = 0));
      inc(n);
    until n > i;
    writeln(Numb2USA(IntToStr(i)): 12, '|', Numb2USA(IntToStr(cnt)): 10);
    i := i * 10;
  until i > Limit;
end;

procedure CheckPerf;
var
  k, kk, p, cnt, limit: NativeInt;
begin
  writeln;
  writeln(' number that is perfect');
  cnt := 0;
  limit := 35000000;
  k := 2;
  kk := 3;
  repeat
    p := k * kk;
    if p > limit then
      BREAK;
    if chowla(p) = (p - 1) then
    begin
      writeln(Numb2USA(IntToStr(p)): 12);
      inc(cnt);
    end;
    k := kk + 1;
    inc(kk, k);
  until false;
end;

var
  I: integer;

begin
  for I := 2 to 37 do
    writeln('chowla(', I: 2, ') =', chowla(I): 3);
  Count10Primes(10 * 1000 * 1000);
  CheckPerf;
end.


/*
	Author: Kevin Bacon
	Date: 04/03/2014
	Task: Closest-pair problem
*/

#include <iostream>
#include <vector>
#include <utility>
#include <cmath>
#include <random>
#include <chrono>
#include <algorithm>
#include <iterator>

typedef std::pair<double, double> point_t;
typedef std::pair<point_t, point_t> points_t;

double distance_between(const point_t& a, const point_t& b) {
	return std::sqrt(std::pow(b.first - a.first, 2)
		+ std::pow(b.second - a.second, 2));
}

std::pair<double, points_t> find_closest_brute(const std::vector<point_t>& points) {
	if (points.size() < 2) {
		return { -1, { { 0, 0 }, { 0, 0 } } };
	}
	auto minDistance = std::abs(distance_between(points.at(0), points.at(1)));
	points_t minPoints = { points.at(0), points.at(1) };
	for (auto i = std::begin(points); i != (std::end(points) - 1); ++i) {
		for (auto j = i + 1; j < std::end(points); ++j) {
			auto newDistance = std::abs(distance_between(*i, *j));
			if (newDistance < minDistance) {
				minDistance = newDistance;
				minPoints.first = *i;
				minPoints.second = *j;
			}
		}
	}
	return { minDistance, minPoints };
}

std::pair<double, points_t> find_closest_optimized(const std::vector<point_t>& xP,
	const std::vector<point_t>& yP) {
	if (xP.size() <= 3) {
		return find_closest_brute(xP);
	}
	auto N = xP.size();
	auto xL = std::vector<point_t>();
	auto xR = std::vector<point_t>();
	std::copy(std::begin(xP), std::begin(xP) + (N / 2), std::back_inserter(xL));
	std::copy(std::begin(xP) + (N / 2), std::end(xP), std::back_inserter(xR));
	auto xM = xP.at((N-1) / 2).first;
	auto yL = std::vector<point_t>();
	auto yR = std::vector<point_t>();
	std::copy_if(std::begin(yP), std::end(yP), std::back_inserter(yL), [&xM](const point_t& p) {
		return p.first <= xM;
	});
	std::copy_if(std::begin(yP), std::end(yP), std::back_inserter(yR), [&xM](const point_t& p) {
		return p.first > xM;
	});
	auto p1 = find_closest_optimized(xL, yL);
	auto p2 = find_closest_optimized(xR, yR);
	auto minPair = (p1.first <= p2.first) ? p1 : p2;
	auto yS = std::vector<point_t>();
	std::copy_if(std::begin(yP), std::end(yP), std::back_inserter(yS), [&minPair, &xM](const point_t& p) {
		return std::abs(xM - p.first) < minPair.first;
	});
	auto result = minPair;
	for (auto i = std::begin(yS); i != (std::end(yS) - 1); ++i) {
		for (auto k = i + 1; k != std::end(yS) &&
		 ((k->second - i->second) < minPair.first); ++k) {
			auto newDistance = std::abs(distance_between(*k, *i));
			if (newDistance < result.first) {
				result = { newDistance, { *k, *i } };
			}
		}
	}
	return result;
}

void print_point(const point_t& point) {
	std::cout << "(" << point.first
		<< ", " << point.second
		<< ")";
}

int main(int argc, char * argv[]) {
	std::default_random_engine re(std::chrono::system_clock::to_time_t(
		std::chrono::system_clock::now()));
	std::uniform_real_distribution<double> urd(-500.0, 500.0);
	std::vector<point_t> points(100);
	std::generate(std::begin(points), std::end(points), [&urd, &re]() {
                return point_t { 1000 + urd(re), 1000 + urd(re) };
        });
	auto answer = find_closest_brute(points);
	std::sort(std::begin(points), std::end(points), [](const point_t& a, const point_t& b) {
		return a.first < b.first;
	});
	auto xP = points;
	std::sort(std::begin(points), std::end(points), [](const point_t& a, const point_t& b) {
		return a.second < b.second;
	});
	auto yP = points;
	std::cout << "Min distance (brute): " << answer.first << " ";
	print_point(answer.second.first);
	std::cout << ", ";
	print_point(answer.second.second);
	answer = find_closest_optimized(xP, yP);
	std::cout << "\nMin distance (optimized): " << answer.first << " ";
	print_point(answer.second.first);
	std::cout << ", ";
	print_point(answer.second.second);
	return 0;
}


use strict;
use warnings;
use ntheory 'divisor_sum';

sub comma { reverse ((reverse shift) =~ s/(.{3})/$1,/gr) =~ s/^,//r }

sub chowla {
    my($n) = @_;
    $n < 2 ? 0 : divisor_sum($n) - ($n + 1);
}

sub prime_cnt {
    my($n) = @_;
    my $cnt = 1;
    for (3..$n) {
        $cnt++ if $_%2 and chowla($_) == 0
    }
    $cnt;
}

sub perfect {
    my($n) = @_;
    my @p;
    for my $i (1..$n) {
        push @p, $i if $i > 1 and chowla($i) == $i-1;
    }
    # map { push @p, $_ if $_ > 1 and chowla($_) == $_-1 } 1..$n; # speed penalty
    @p;
}

printf "chowla(%2d) = %2d\n", $_, chowla($_) for 1..37;
print "\nCount of primes up to:\n";
printf "%10s %s\n", comma(10**$_), comma(prime_cnt(10**$_)) for 2..7;
my @perfect = perfect(my $limit = 35_000_000);
printf "\nThere are %d perfect numbers up to %s: %s\n",
    1+$#perfect, comma($limit), join(' ', map { comma($_) } @perfect);


(defn distance [[x1 y1] [x2 y2]]
  (let [dx (- x2 x1), dy (- y2 y1)]
    (Math/sqrt (+ (* dx dx) (* dy dy)))))

(defn brute-force [points]
  (let [n (count points)]
    (when (< 1 n)
      (apply min-key first
             (for [i (range 0 (dec n)), :let [p1 (nth points i)],
                   j (range (inc i) n), :let [p2 (nth points j)]]
               [(distance p1 p2) p1 p2])))))

(defn combine [yS [dmin pmin1 pmin2]]
  (apply min-key first
         (conj (for [[p1 p2] (partition 2 1 yS)
                     :let [[_ py1] p1 [_ py2] p2]
                     :while (< (- py1 py2) dmin)]
                 [(distance p1 p2) p1 p2])
               [dmin pmin1 pmin2])))

(defn closest-pair
  ([points]
     (closest-pair
      (sort-by first points)
      (sort-by second points)))
  ([xP yP]
     (if (< (count xP) 4)
       (brute-force xP)
       (let [[xL xR] (partition-all (Math/ceil (/ (count xP) 2)) xP)
             [xm _] (last xL)
             {yL true yR false} (group-by (fn [[px _]] (<= px xm)) yP)
             dL&pairL (closest-pair xL yL)
             dR&pairR (closest-pair xR yR)
             [dmin pmin1 pmin2] (min-key first dL&pairL dR&pairR)
             {yS true} (group-by (fn [[px _]] (< (Math/abs (- xm px)) dmin)) yP)]
         (combine yS [dmin pmin1 pmin2])))))


function chowla(atom n)
    return sum(factors(n))
end function

function sieve(integer limit)
    -- True denotes composite, false denotes prime.
    -- Only interested in odd numbers >= 3
    sequence c = repeat(false,limit)
    for i=3 to floor(limit/3) by 2 do
--      if not c[i] and chowla(i)==0 then
        if not c[i] then -- (see note below)
            for j=3*i to limit by 2*i do
                c[j] = true
            end for
        end if
    end for
    return c
end function

atom limit = 1e7, count = 1, pow10 = 100, t0 = time()
sequence s = {}
for i=1 to 37 do
    s &= chowla(i)
end for
printf(1,"chowla[1..37]: %V\n",{s})
s = sieve(limit)
for i=3 to limit by 2 do
    if not s[i] then count += 1 end if
    if i==pow10-1 then
        printf(1,"Count of primes up to %,d = %,d\n", {pow10, count})
        pow10 *= 10
    end if
end for

count = 0
limit = iff(machine_bits()=32?1.4e11:2.4e18)
--limit = power(2,iff(machine_bits()=32?53:64)) -- (see note below)
integer i=2
while true do
    atom p = power(2,i-1)*(power(2,i)-1) -- perfect numbers must be of this form
    if p>limit then exit end if
    if chowla(p)==p-1 then
        printf(1,"%,d is a perfect number\n", p)
        count += 1
    end if
    i += 1
end while
printf(1,"There are %d perfect numbers <= %,d\n",{count,limit})
?elapsed(time()-t0)


(defun point-distance (p1 p2)
  (destructuring-bind (x1 . y1) p1
    (destructuring-bind (x2 . y2) p2
      (let ((dx (- x2 x1)) (dy (- y2 y1)))
        (sqrt (+ (* dx dx) (* dy dy)))))))

(defun closest-pair-bf (points)
  (let ((pair (list (first points) (second points)))
        (dist (point-distance (first points) (second points))))
    (dolist (p1 points (values pair dist))
      (dolist (p2 points)
        (unless (eq p1 p2)
          (let ((pdist (point-distance p1 p2)))
            (when (< pdist dist)
              (setf (first pair) p1
                    (second pair) p2
                    dist pdist))))))))

(defun closest-pair (points)
  (labels
      ((cp (xp &aux (length (length xp)))
         (if (<= length 3)
           (multiple-value-bind (pair distance) (closest-pair-bf xp)
             (values pair distance (sort xp '< :key 'cdr)))
           (let* ((xr (nthcdr (1- (floor length 2)) xp))
                  (xm (/ (+ (caar xr) (caadr xr)) 2)))
             (psetf xr (rest xr)
                    (rest xr) '())
             (multiple-value-bind (lpair ldist yl) (cp xp)
               (multiple-value-bind (rpair rdist yr) (cp xr)
                 (multiple-value-bind (dist pair)
                     (if (< ldist rdist)
                       (values ldist lpair)
                       (values rdist rpair))
                   (let* ((all-ys (merge 'vector yl yr '< :key 'cdr))
                          (ys (remove-if #'(lambda (p)
                                             (> (abs (- (car p) xm)) dist))
                                         all-ys))
                          (ns (length ys)))
                     (dotimes (i ns)
                       (do ((k (1+ i) (1+ k)))
                           ((or (= k ns)
                                (> (- (cdr (aref ys k))
                                      (cdr (aref ys i)))
                                   dist)))
                         (let ((pd (point-distance (aref ys i)
                                                   (aref ys k))))
                           (when (< pd dist)
                             (setf dist pd
                                   (first pair) (aref ys i)
                                   (second pair) (aref ys k))))))
                     (values pair dist all-ys)))))))))
    (multiple-value-bind (pair distance)
        (cp (sort (copy-list points) '< :key 'car))
      (values pair distance))))


table
chowla(1) = 0.
chowla(2) = 0.
chowla(3) = 0.
chowla(N) = C, N>3 =>
    Max = floor(sqrt(N)),
    Sum = 0,
    foreach (X in 2..Max, N mod X == 0)
        Y := N div X,
        Sum := Sum + X + Y
    end,
    if (N == Max * Max) then
        Sum := Sum - Max
    end,
    C = Sum.

main =>
    foreach (I in 1..37)
        printf("chowla(%d) = %d\n", I, chowla(I))
    end,
    Ranges = {100, 1000, 10000, 100000, 1000000, 10000000},
    foreach (Range in Ranges)
        Count = 0,
        foreach (I in 2..Range)
            if (chowla(I) == 0) then
                Count := Count + 1
            end
        end,
        printf("There are %d primes less than %d.\n", Count, Range)
    end,
    Limit = 35000000,
    Count = 0,
    foreach (I in 2..Limit)
        if (chowla(I) == I-1) then
            printf("%d is a perfect number\n", I),
            Count := Count + 1
        end
    end,
    printf("There are %d perfect numbers less than %d.\n", Count, Limit).


(de accu1 (Var Key)
   (if (assoc Key (val Var))
      (con @ (inc (cdr @)))
      (push Var (cons Key 1)) )
   Key )
(de factor (N)
   (let
      (R NIL
         D 2
         L (1 2 2 . (4 2 4 2 4 6 2 6 .))
         M (sqrt N) )
      (while (>= M D)
         (if (=0 (% N D))
            (setq M
               (sqrt (setq N (/ N (accu1 'R D)))) )
            (inc 'D (pop 'L)) ) )
      (accu1 'R N)
      (mapcar
         '((L)
            (make
               (for N (cdr L)
                  (link (** (car L) N)) ) ) )
         R ) ) )
(de chowla (N)
   (let F (factor N)
      (-
         (sum
            prog
            (make
               (link 1)
               (mapc
                  '((A)
                     (chain
                        (mapcan
                           '((B)
                              (mapcar '((C) (* C B)) (made)) )
                           A ) ) )
                  F ) ) )
         N
         1 ) ) )
(de prime (N)
   (and (> N 1) (=0 (chowla N))) )
(de perfect (N)
   (and
      (> N 1)
      (= (chowla N) (dec N))) )
(de countP (N)
   (let C 0
      (for I N
         (and (prime I) (inc 'C)) )
      C ) )
(de listP (N)
   (make
      (for I N
         (and (perfect I) (link I)) ) ) )
(for I 37
   (prinl "chowla(" I ") = " (chowla I)) )
(prinl "Count of primes up to      100 = " (countP 100))
(prinl "Count of primes up to     1000 = " (countP 1000))
(prinl "Count of primes up to    10000 = " (countP 10000))
(prinl "Count of primes up to   100000 = " (countP 100000))
(prinl "Count of primes up to  1000000 = " (countP 1000000))
(prinl "Count of primes up to 10000000 = " (countP 10000000))
(println (listP 35000000))


#COMPILE EXE
#DIM ALL
#COMPILER PBCC 6

FUNCTION chowla(BYVAL n AS LONG) AS LONG
REGISTER i AS LONG, j AS LONG
LOCAL r AS LONG
    i = 2
    DO WHILE i * i <= n
        j = n \ i
        IF n MOD i = 0 THEN
            r += i
            IF i <> j THEN
                r += j
            END IF
        END IF
        INCR i
    LOOP
    FUNCTION = r
END FUNCTION

FUNCTION chowla1(BYVAL n AS QUAD) AS QUAD
LOCAL i, j, r AS QUAD
    i = 2
    DO WHILE i * i <= n
        j = n \ i
        IF n MOD i = 0 THEN
            r += i
            IF i <> j THEN
                r += j
            END IF
        END IF
        INCR i
    LOOP
    FUNCTION = r
END FUNCTION

SUB sieve(BYVAL limit AS LONG, BYREF c() AS INTEGER)
LOCAL i, j AS LONG
REDIM c(limit - 1)
    i = 3
    DO WHILE i * 3 < limit
        IF NOT c(i) THEN
            IF chowla(i) = 0 THEN
                j = 3 * i
                DO WHILE j < limit
                    c(j) = -1
                    j += 2 * i
                LOOP
            END IF
        END IF
        i += 2
    LOOP
END SUB

FUNCTION PBMAIN () AS LONG
LOCAL i, count, limit, power AS LONG
LOCAL c() AS INTEGER
LOCAL s AS STRING
LOCAL s30 AS STRING * 30
LOCAL p, k, kk, r, ql AS QUAD
    FOR i = 1 TO 37
        s = "chowla(" & TRIM$(STR$(i)) & ") = " & TRIM$(STR$(chowla(i)))
        CON.PRINT s
    NEXT i
    count = 1
    limit = 10000000
    power = 100
    CALL sieve(limit, c())
    FOR i = 3 TO limit - 1 STEP 2
        IF ISFALSE c(i) THEN count += 1
        IF i = power - 1 THEN
            RSET s30 = FORMAT$(power, "#,##0")
            s = "Count of primes up to " & s30 & " =" & STR$(count)
            CON.PRINT s
            power *= 10
        END IF
    NEXT i

    ql = 2 ^ 61
    k = 2: kk = 3
    RESET count
    DO
        p = k * kk : IF p > ql THEN EXIT DO
        IF chowla1(p) = p - 1 THEN
            RSET s30 = FORMAT$(p, "#,##0")
            s = s30 & " is a number that is perfect"
            CON.PRINT s
            count += 1
        END IF
        k = kk + 1 : kk += k
    LOOP
    s = "There are" & STR$(count) & " perfect numbers <= " & FORMAT$(ql, "#,##0")
    CON.PRINT s

    CON.PRINT "press any key to exit program"
    CON.WAITKEY$
END FUNCTION


chowla(1, 0).
chowla(2, 0).
chowla(N, C) :-
    N > 2,
    Max is floor(sqrt(N)),
    findall(X, (between(2, Max, X), N mod X =:= 0), Xs),
    findall(Y, (member(X1, Xs), Y is N div X1, Y \= Max), Ys),
    !,
    sum_list(Xs, S1),
    sum_list(Ys, S2),
    C is S1 + S2.

prime_count(Upper, Upper, Count, Count) :-
    !.

prime_count(Lower, Upper, Add, Count) :-
    chowla(Lower, 0),
    !,
    Lower1 is Lower + 1,
    Add1 is Add + 1,
    prime_count(Lower1, Upper, Add1, Count).

prime_count(Lower, Upper, Add, Count) :-
    Lower1 is Lower + 1,
    prime_count(Lower1, Upper, Add, Count).

perfect_numbers(Upper, Upper, AccNums, Nums) :-
    !,
    reverse(AccNums, Nums).

perfect_numbers(Lower, Upper, AccNums, Nums) :-
    Perfect is Lower - 1,
    chowla(Lower, Perfect),
    !,
    Lower1 is Lower + 1,
    AccNums1 = [Lower|AccNums],
    perfect_numbers(Lower1, Upper, AccNums1, Nums).

perfect_numbers(Lower, Upper, AccNums, Nums) :-
    Lower1 is Lower + 1,
    perfect_numbers(Lower1, Upper, AccNums, Nums).

main :-
    % Chowla numbers
    forall(between(1, 37, N), (
        chowla(N, C),
        format('chowla(~D) = ~D\n', [N, C])
    )),

    % Prime numbers
    Ranges = [100, 1000, 10000, 100000, 1000000, 10000000],
    forall(member(Range, Ranges), (
        prime_count(2, Range, 0, PrimeCount),
        format('There are ~D primes less than ~D.\n', [PrimeCount, Range])
    )),

    % Perfect numbers
    Limit = 35000000,
    perfect_numbers(2, Limit, [], Nums),
    forall(member(Perfect, Nums), (
        format('~D is a perfect number.\n', [Perfect])
    )),
    length(Nums, PerfectCount),
    format('There are ~D perfect numbers < ~D.\n', [PerfectCount, Limit]).


import std.stdio, std.typecons, std.math, std.algorithm,
       std.random, std.traits, std.range, std.complex;

auto bruteForceClosestPair(T)(in T[] points) pure nothrow @nogc {
//  return pairwise(points.length.iota, points.length.iota)
//         .reduce!(min!((i, j) => abs(points[i] - points[j])));
  auto minD = Unqual!(typeof(T.re)).infinity;
  T minI, minJ;
  foreach (immutable i, const p1; points.dropBackOne)
    foreach (const p2; points[i + 1 .. $]) {
      immutable dist = abs(p1 - p2);
      if (dist < minD) {
        minD = dist;
        minI = p1;
        minJ = p2;
      }
    }
  return tuple(minD, minI, minJ);
}

auto closestPair(T)(T[] points) pure nothrow {
  static Tuple!(typeof(T.re), T, T) inner(in T[] xP, /*in*/ T[] yP)
  pure nothrow {
    if (xP.length <= 3)
      return xP.bruteForceClosestPair;
    const Pl = xP[0 .. $ / 2];
    const Pr = xP[$ / 2 .. $];
    immutable xDiv = Pl.back.re;
    auto Yr = yP.partition!(p => p.re <= xDiv);
    immutable dl_pairl = inner(Pl, yP[0 .. yP.length - Yr.length]);
    immutable dr_pairr = inner(Pr, Yr);
    immutable dm_pairm = dl_pairl[0]<dr_pairr[0] ? dl_pairl : dr_pairr;
    immutable dm = dm_pairm[0];
    const nextY = yP.filter!(p => abs(p.re - xDiv) < dm).array;

    if (nextY.length > 1) {
      auto minD = typeof(T.re).infinity;
      size_t minI, minJ;
      foreach (immutable i; 0 .. nextY.length - 1)
        foreach (immutable j; i + 1 .. min(i + 8, nextY.length)) {
          immutable double dist = abs(nextY[i] - nextY[j]);
          if (dist < minD) {
            minD = dist;
            minI = i;
            minJ = j;
          }
        }
      return dm <= minD ? dm_pairm :
                        typeof(return)(minD, nextY[minI], nextY[minJ]);
    } else
      return dm_pairm;
  }

  points.sort!q{ a.re < b.re };
  const xP = points.dup;
  points.sort!q{ a.im < b.im };
  return inner(xP, points);
}

void main() {
  alias C = complex;
  auto pts = [C(5,9), C(9,3), C(2), C(8,4), C(7,4), C(9,10), C(1,9),
              C(8,2), C(0,10), C(9,6)];
  pts.writeln;
  writeln("bruteForceClosestPair: ", pts.bruteForceClosestPair);
  writeln("          closestPair: ", pts.closestPair);

  rndGen.seed = 1;
  Complex!double[10_000] points;
  foreach (ref p; points)
    p = C(uniform(0.0, 1000.0) + uniform(0.0, 1000.0));
  writeln("bruteForceClosestPair: ", points.bruteForceClosestPair);
  writeln("          closestPair: ", points.closestPair);
}


# https://docs.sympy.org/latest/modules/ntheory.html#sympy.ntheory.factor_.divisors
from sympy import divisors

def chowla(n):
    return 0 if n < 2 else sum(divisors(n, generator=True)) - 1 -n

def is_prime(n):
    return chowla(n) == 0

def primes_to(n):
    return sum(chowla(i) == 0 for i in range(2, n))

def perfect_between(n, m):
    c = 0
    print(f"\nPerfect numbers between [{n:_}, {m:_})")
    for i in range(n, m):
        if i > 1 and chowla(i) == i - 1:
            print(f"  {i:_}")
            c += 1
    print(f"Found {c} Perfect numbers between [{n:_}, {m:_})")

if __name__ == '__main__':
    for i in range(1, 38):
        print(f"chowla({i:2}) == {chowla(i)}")
    for i in range(2, 6):
        print(f"primes_to({10**i:_}) == {primes_to(10**i):_}")
    perfect_between(1, 1_000_000)
    print()
    for i in range(6, 8):
        print(f"primes_to({10**i:_}) == {primes_to(10**i):_}")
    perfect_between(1_000_000, 35_000_000)


#lang racket

(require racket/fixnum)

(define cache-size 35000000)

(define chowla-cache (make-fxvector cache-size -1))

(define (chowla/uncached n)
  (for/sum ((i (sequence-filter (λ (x) (zero? (modulo n x))) (in-range 2 (add1 (quotient n 2)))))) i))

(define (chowla n)
  (if (> n cache-size)
    (chowla/uncached n)
    (let ((idx (sub1 n)))
      (if (negative? (fxvector-ref chowla-cache idx))
        (let ((c (chowla/uncached n))) (fxvector-set! chowla-cache idx c) c)
        (fxvector-ref chowla-cache idx)))))

(define (prime?/chowla n)
  (and (> n 1)
       (zero? (chowla n))))

(define (perfect?/chowla n)
  (and (> n 1)
       (= n (add1 (chowla n)))))

(define (make-chowla-sieve n)
  (let ((v (make-vector n 0)))
    (for* ((i (in-range 2 n)) (j (in-range (* 2 i) n i))) (vector-set! v j (+ i (vector-ref v j))))
    (for ((i (in-range 1 n))) (fxvector-set! chowla-cache (sub1 i) (vector-ref v i)))))

(module+
  main
  (define (count-and-report-primes limit)
    (printf "Primes < ~a: ~a~%" limit (for/sum ((i (sequence-filter prime?/chowla (in-range 2 (add1 limit))))) 1)))

  (for ((i (in-range 1 (add1 37)))) (printf "(chowla ~a) = ~a~%" i (chowla i)))

  (make-chowla-sieve cache-size)

  (for-each count-and-report-primes '(1000 10000 100000 1000000 10000000))

  (let ((ns (for/list ((n (sequence-filter perfect?/chowla (in-range 2 35000000)))) n)))
    (printf "There are ~a perfect numbers <= 35000000: ~a~%" (length ns) ns)))


sub comma { $^i.flip.comb(3).join(',').flip }

sub schnitzel (\Radda, \radDA = 0) {
    Radda.is-prime ?? !Radda !! ?radDA ?? Radda
    !! sum flat (2 .. Radda.sqrt.floor).map: -> \RAdda {
        my \RADDA = Radda div RAdda;
        next if RADDA * RAdda !== Radda;
        RAdda !== RADDA ?? (RAdda, RADDA) !! RADDA
    }
}

my \chowder = cache (1..Inf).hyper(:8degree).grep( !*.&schnitzel: 'panini' );

my \mung-daal = lazy gather for chowder -> \panini {
    my \gazpacho = 2**panini - 1;
    take gazpacho * 2**(panini - 1) unless schnitzel gazpacho, panini;
}

printf "chowla(%2d) = %2d\n", $_, .&schnitzel for 1..37;

say '';

printf "Count of primes up to %10s: %s\n", comma(10**$_),
  comma chowder.first( * > 10**$_, :k) for 2..7;

say "\nPerfect numbers less than 35,000,000";

.&comma.say for mung-daal[^5];


/*REXX program computes/displays chowla numbers (and may count primes & perfect numbers.*/
parse arg LO HI .                                /*obtain optional arguments from the CL*/
if LO=='' | LO==","  then LO=  1                 /*Not specified?  Then use the default.*/
perf= LO<0;               LO= abs(LO)            /*Negative?  Then determine if perfect.*/
if HI=='' | HI==","  then HI= LO                 /*Not specified?  Then use the default.*/
prim= HI<0;               HI= abs(HI)            /*Negative?  Then determine if a prime.*/
numeric digits max(9, length(HI) + 1 )           /*use enough decimal digits for   //   */
w= length( commas(HI) )                          /*W:   used in aligning output numbers.*/
tell= \(prim | perf)                             /*set boolean value for showing chowlas*/
p= 0                                             /*the number of primes found  (so far).*/
     do j=LO  to HI;       #= chowla(j)          /*compute the  cholwa number  for  J.  */
     if tell  then say right('chowla('commas(j)")", w+9)    ' = '    right( commas(#), w)
              else if #==0  then if j>1  then p= p+1
     if perf  then if j-1==# & j>1  then say right(commas(j), w)   ' is a perfect number.'
     end   /*j*/

if prim & \perf  then say 'number of primes found for the range '   commas(LO)    " to " ,
                           commas(HI)        " (inclusive)  is: "   commas(p)
exit                                             /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
chowla: procedure; parse arg x;         if x<2  then return 0;          odd= x // 2
        s=0                                      /* [↓]  use EVEN or ODD integers.   ___*/
            do k=2+odd  by 1+odd  while k*k<x    /*divide by all the integers up to √ X */
            if x//k==0  then  s=s + k + x%k      /*add the two divisors to the sum.     */
            end   /*k*/                          /* [↓]  adkust for square.          ___*/
        if k*k==x  then  s=s + k                 /*Was  X  a square?    If so, add  √ X */
        return s                                 /*return     "     "    "      "     " */
/*──────────────────────────────────────────────────────────────────────────────────────*/
commas: parse arg _;  do k=length(_)-3  to 1  by -3; _= insert(',', _, k); end;   return _


defmodule Closest_pair do
  # brute-force algorithm:
  def bruteForce([p0,p1|_] = points), do: bf_loop(points, {distance(p0, p1), {p0, p1}})

  defp bf_loop([_], acc), do: acc
  defp bf_loop([h|t], acc), do: bf_loop(t, bf_loop(h, t, acc))

  defp bf_loop(_, [], acc), do: acc
  defp bf_loop(p0, [p1|t], {minD, minP}) do
    dist = distance(p0, p1)
    if dist < minD, do: bf_loop(p0, t, {dist, {p0, p1}}),
                  else: bf_loop(p0, t, {minD, minP})
  end

  defp distance({p0x,p0y}, {p1x,p1y}) do
    :math.sqrt( (p1x - p0x) * (p1x - p0x) + (p1y - p0y) * (p1y - p0y) )
  end

  # recursive divide&conquer approach:
  def recursive(points) do
    recursive(Enum.sort(points), Enum.sort_by(points, fn {_x,y} -> y end))
  end

  def recursive(xP, _yP) when length(xP) <= 3, do: bruteForce(xP)
  def recursive(xP, yP) do
    {xL, xR} = Enum.split(xP, div(length(xP), 2))
    {xm, _} = hd(xR)
    {yL, yR} = Enum.partition(yP, fn {x,_} -> x < xm end)
    {dL, pairL} = recursive(xL, yL)
    {dR, pairR} = recursive(xR, yR)
    {dmin, pairMin} = if dL<dR, do: {dL, pairL}, else: {dR, pairR}
    yS = Enum.filter(yP, fn {x,_} -> abs(xm - x) < dmin end)
    merge(yS, {dmin, pairMin})
  end

  defp merge([_], acc), do: acc
  defp merge([h|t], acc), do: merge(t, merge_loop(h, t, acc))

  defp merge_loop(_, [], acc), do: acc
  defp merge_loop(p0, [p1|_], {dmin,_}=acc) when dmin <= elem(p1,1) - elem(p0,1), do: acc
  defp merge_loop(p0, [p1|t], {dmin, pair}) do
    dist = distance(p0, p1)
    if dist < dmin, do: merge_loop(p0, t, {dist, {p0, p1}}),
                  else: merge_loop(p0, t, {dmin, pair})
  end
end

data = [{0.654682, 0.925557}, {0.409382, 0.619391}, {0.891663, 0.888594}, {0.716629, 0.996200},
        {0.477721, 0.946355}, {0.925092, 0.818220}, {0.624291, 0.142924}, {0.211332, 0.221507},
        {0.293786, 0.691701}, {0.839186, 0.728260}]

IO.inspect Closest_pair.bruteForce(data)
IO.inspect Closest_pair.recursive(data)

data2 = for _ <- 1..5000, do: {:rand.uniform, :rand.uniform}
IO.puts "\nBrute-force:"
IO.inspect :timer.tc(fn -> Closest_pair.bruteForce(data2) end)
IO.puts "Recursive divide&conquer:"
IO.inspect :timer.tc(fn -> Closest_pair.recursive(data2) end)


def chowla(n)
    sum = 0
    i = 2
    while i * i <= n do
        if n % i == 0 then
            sum = sum + i
            j = n / i
            if i != j then
                sum = sum + j
            end
        end
        i = i + 1
    end
    return sum
end

def main
    for n in 1 .. 37 do
        puts "chowla(%d) = %d" % [n, chowla(n)]
    end

    count = 0
    power = 100
    for n in 2 .. 10000000 do
        if chowla(n) == 0 then
            count = count + 1
        end
        if n % power == 0 then
            puts "There are %d primes < %d" % [count, power]
            power = power * 10
        end
    end

    count = 0
    limit = 350000000
    k = 2
    kk = 3
    loop do
        p = k * kk
        if p > limit then
            break
        end
        if chowla(p) == p - 1 then
            puts "%d is a perfect number" % [p]
            count = count + 1
        end
        k = kk + 1
        kk = kk + k
    end
    puts "There are %d perfect numbers < %d" % [count, limit]
end

main()


object ChowlaNumbers {
  def main(args: Array[String]): Unit = {
    println("Chowla Numbers...")
    for(n <- 1 to 37){println(s"$n: ${chowlaNum(n)}")}
    println("\nPrime Counts...")
    for(i <- (2 to 7).map(math.pow(10, _).toInt)){println(f"$i%,d: ${primesPar(i).size}%,d")}
    println("\nPerfect Numbers...")
    print(perfectsPar(35000000).toVector.sorted.zipWithIndex.map{case (n, i) => f"${i + 1}%,d: $n%,d"}.mkString("\n"))
  }

  def primesPar(num: Int): ParVector[Int] = ParVector.range(2, num + 1).filter(n => chowlaNum(n) == 0)
  def perfectsPar(num: Int): ParVector[Int] = ParVector.range(6, num + 1).filter(n => chowlaNum(n) + 1 == n)

  def chowlaNum(num: Int): Int = Iterator.range(2, math.sqrt(num).toInt + 1).filter(n => num%n == 0).foldLeft(0){case (s, n) => if(n*n == num) s + n else s + n + (num/n)}
}


let closest_pairs (xys: Point []) =
  let n = xys.Length
  seq { for i in 0..n-2 do
          for j in i+1..n-1 do
            yield xys.[i], xys.[j] }
  |> Seq.minBy (fun (p0, p1) -> (p1 - p0).LengthSquared)


class Point
{
  Float x
  Float y

  // create a random point
  new make (Float x := Float.random * 10, Float y := Float.random * 10)
  {
    this.x = x
    this.y = y
  }

  Float distance (Point p)
  {
    ((x-p.x)*(x-p.x) + (y-p.y)*(y-p.y)).sqrt
  }

  override Str toStr () { "($x, $y)" }
}

class Main
{
  // use brute force approach
  static Point[] findClosestPair1 (Point[] points)
  {
    if (points.size < 2) return points  // list too small
    Point[] closestPair := [points[0], points[1]]
    Float closestDistance := points[0].distance(points[1])

    (1..<points.size).each |Int i|
    {
      ((i+1)..<points.size).each |Int j|
      {
        Float trydistance := points[i].distance(points[j])
        if (trydistance < closestDistance)
        {
          closestPair = [points[i], points[j]]
          closestDistance = trydistance
        }
      }
    }

    return closestPair
  }

  // use recursive divide-and-conquer approach
  static Point[] findClosestPair2 (Point[] points)
  {
    if (points.size <= 3) return findClosestPair1(points)
    points.sort |Point a, Point b -> Int| { a.x <=> b.x }
    bestLeft := findClosestPair2 (points[0..(points.size/2)])
    bestRight := findClosestPair2 (points[(points.size/2)..-1])

    Float minDistance
    Point[] closePoints := [,]
    if (bestLeft[0].distance(bestLeft[1]) < bestRight[0].distance(bestRight[1]))
    {
      minDistance = bestLeft[0].distance(bestLeft[1])
      closePoints = bestLeft
    }
    else
    {
      minDistance = bestRight[0].distance(bestRight[1])
      closePoints = bestRight
    }
    yPoints := points.findAll |Point p -> Bool|
    {
      (points.last.x - p.x).abs < minDistance
    }.sort |Point a, Point b -> Int| { a.y <=> b.y }

    closestPair := [,]
    closestDist := Float.posInf

    for (Int i := 0; i < yPoints.size - 1; ++i)
    {
      for (Int j := (i+1); j < yPoints.size; ++j)
      {
        if ((yPoints[j].y - yPoints[i].y) >= minDistance)
        {
          break
        }
        else
        {
          dist := yPoints[i].distance (yPoints[j])
          if (dist < closestDist)
          {
            closestDist = dist
            closestPair = [yPoints[i], yPoints[j]]
          }
        }
      }
    }
    if (closestDist < minDistance)
      return closestPair
    else
      return closePoints
  }

  public static Void main (Str[] args)
  {
    Int numPoints := 10 // default value, in case a number not given on command line
    if ((args.size > 0) && (args[0].toInt(10, false) != null))
    {
      numPoints = args[0].toInt(10, false)
    }

    Point[] points := [,]
    numPoints.times { points.add (Point()) }

    Int t1 := Duration.now.toMillis
    echo (findClosestPair1(points.dup))
    Int t2 := Duration.now.toMillis
    echo ("Time taken: ${(t2-t1)}ms")
    echo (findClosestPair2(points.dup))
    Int t3 := Duration.now.toMillis
    echo ("Time taken: ${(t3-t2)}ms")
  }
}


import Foundation

@inlinable
public func chowla<T: BinaryInteger>(n: T) -> T {
  stride(from: 2, to: T(Double(n).squareRoot()+1), by: 1)
    .lazy
    .filter({ n % $0 == 0 })
    .reduce(0, {(s: T, m: T) in
      m*m == n ? s + m : s + m + (n / m)
    })
}

extension Dictionary where Key == ClosedRange<Int> {
  subscript(n: Int) -> Value {
    get {
      guard let key = keys.first(where: { $0.contains(n) }) else {
        fatalError("dict does not contain range for \(n)")
      }

      return self[key]!
    }

    set {
      guard let key = keys.first(where: { $0.contains(n) }) else {
        fatalError("dict does not contain range for \(n)")
      }

      self[key] = newValue
    }
  }
}

let lock = DispatchSemaphore(value: 1)

var perfect = [Int]()
var primeCounts = [
  1...100: 0,
  101...1_000: 0,
  1_001...10_000: 0,
  10_001...100_000: 0,
  100_001...1_000_000: 0,
  1_000_001...10_000_000: 0
]

for i in 1...37 {
  print("chowla(\(i)) = \(chowla(n: i))")
}

DispatchQueue.concurrentPerform(iterations: 35_000_000) {i in
  let chowled = chowla(n: i)

  if chowled == 0 && i > 1 && i < 10_000_000 {
    lock.wait()
    primeCounts[i] += 1
    lock.signal()
  }

  if chowled == i - 1 && i > 1 {
    lock.wait()
    perfect.append(i)
    lock.signal()
  }
}

let numPrimes = primeCounts
  .sorted(by: { $0.key.lowerBound < $1.key.lowerBound })
  .reduce(into: [(Int, Int)](), {counts, oneCount in
    guard !counts.isEmpty else {
      counts.append((oneCount.key.upperBound, oneCount.value))

      return
    }

    counts.append((oneCount.key.upperBound, counts.last!.1 + oneCount.value))
  })

for (upper, count) in numPrimes {
  print("Number of primes < \(upper) = \(count)")
}

for p in perfect {
  print("\(p) is a perfect number")
}


Option Explicit

Private Declare Function AllocConsole Lib "kernel32.dll" () As Long
Private Declare Function FreeConsole Lib "kernel32.dll" () As Long
Dim mStdOut As Scripting.TextStream

Function chowla(ByVal n As Long) As Long
Dim j As Long, i As Long
  i = 2
  Do While i * i <= n
    j = n \ i
    If n Mod i = 0 Then
    chowla = chowla + i
      If i <> j Then
      chowla = chowla + j
      End If
    End If
    i = i + 1
  Loop
End Function

Function sieve(ByVal limit As Long) As Boolean()
Dim c() As Boolean
Dim i As Long
Dim j As Long
  i = 3
  ReDim c(limit - 1)
    Do While i * 3 < limit
      If Not c(i) Then
        If (chowla(i) = 0) Then
          j = 3 * i
          Do While j < limit
            c(j) = True
            j = j + 2 * i
          Loop
        End If
    End If
    i = i + 2
    Loop
  sieve = c()
End Function

Sub Display(ByVal s As String)
  Debug.Print s
  mStdOut.Write s & vbNewLine
End Sub

Sub Main()
Dim i As Long
Dim count As Long
Dim limit As Long
Dim power As Long
Dim c() As Boolean
Dim p As Long
Dim k As Long
Dim kk As Long
Dim s As String * 30
Dim mFSO As Scripting.FileSystemObject
Dim mStdIn As Scripting.TextStream

  AllocConsole
  Set mFSO = New Scripting.FileSystemObject
  Set mStdIn = mFSO.GetStandardStream(StdIn)
  Set mStdOut = mFSO.GetStandardStream(StdOut)

  For i = 1 To 37
    Display "chowla(" & i & ")=" & chowla(i)
  Next i

  count = 1
  limit = 10000000
  power = 100
  c = sieve(limit)

  For i = 3 To limit - 1 Step 2
    If Not c(i) Then
      count = count + 1
    End If
    If i = power - 1 Then
      RSet s = FormatNumber(power, 0, vbUseDefault, vbUseDefault, True)
      Display "Count of primes up to " & s & " = " & FormatNumber(count, 0, vbUseDefault, vbUseDefault, True)
      power = power * 10
    End If
  Next i

  count = 0: limit = 35000000
  k = 2:     kk = 3

  Do
    p = k * kk
    If p > limit Then
      Exit Do
    End If

    If chowla(p) = p - 1 Then
      RSet s = FormatNumber(p, 0, vbUseDefault, vbUseDefault, True)
      Display s & " is a number that is perfect"
      count = count + 1
    End If
    k = kk + 1
    kk = kk + k
  Loop

  Display "There are " & CStr(count) & " perfect numbers <= 35.000.000"

  mStdOut.Write "press enter to quit program."
  mStdIn.Read 1

  FreeConsole

End Sub


Dim As Integer i, j
Dim As Double minDist = 1^30
Dim As Double x(9), y(9), dist, mini, minj

Data  0.654682, 0.925557
Data  0.409382, 0.619391
Data  0.891663, 0.888594
Data  0.716629, 0.996200
Data  0.477721, 0.946355
Data  0.925092, 0.818220
Data  0.624291, 0.142924
Data  0.211332, 0.221507
Data  0.293786, 0.691701
Data  0.839186, 0.728260

For i = 0 To 9
    Read x(i), y(i)
Next i

For i = 0 To 8
    For j = i+1 To 9
        dist = (x(i) - x(j))^2 + (y(i) - y(j))^2
        If dist < minDist Then
            minDist = dist
            mini = i
            minj = j
        End If
    Next j
Next i

Print "El par más cercano es "; mini; " y "; minj; " a una distancia de "; Sqr(minDist)
End


Imports System

Module Program
    Function chowla(ByVal n As Integer) As Integer
        chowla = 0 : Dim j As Integer, i As Integer = 2
        While i * i <= n
            j = n / i : If n Mod i = 0 Then chowla += i + (If(i = j, 0, j))
            i += 1
        End While
    End Function

    Function sieve(ByVal limit As Integer) As Boolean()
        Dim c As Boolean() = New Boolean(limit - 1) {}, i As Integer = 3
        While i * 3 < limit
            If Not c(i) AndAlso (chowla(i) = 0) Then
                Dim j As Integer = 3 * i
                While j < limit : c(j) = True : j += 2 * i : End While
            End If : i += 2
        End While
        Return c
    End Function

    Sub Main(args As String())
        For i As Integer = 1 To 37
            Console.WriteLine("chowla({0}) = {1}", i, chowla(i))
        Next
        Dim count As Integer = 1, limit As Integer = CInt((10000000.0)), power As Integer = 100,
            c As Boolean() = sieve(limit)
        For i As Integer = 3 To limit - 1 Step 2
            If Not c(i) Then count += 1
            If i = power - 1 Then
                Console.WriteLine("Count of primes up to {0,10:n0} = {1:n0}", power, count)
                power = power * 10
            End If
        Next
        count = 0 : limit = 35000000
        Dim p As Integer, k As Integer = 2, kk As Integer = 3
        While True
            p = k * kk : If p > limit Then Exit While
            If chowla(p) = p - 1 Then
                Console.WriteLine("{0,10:n0} is a number that is perfect", p)
                count += 1
            End If
            k = kk + 1 : kk += k
        End While
        Console.WriteLine("There are {0} perfect numbers <= 35,000,000", count)
        If System.Diagnostics.Debugger.IsAttached Then Console.ReadKey()
    End Sub
End Module


package main

import (
    "fmt"
    "math"
    "math/rand"
    "time"
)

type xy struct {
    x, y float64
}

const n = 1000
const scale = 100.

func d(p1, p2 xy) float64 {
    return math.Hypot(p2.x-p1.x, p2.y-p1.y)
}

func main() {
    rand.Seed(time.Now().Unix())
    points := make([]xy, n)
    for i := range points {
        points[i] = xy{rand.Float64() * scale, rand.Float64() * scale}
    }
    p1, p2 := closestPair(points)
    fmt.Println(p1, p2)
    fmt.Println("distance:", d(p1, p2))
}

func closestPair(points []xy) (p1, p2 xy) {
    if len(points) < 2 {
        panic("at least two points expected")
    }
    min := 2 * scale
    for i, q1 := range points[:len(points)-1] {
        for _, q2 := range points[i+1:] {
            if dq := d(q1, q2); dq < min {
                p1, p2 = q1, q2
                min = dq
            }
        }
    }
    return
}


fn chowla(n int) int {
    if n < 1 {
        panic("argument must be a positive integer")
    }
    mut sum := 0
    for i := 2; i*i <= n; i++ {
        if n%i == 0 {
            j := n / i
            if i == j {
                sum += i
            } else {
                sum += i + j
            }
        }
    }
    return sum
}

fn sieve(limit int) []bool {
    // True denotes composite, false denotes prime.
    // Only interested in odd numbers >= 3
    mut c := []bool{len: limit}
    for i := 3; i*3 < limit; i += 2 {
        if !c[i] && chowla(i) == 0 {
            for j := 3 * i; j < limit; j += 2 * i {
                c[j] = true
            }
        }
    }
    return c
}

fn main() {
    for i := 1; i <= 37; i++ {
        println("chowla(${i:2}) = ${chowla(i)}")
    }
    println('')

    mut count := 1
    mut limit := int(1e7)
    c := sieve(limit)
    mut power := 100
    for i := 3; i < limit; i += 2 {
        if !c[i] {
            count++
        }
        if i == power-1 {
            println("Count of primes up to ${power:-10} = $count")
            power *= 10
        }
    }

    println('')
    count = 0
    limit = 35000000
    for i := 2; ; i++ {
        p := (1 << (i -1)) * ((1<<i) - 1)
        if p > limit {
            break
        }
        if chowla(p) == p-1  {
            println("$p is a perfect number")
            count++
        }
    }
    println("There are $count perfect numbers <= 35,000,000")
}


import "./fmt" for Fmt
import "./math" for Int, Nums

var chowla = Fn.new { |n| (n > 1) ? Nums.sum(Int.properDivisors(n)) - 1 : 0 }

for (i in 1..37) Fmt.print("chowla($2d) = $d", i, chowla.call(i))
System.print()
var count = 1
var limit = 1e7
var c = Int.primeSieve(limit, false)
var power = 100
var i = 3
while (i < limit) {
    if (!c[i]) count = count + 1
    if (i == power - 1) {
        Fmt.print("Count of primes up to $,-10d = $,d", power, count)
        power = power * 10
    }
    i = i + 2
}
System.print()
count = 0
limit = 35 * 1e6
i = 2
while (true) {
    var p = (1 << (i -1)) * ((1<<i) - 1) // perfect numbers must be of this form
    if (p > limit) break
    if (chowla.call(p) == p-1) {
        Fmt.print("$,d is a perfect number", p)
        count = count + 1
    }
    i = i + 1
}
System.print("There are %(count) perfect numbers <= 35,000,000")


class Point {
    final Number x, y
    Point(Number x = 0, Number y = 0) { this.x = x; this.y = y }
    Number distance(Point that) { ((this.x - that.x)**2 + (this.y - that.y)**2)**0.5 }
    String toString() { "{x:${x}, y:${y}}" }
}


import Data.List (minimumBy, tails, unfoldr, foldl1') --'

import System.Random (newStdGen, randomRs)

import Control.Arrow ((&&&))

import Data.Ord (comparing)

vecLeng [[a, b], [p, q]] = sqrt $ (a - p) ^ 2 + (b - q) ^ 2

findClosestPair =
  foldl1'' ((minimumBy (comparing vecLeng) .) . (. return) . (:)) .
  concatMap (\(x:xs) -> map ((x :) . return) xs) . init . tails

testCP = do
  g <- newStdGen
  let pts :: [[Double]]
      pts = take 1000 . unfoldr (Just . splitAt 2) $ randomRs (-1, 1) g
  print . (id &&& vecLeng) . findClosestPair $ pts

main = testCP

foldl1'' = foldl1'


func Chowla(N);         \Return sum of divisors
int  N, Div, Sum, Quot;
[Div:= 2;  Sum:= 0;
loop    [Quot:= N/Div;
        if Quot < Div then quit;
        if Quot = Div and rem(0) = 0 then \N is a square
            [Sum:= Sum+Quot;  quit];
        if rem(0) = 0 then
            Sum:= Sum + Div + Quot;
        Div:= Div+1;
        ];
return Sum;
];

int N, C, P;
[for N:= 1 to 37 do
    [IntOut(0, N);  Text(0, ": ");
    IntOut(0, Chowla(N));  CrLf(0);
    ];
C:= 1;  \count 2 as prime
N:= 3;  \only check odd numbers
repeat  if Chowla(N) = 0 then \N is prime
            C:= C+1;
        case N+1 of 100, 1000, 10_000, 100_000, 1_000_000, 10_000_000:
            [Text(0, "There are ");  IntOut(0, C);  Text(0, " primes < ");
            IntOut(0, N+1);  CrLf(0)]
        other [];
        N:= N+2;
until   N >= 10_000_000;
P:= 1;  \perfect numbers are of form: 2^(P-1) * (2^P - 1)
loop    [P:= P*2;
        N:= P*(P*2-1);
        if N > 35_000_000 then quit;
        if Chowla(N) = N-1 then \N is perfect
            [IntOut(0, N);  CrLf(0)];
        ];
]


fcn chowla(n){
   if(n<1)
      throw(Exception.ValueError("Chowla function argument must be positive"));
   sum:=0;
   foreach i in ([2..n.toFloat().sqrt()]){
      if(n%i == 0){
	 j:=n/i;
	 if(i==j) sum+=i;
	 else     sum+=i+j;
      }
   }
   sum
}

fcn chowlaSieve(limit){
    // True denotes composite, false denotes prime.
    // Only interested in odd numbers >= 3
   c:=Data(limit+100).fill(0); # slop at the end (for reverse wrap around)
   foreach i in ([3..limit/3,2]){
      if(not c[i] and chowla(i)==0)
         { foreach j in ([3*i..limit,2*i]){ c[j]=True } }
   }
   c
}


record point(x,y)

procedure main()
    minDist := 0
    minPair := &null
    every (points := [],p1 := readPoint()) do {
        if *points == 1 then minDist := dSquared(p1,points[1])
        every minDist >=:= dSquared(p1,p2 := !points) do minPair := [p1,p2]
        push(points, p1)
        }

    if \minPair then {
        write("(",minPair[1].x,",",minPair[1].y,") -> ",
              "(",minPair[2].x,",",minPair[2].y,")")
        }
    else write("One or fewer points!")
end

procedure readPoint()  # Skips lines that don't have two numbers on them
    suspend !&input ? point(numeric(tab(upto(', '))), numeric((move(1),tab(0))))
end

procedure dSquared(p1,p2)    # Compute the square of the distance
    return (p2.x-p1.x)^2 + (p2.y-p1.y)^2  # (sufficient for closeness)
end


vecl   =:  +/"1&.:*:                  NB. length of each vector
dist   =: <@:[email protected]:({: -"1 }:)\               NB. calculate all distances among vectors
minpair=: ({~ > {[email protected]($ #: [email protected],)@:= <./@;)dist  NB. find one pair of the closest points
closestpairbf =: (; [email protected]:-/)@minpair         NB. the pair and their distance


import java.util.*;

public class ClosestPair
{
  public static class Point
  {
    public final double x;
    public final double y;

    public Point(double x, double y)
    {
      this.x = x;
      this.y = y;
    }

    public String toString()
    {  return "(" + x + ", " + y + ")";  }
  }

  public static class Pair
  {
    public Point point1 = null;
    public Point point2 = null;
    public double distance = 0.0;

    public Pair()
    {  }

    public Pair(Point point1, Point point2)
    {
      this.point1 = point1;
      this.point2 = point2;
      calcDistance();
    }

    public void update(Point point1, Point point2, double distance)
    {
      this.point1 = point1;
      this.point2 = point2;
      this.distance = distance;
    }

    public void calcDistance()
    {  this.distance = distance(point1, point2);  }

    public String toString()
    {  return point1 + "-" + point2 + " : " + distance;  }
  }

  public static double distance(Point p1, Point p2)
  {
    double xdist = p2.x - p1.x;
    double ydist = p2.y - p1.y;
    return Math.hypot(xdist, ydist);
  }

  public static Pair bruteForce(List<? extends Point> points)
  {
    int numPoints = points.size();
    if (numPoints < 2)
      return null;
    Pair pair = new Pair(points.get(0), points.get(1));
    if (numPoints > 2)
    {
      for (int i = 0; i < numPoints - 1; i++)
      {
        Point point1 = points.get(i);
        for (int j = i + 1; j < numPoints; j++)
        {
          Point point2 = points.get(j);
          double distance = distance(point1, point2);
          if (distance < pair.distance)
            pair.update(point1, point2, distance);
        }
      }
    }
    return pair;
  }

  public static void sortByX(List<? extends Point> points)
  {
    Collections.sort(points, new Comparator<Point>() {
        public int compare(Point point1, Point point2)
        {
          if (point1.x < point2.x)
            return -1;
          if (point1.x > point2.x)
            return 1;
          return 0;
        }
      }
    );
  }

  public static void sortByY(List<? extends Point> points)
  {
    Collections.sort(points, new Comparator<Point>() {
        public int compare(Point point1, Point point2)
        {
          if (point1.y < point2.y)
            return -1;
          if (point1.y > point2.y)
            return 1;
          return 0;
        }
      }
    );
  }

  public static Pair divideAndConquer(List<? extends Point> points)
  {
    List<Point> pointsSortedByX = new ArrayList<Point>(points);
    sortByX(pointsSortedByX);
    List<Point> pointsSortedByY = new ArrayList<Point>(points);
    sortByY(pointsSortedByY);
    return divideAndConquer(pointsSortedByX, pointsSortedByY);
  }

  private static Pair divideAndConquer(List<? extends Point> pointsSortedByX, List<? extends Point> pointsSortedByY)
  {
    int numPoints = pointsSortedByX.size();
    if (numPoints <= 3)
      return bruteForce(pointsSortedByX);

    int dividingIndex = numPoints >>> 1;
    List<? extends Point> leftOfCenter = pointsSortedByX.subList(0, dividingIndex);
    List<? extends Point> rightOfCenter = pointsSortedByX.subList(dividingIndex, numPoints);

    List<Point> tempList = new ArrayList<Point>(leftOfCenter);
    sortByY(tempList);
    Pair closestPair = divideAndConquer(leftOfCenter, tempList);

    tempList.clear();
    tempList.addAll(rightOfCenter);
    sortByY(tempList);
    Pair closestPairRight = divideAndConquer(rightOfCenter, tempList);

    if (closestPairRight.distance < closestPair.distance)
      closestPair = closestPairRight;

    tempList.clear();
    double shortestDistance =closestPair.distance;
    double centerX = rightOfCenter.get(0).x;
    for (Point point : pointsSortedByY)
      if (Math.abs(centerX - point.x) < shortestDistance)
        tempList.add(point);

    for (int i = 0; i < tempList.size() - 1; i++)
    {
      Point point1 = tempList.get(i);
      for (int j = i + 1; j < tempList.size(); j++)
      {
        Point point2 = tempList.get(j);
        if ((point2.y - point1.y) >= shortestDistance)
          break;
        double distance = distance(point1, point2);
        if (distance < closestPair.distance)
        {
          closestPair.update(point1, point2, distance);
          shortestDistance = distance;
        }
      }
    }
    return closestPair;
  }

  public static void main(String[] args)
  {
    int numPoints = (args.length == 0) ? 1000 : Integer.parseInt(args[0]);
    List<Point> points = new ArrayList<Point>();
    Random r = new Random();
    for (int i = 0; i < numPoints; i++)
      points.add(new Point(r.nextDouble(), r.nextDouble()));
    System.out.println("Generated " + numPoints + " random points");
    long startTime = System.currentTimeMillis();
    Pair bruteForceClosestPair = bruteForce(points);
    long elapsedTime = System.currentTimeMillis() - startTime;
    System.out.println("Brute force (" + elapsedTime + " ms): " + bruteForceClosestPair);
    startTime = System.currentTimeMillis();
    Pair dqClosestPair = divideAndConquer(points);
    elapsedTime = System.currentTimeMillis() - startTime;
    System.out.println("Divide and conquer (" + elapsedTime + " ms): " + dqClosestPair);
    if (bruteForceClosestPair.distance != dqClosestPair.distance)
      System.out.println("MISMATCH");
  }
}


function distance(p1, p2) {
  var dx = Math.abs(p1.x - p2.x);
  var dy = Math.abs(p1.y - p2.y);
  return Math.sqrt(dx*dx + dy*dy);
}

function bruteforceClosestPair(arr) {
  if (arr.length < 2) {
    return Infinity;
  } else {
    var minDist = distance(arr[0], arr[1]);
    var minPoints = arr.slice(0, 2);

    for (var i=0; i<arr.length-1; i++) {
      for (var j=i+1; j<arr.length; j++) {
        if (distance(arr[i], arr[j]) < minDist) {
          minDist = distance(arr[i], arr[j]);
          minPoints = [ arr[i], arr[j] ];
        }
      }
    }
    return {
      distance: minDist,
      points: minPoints
    };
  }
}


# This definition of "until" is included in recent versions (> 1.4) of jq
# Emit the first input that satisfied the condition
def until(cond; next):
  def _until:
    if cond then . else (next|_until) end;
  _until;

# Euclidean 2d distance
def dist(x;y):
  [x[0] - y[0], x[1] - y[1]] | map(.*.) | add | sqrt;