(set-sig-handler sig-int
                 (lambda (signum async-p)
                   (throwf 'error "caught signal ~s" signum)))

(let ((start-time (time)))
  (catch (each ((num (range 1)))
           (format t "~s\n" num)
           (usleep 500000))
    (error (msg)
           (let ((end-time (time)))
             (format t "\n\n~a after ~s seconds of execution\n"
                     msg (- end-time start-time))))))


c="1"
# Trap signals for SIGQUIT (3), SIGABRT (6) and SIGTERM (15)
trap "echo -n 'We ran for ';echo -n `expr $c /2`; echo " seconds"; exit" 3 6 15
while [ "$c" -ne 0 ]; do    # infinite loop
  # wait 0.5    # We need a helper program for the half second interval
  c=`expr $c + 1`
done


Module Module1
    Dim startTime As Date

    Sub Main()
        startTime = Date.Now
        ' Add event handler for Cntrl+C command
        AddHandler Console.CancelKeyPress, AddressOf Console_CancelKeyPress

        Dim counter = 0
        While True
            counter += 1
            Console.WriteLine(counter)
            Threading.Thread.Sleep(500)
        End While
    End Sub

    Sub Console_CancelKeyPress(sender As Object, e As ConsoleCancelEventArgs)
        Dim stopTime = Date.Now
        Console.WriteLine("This program ran for {0:000.000} seconds", (stopTime - startTime).TotalMilliseconds / 1000)
        Environment.Exit(0)
    End Sub

End Module


*!* In VFP, Ctrl+C is normally used to copy text to the clipboard.
*!* Esc is used to stop execution.
CLEAR
SET ESCAPE ON
ON ESCAPE DO StopLoop
CLEAR DLLS
DECLARE Sleep IN WIN32API INTEGER nMilliSeconds
lLoop = .T.
n = 0
? "Press Esc to Cancel..."
t1 = INT(SECONDS())
DO WHILE lLoop
	n = n + 1
	? n
	Sleep(500)
ENDDO
? "Elapsed time:", TRANSFORM(INT(SECONDS()) - t1) + " secs."
CLEAR DLLS
RETURN TO MASTER

PROCEDURE StopLoop
lLoop = .F.
ENDPROC


import "scheduler" for Scheduler
import "timer" for Timer
import "io" for Stdin

var start = System.clock
var stop = false

Scheduler.add {
    var n = 0
    while (true) {
        System.print(n)
        if (stop) {
            var elapsed = System.clock - start + n * 0.5
            System.print("Program has run for %(elapsed) seconds.")
            return
        }
        Timer.sleep(500)
        n = n + 1
    }
}

Stdin.isRaw = true  // enable control characters to go into stdin
while (true) {
    var b = Stdin.readByte()
    if (b == 3 || b == 28) break  // quits on pressing either Ctrl-C os Ctrl-\
}
Stdin.isRaw = false
stop = true


package main

import "fmt"

func main() { fmt.Println("Hello world!") }


proc slice[T](iter: iterator(): T {.closure.}; sl: Slice[T]): seq[T] =
  var i = 0
  for n in iter():
    if i > sl.b: break
    if i >= sl.a: result.add(n)
    inc i

iterator harshad(): int {.closure.} =
  for n in 1 ..<  int.high:
    var sum = 0
    for ch in $n:
      sum += ord(ch) - ord('0')
    if n mod sum == 0:
      yield n

echo harshad.slice 0 ..< 20

for n in harshad():
  if n > 1000:
    echo n
    break


class Harshad {
  function : Main(args : String[]) ~ Nil {
    count := 0;
    for(i := 1; count < 20; i += 1;) {
      if(i % SumDigits(i) = 0){
        "{$i} "->Print();
        count += 1;
      };
    };

    for(i := 1001; true; i += 1;) {
      if(i % SumDigits(i) = 0){
        "... {$i}"->PrintLine();
        break;
      };
    };
  }

  function : SumDigits(n : Int) ~ Int {
    sum := 0;
    do {
      sum += n % 10;
      n /= 10;
    } while(n <> 0);

    return sum;
  }
}


# syntax: GAWK -f HALT_AND_CATCH_FIRE.AWK
#
# This won't halt the CPU but the program will crash immediately on startup
# with "error: division by zero attempted".
BEGIN { 1/0 }
#
# This will heat up the CPU, don't think it will catch on fire.
BEGIN { while(1) {} }
#
# Under TAWK 5.0 using AWKW will immediately abort.
BEGIN { abort(1) }


#include <stdexcept>
int main()
{
    throw std::runtime_error("boom");
}


(define (lists->hash-table keys values . rest)
  (apply alist->hash-table (map cons keys values) rest))


$ include "seed7_05.s7i";

const type: numericHash is hash [string] integer;
var numericHash: myHash is numericHash.value;

const proc: main is func
  local
    var array string: keyList is [] ("one", "two", "three");
    var array integer: valueList is [] (1, 2, 3);
    var integer: number is 0;
  begin
    for number range 1 to length(keyList) do
      myHash @:= [keyList[number]] valueList[number];
    end for;
  end func;


set keyList to ["red", "green", "blue"]
set valueList to [150,0,128]

repeat with n=1 to the number of items in keyList
	set map.(item n of keyList) to item n of valueList
end repeat

put map
--> (blue:"128", green:"0", red:"150")


var keys = %w(a b c)
var vals = [1, 2, 3]

var hash = Hash()
hash{keys...} = vals...
say hash


Array extend [
  dictionaryWithValues: array [ |d|
    d := Dictionary new.
    1 to: ((self size) min: (array size)) do: [:i|
      d at: (self at: i) put: (array at: i).
    ].
    ^ d
  ]
].

({ 'red' . 'one' . 'two' }
 dictionaryWithValues: { '#ff0000'. 1. 2 }) displayNl.


  [ $ "bigrat.qky" loadfile ] now!

  0 n->v
  20 times
    [ i^ 1+ n->v 1/v v+
      2dup 20 point$ echo$
      say " = "
      2dup vulgar$ echo$ cr ]
  2drop
  cr
  1 temp put
  0 n->v 1
  [ dup dip
      [ n->v 1/v v+
       temp share n->v 2over v< ]
    swap if
      [ temp share echo
        say " : "
        dup echo cr
        1 temp tally ]
    temp share 11 < while
    1+
    again ]
  temp release
  drop 2drop


HofN <- function(n) sum(1/seq_len(n)) #Task 1
H <- sapply(1:100000, HofN)
print(H[1:20]) #Task 2
print(sapply(1:10, function(x) which.max(H > x))) #Task 3 and stretch


use Lingua::EN::Numbers;

my @H = [\+] (1..*).map: { FatRat.new: 1, $_ };

say "First twenty harmonic numbers as rationals:\n",
    @H[^20]».&pretty-rat.batch(5)».fmt("%18s").join: "\n";

put "\nOne Hundredth:\n", pretty-rat @H[99];

say "\n(zero based) Index of first value:";
printf "  greater than %2d: %6s (%s term)\n",
  $_, comma( my $i = @H.first(* > $_, :k) ), ordinal 1 + $i for 1..10;


/*REXX pgm to calculate N numbers (sums) in the harmonic series and also when they > X. */
parse arg digs sums high ints                    /*obtain optional arguments from the CL*/
if digs='' | digs=","  then digs= 80             /*Not specified?  Then use the default.*/
if sums='' | sums=","  then sums= 20             /* "      "         "   "   "      "   */
if high='' | high=","  then high= 10             /* "      "         "   "   "      "   */
if ints='' | ints=","  then ints= 1 2 3 4 5 6 7 8 9 10  /*Not specified? "   "      "   */
w= length(sums) + 2                              /*width of Nth harmonic index + suffix.*/
numeric digits digs                              /*have REXX use more numeric dec. digs.*/
                         s= 0                    /*initialize harmonic series sum to 0. */
      do j=1  for sums;  s= s + 1/j              /*calc  "sums" of harmonic series nums.*/
      @iter= right((j)th(j), w)                  /*obtain a nicely formatted sum index. */
      say right(@iter, w)  'harmonic sum ──►'  s /*indent the output to the terminal.   */
      end   /*j*/
say                                              /*have a blank line between output sets*/
many= words(ints)                                /*obtain number of limits to be used.  */
z= word(ints, 1)                                 /*   "   the first   "     "  "   "    */
lastInt= word(ints, many)                        /*   "    "  last    "     "  "   "    */
w= length(lastInt)                               /*W:  is the maximum width of any limit*/
#= 1                                             /*a pointer to a list of integer limits*/
                    s= 0                         /*initialize harmonic series sum to 0. */
      do j=1;       s= s + 1/j                   /*calculate sums of harmonic sum index.*/
      if s<=z  then iterate                      /*Is sum <= a limit?  Then keep going. */
      iter= commas(j)th(j)                       /*obtain a nicely formatted sum index. */
      L= length(iter)                            /*obtain length so as to align output. */
      @iter= right(iter, max(L, 25) )            /*indent the output to the terminal.   */
      say @iter " iteration of the harmonic series, the sum is greater than "  right(z, w)
      #= # + 1                                   /*bump the pointer to the next limit.  */
      if #>many  then leave                      /*Are at the end of the limits?  Done. */
      z= word(ints, #)                           /*point to the next limit to be used.  */
      end   /*j*/                                /* [↑]  above indices are unity─based. */
exit 0                                           /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
commas: parse arg ?;  do jc=length(?)-3  to 1  by -3; ?=insert(',', ?, jc); end;  return ?
th:     parse arg x;  return word('th st nd rd', 1 + (x//10) *(x//100%10\==1) *(x//10<4))


ageName:=T(27,"Jonah", 18,"Alan", 28,"Glory", 18,"Popeye", 28,"Alan");
nameNemesis:=T("Jonah","Whales", "Jonah","Spiders", "Alan","Ghosts",
      "Alan","Zombies", "Glory","Buffy");

fcn addAN(age,name,d){  // keys are names, values are ( (age,...),() )
   if (r:=d.find(name)) d[name] = T(r[0].append(age),r[1]);
   else d.add(name,T(T(age),T));
   d	// return d so pump will use that as result for assignment
}
fcn addNN(name,nemesis,d){ // values-->( (age,age...), (nemesis,...) )
   if (r:=d.find(name)){
      ages,nemesises := r;
      d[name] = T(ages,nemesises.append(nemesis));
   }
}
    // Void.Read --> take existing i, read next one, pass both to next function
var d=ageName.pump(Void,Void.Read,T(addAN,Dictionary()));
nameNemesis.pump(Void,Void.Read,T(addNN,d));

d.println();  // the union of the two tables
d.keys.sort().pump(Console.println,'wrap(name){  //pretty print the join
   val:=d[name]; if (not val[1])return(Void.Skip);
   String(name,":",d[name][1].concat(","));
})


%define sys_signal 	48
%define SIGINT			2
%define sys_time	13

extern usleep
extern printf

section .text
	global _start

	_sig_handler:
		mov ebx, end_time
		mov eax, sys_time
		int 0x80
		mov eax, dword [start_time]
		mov ebx, dword [end_time]
		sub ebx, eax
		mov ax, 100
		div ebx
		push ebx
		push p_time
		call printf
		push 0x1
		mov eax, 1
		push eax
		int 0x80
		ret

	_start:
		mov ebx, start_time
		mov eax, sys_time
		int 0x80
		mov ecx, _sig_handler
		mov ebx, SIGINT
		mov eax, sys_signal
		int 0x80
		xor edi, edi
		.looper:
			push 500000
			call usleep
			push edi
			push p_cnt
			call printf
			inc edi
		jmp .looper

section .data
p_time	db "The program has run for %d seconds.",13,10,0
p_cnt		db "%d",13,10,0

section .bss
start_time	resd 1
end_time		resd 1


var t=Time.Clock.time;
try{ n:=0; while(1){(n+=1).println(); Atomic.sleep(0.5)} }
catch{ println("ran for ",Time.Clock.time-t," seconds"); System.exit() }


: sumDigits(n)  0 while(n) [ n 10 /mod ->n + ] ;
: isHarshad     dup sumDigits mod 0 == ;

1100 seq filter(#isHarshad) dup left(20) println dup filter(#[ 1000 > ]) first println


/* REXX ---------------------------------------------------------------
* 21.01.2014 Walter Pachl modi-(simpli-)fied from REXX version 1
*--------------------------------------------------------------------*/
  Parse Arg x y .                   /* get optional arguments:  X  Y */
  If x='' Then x=20                 /* Not specified?  Use default   */
  If y='' Then y=1000               /* "      "        "     "       */
  n=0                               /* Niven count                   */
  nl=''                             /* Niven list.                   */

  Do j=1 Until n=x                  /* let's go Niven number hunting.*/
    If j//sumdigs(j)=0 Then Do      /* j is a Niven number           */
      n=n+1                         /* bump Niven count              */
      nl=nl j                       /* add to list.                  */
      End
    End

  Say 'first' n 'Niven numbers:'nl

  Do j=y+1                          /* start with first candidate    */
    If j//sumdigs(j)=0 Then         /* j is a Niven number           */
      Leave
    End

  Say 'first Niven number >' y 'is:' j
  Exit

sumdigs: Procedure                  /* compute sum of n's digits     */
  Parse Arg n
  sum=left(n,1)
  Do k=2 To length(n)
    sum=sum+substr(n,k,1)
    End
  Return sum


package main; import "fmt"; func main(){a, b := 0, 0; fmt.Println(a/b)}


*       # Fill arrays
        keys = array(5); vals = array(5)
        ks = 'ABCDE'; vs = '12345'
kloop   i = i + 1; ks len(1) . keys<i> = :s(kloop)
vloop   j = j + 1; vs len(1) . vals<j> = :s(vloop)

*       # Create hash
        hash = table(5)
hloop   k = k + 1; hash<keys<k>> = vals<k> :s(hloop)

*       # Test and display
        ts = 'ABCDE'
tloop   ts len(1) . ch = :f(out)
        str = str ch ':' hash<ch> ' ' :(tloop)
out     output = str
end


let keys = { "foo", "bar", "baz" };
let vals = { 13, 37, 42 };
var hash = {};
for var i = 0; i < sizeof keys; i++ {
    hash[keys[i]] = vals[i];
}


structure StringMap = BinaryMapFn (struct
                                     type ord_key = string
                                     val compare = String.compare
                                   end);

val keys = [ "foo", "bar", "baz" ]
and vals = [ 16384, 32768, 65536 ]
and myMap = StringMap.empty;

val myMap = foldl StringMap.insert' myMap (ListPair.zipEq (keys, vals));


let keys = ["a","b","c"]
let vals = [1,2,3]
var hash = [String: Int]()
for (key, val) in zip(keys, vals) {
  hash[key] = val
}


set keys   [list fred bob joe]
set values [list barber plumber tailor]
array set arr {}
foreach a $keys b $values { set arr($a) $b }

parray arr


decimals(12)
sum = 0
nNew = 1
limit = 13000
Harmonic = []

for n = 1 to limit
    sum += 1/n
    add(Harmonic,[n,sum])
next

see "The first twenty harmonic numbers are:" + nl
for n = 1 to 20
    see "" + Harmonic[n][1] + " -> " + Harmonic[n][2] + nl
next
see nl

for m = 1 to 10
    for n = nNew to len(Harmonic)
        if Harmonic[n][2] > m
           see "The first harmonic number greater than "
           see "" + m + " is " + Harmonic[n][2] + ", at position " + n + nl
           nNew = n
           exit
        ok
    next
next


use num::rational::Ratio;
use num::{BigInt, FromPrimitive};

fn main() {
    for n in 1..=20 {
        println!("Harmonic number {} = {}", n, harmonic_number(n.into()));
    }

    println!("Harmonic number 100 = {}", harmonic_number(100.into()));

    let max = 5;
    let mut target = 1;
    let mut i = 1;
    while target <= max {
        if harmonic_number(i.into()) > Ratio::from_integer(FromPrimitive::from_u64(target).unwrap())
        {
            println!("Position of first term > {} is {}", target, i);
            target += 1;
        }
        i += 1;
    }
}

fn harmonic_number(n: BigInt) -> Ratio<BigInt> {
    let mut result: Ratio<BigInt> = Ratio::from_integer(FromPrimitive::from_u8(0).unwrap());
    let mut i: BigInt = FromPrimitive::from_u8(1).unwrap();
    let one: Ratio<BigInt> = Ratio::from_integer(FromPrimitive::from_u8(1).unwrap());

    while i <= n {
        result = &result + &one / &i;
        i += 1;
    }

    result
}


module main;
  integer n, i;
  real h;

  initial begin
    h = 0.0;

    $display("The first twenty harmonic numbers are:");
    for(n=1; n<=20; n=n+1) begin
      h = h + 1.0 / n;
      $display(n, "  ", h);
    end
    $display("");

    h = 1.0;
    n = 2;
    for(i=2; i<=10; i=i+1) begin
      while (h < i) begin
        h = h + 1.0 / n;
        n = n + 1;
      end
      $write("The first harmonic number greater than ");
      $display(i, " is ", h, ", at position ", n-1);
    end
    $finish ;
  end
endmodule


import "/big" for BigRat
import "/fmt" for Fmt

var harmonic = Fn.new { |n| (1..n).reduce(BigRat.zero) { |sum, i| sum + BigRat.one/i } }

BigRat.showAsInt = true
System.print("The first 20 harmonic numbers and the 100th, expressed in rational form, are:")
var numbers = (1..20).toList
numbers.add(100)
for (i in numbers) Fmt.print("$3d : $s", i, harmonic.call(i))

System.print("\nThe first harmonic number to exceed the following integers is:")
var i = 1
var limit = 10
var n = 1
var h = 0
while (true) {
    h = h + 1/n
    if (h > i) {
        Fmt.print("integer = $2d  -> n = $,6d  ->  harmonic number = $9.6f (to 6dp)", i, n, h)
        i = i + 1
        if (i > limit) return
    }
    n = n + 1
}


program Niven;

{$IFDEF FPC}
  {$MODE DELPHI}
{$ENDIF}

const
  base = 10;

type
  tNum = longword; {Uint64}
{$IFDEF FPC}

const
  cntbasedigits = trunc(ln(High(tNum)) / ln(base)) + 1;
{$ELSE}

var
  cntbasedigits: Integer = 0;
{$ENDIF}

type
  tSumDigit = record
    sdNumber: tNum;
{$IFDEF FPC}
    sdDigits: array[0..cntbasedigits - 1] of byte;
{$ELSE}
    sdDigits: TArray<Byte>;
{$ENDIF}
    sdSumDig: byte;
    sdIsNiven: boolean;
  end;

function InitSumDigit(n: tNum): tSumDigit;
var
  sd: tSumDigit;
  qt: tNum;
  i: integer;
begin
  with sd do
  begin
    sdNumber := n;
{$IFDEF FPC}
    fillchar(sdDigits, SizeOf(sdDigits), #0);
{$ELSE}
    SetLength(sdDigits,cntbasedigits);
    fillchar(sdDigits[0], SizeOf(sdDigits), #0);
{$ENDIF}
    sdSumDig := 0;
    sdIsNiven := false;
    i := 0;
    // calculate Digits und sum them up
    while n > 0 do
    begin
      qt := n div base;
      {n mod base}
      sdDigits[i] := n - qt * base;
      inc(sdSumDig, sdDigits[i]);
      n := qt;
      inc(i);
    end;
    if sdSumDig > 0 then
      sdIsNiven := (sdNumber mod sdSumDig = 0);
  end;
  InitSumDigit := sd;
end;

procedure IncSumDigit(var sd: tSumDigit);
var
  i, d: integer;
begin
  i := 0;
  with sd do
  begin
    inc(sdNumber);
    repeat
      d := sdDigits[i];
      inc(d);
      inc(sdSumDig);
      //base-1 times the repeat is left here
      if d < base then
      begin
        sdDigits[i] := d;
        BREAK;
      end
      else
      begin
        sdDigits[i] := 0;
        dec(sdSumDig, base);
        inc(i);
      end;
    until i > high(sdDigits);
    sdIsNiven := (sdNumber mod sdSumDig) = 0;
  end;
end;

var
  MySumDig: tSumDigit;
  lnn: tNum;
  cnt: integer;

begin
{$IFNDEF FPC}
  cntbasedigits := trunc(ln(High(tNum)) / ln(base)) + 1;
{$ENDIF}

  MySumDig := InitSumDigit(0);
  cnt := 0;
  repeat
    IncSumDigit(MySumDig);
    if MySumDig.sdIsNiven then
    begin
      write(MySumDig.sdNumber, '.');
      inc(cnt);
    end;
  until cnt >= 20;
  write('....');
  MySumDig := InitSumDigit(1000);
  repeat
    IncSumDigit(MySumDig);
  until MySumDig.sdIsNiven;
  writeln(MySumDig.sdNumber, '.');
// searching for big gaps between two niven-numbers
//  MySumDig:=InitSumDigit(18879989100-276);
  MySumDig := InitSumDigit(1);
  cnt := 0;
  lnn := MySumDig.sdNumber;
  repeat
    IncSumDigit(MySumDig);
    if MySumDig.sdIsNiven then
    begin
      if cnt < (MySumDig.sdNumber - lnn) then
      begin
        cnt := (MySumDig.sdNumber - lnn);
        writeln(lnn, ' --> ', MySumDig.sdNumber, '  d=', cnt);
      end;
      lnn := MySumDig.sdNumber;
    end;
  until MySumDig.sdNumber = High(tNum);
{
689988915 --> 689989050  d=135
879987906 --> 879988050  d=144
989888823 --> 989888973  d=150
2998895823 --> 2998895976  d=153
~ 24 Cpu-cycles per test i3- 4330 1..2^32-1}
{$IFNDEF LINUX}readln;{$ENDIF}
end.


 > quackery

Welcome to Quackery.

Enter "leave" to leave the shell.

Building extensions.

/O> ' tuck take
...

Quackery system damage detected.
Python reported: maximum recursion depth exceeded


try
   see 5/0
catch
   see "Catch!" + nl + cCatchError
done


fatalError("You've met with a terrible fate, haven't you?")


keys=( foo bar baz )
values=( 123 456 789 )
declare -A hash

for (( i = 0; i < ${#keys[@]}; i++ )); do
  hash["${keys[i]}"]=${values[i]}
done

for key in "${!hash[@]}"; do
  printf "%s => %s\n" "$key" "${hash[$key]}"
done


cat <<VAL >p.values
apple
boy
cow
dog
elephant
VAL

cat <<KEYS >p.keys
a
b
c
d
e
KEYS

paste -d\   <(cat p.values | sort) <(cat p.keys | sort)


keys   = <'foo','bar','baz'>
values = <12354,145430,76748>

hash_function = keys-$values


using Gee;

void main(){
    // mostly copied from C# example
    var hashmap = new HashMap<string, string>();

    string[] arg_keys = {"foo", "bar", "val"};
    string[] arg_values = {"little", "miss", "muffet"};

    if (arg_keys.length	== arg_values.length ){
	for (int i = 0;	i < arg_keys.length; i++){
            hashmap[arg_keys[i]] = arg_values[i];
	}
    }
}


func real Harmonic(N);  \Return Nth harmonic number
int  N;  real X;
[X:= 1.0;
while N >= 2 do
        [X:= X + 1.0/float(N);  N:= N-1];
return X;
];

int N, M;
[for N:= 1 to 20 do
    [RlOut(0, Harmonic(N));
    if rem(N/5) = 0 then CrLf(0);
    ];
for M:= 1 to 10 do
    [N:= 1;
    repeat N:= N+1 until Harmonic(N) > float(M);
    IntOut(0, M);
    Text(0, ": ");
    IntOut(0, N);
    CrLf(0);
    ];
]


#!/usr/bin/perl
use strict ;
use warnings ;
use List::Util qw ( sum ) ;

sub createHarshads {
   my @harshads ;
   my $number = 1 ;
   do {
      if ( $number % sum ( split ( // , $number ) ) == 0 ) {
	 push @harshads , $number ;
      }
      $number++ ;
   } until (  $harshads[ -1 ] > 1000 ) ;
   return @harshads ;
}
my @harshadnumbers = createHarshads ;
for my $i ( 0..19 ) {
   print "$harshadnumbers[ $i ]\n" ;
}
print "The first Harshad number greater than 1000 is $harshadnumbers[ -1 ]!\n" ;


integer n = 0
sequence digits={0}

procedure nNiven()
    while 1 do
        n += 1
        for i=length(digits) to 0 by -1 do
            if i=0 then
                digits = prepend(digits,1)
                exit
            end if
            if digits[i]<9 then
                digits[i] += 1
                exit
            end if
            digits[i] = 0
        end for
        if remainder(n,sum(digits))=0 then exit end if
    end while
end procedure

sequence s = {}
for i=1 to 20 do
    nNiven()
    s &= n
end for
?s
while n<=1000 do
    nNiven()
end while
?n


Set dict = CreateObject("Scripting.Dictionary")
os = Array("Windows", "Linux", "MacOS")
owner = Array("Microsoft", "Linus Torvalds", "Apple")
For n = 0 To 2
    dict.Add os(n), owner(n)
Next
MsgBox dict.Item("Linux")
MsgBox dict.Item("MacOS")
MsgBox dict.Item("Windows")


Dim dict As New Collection
os = Array("Windows", "Linux", "MacOS")
owner = Array("Microsoft", "Linus Torvalds", "Apple")
For n = 0 To 2
    dict.Add owner(n), os(n)
Next
Debug.Print dict.Item("Linux")
Debug.Print dict.Item("MacOS")
Debug.Print dict.Item("Windows")


let a => import 'arrays';
let s => import 'stream';

let toScope keys vals =>
    s.zip (a.stream keys) (a.stream vals)
    ->
        s.reduce (collect (true)) (@ r scope kv =>
            let [k v] => kv;
            set scope k v;
        )
    ;


fn main() {
    keys := ["a", "b", "c"]
    vals := [1, 2, 3]
    mut hash := map[string]int{}
    for i, key in keys {
        hash[key] = vals[i]
    }
    println(hash)
}


var keys = [1, 2, 3, 4, 5]
var values = ["first", "second", "third", "fourth","fifth"]
var hash = {}
(0..4).each { |i| hash[keys[i]] = values[i] }
System.print(hash)


use fmt;

export fn main() void = {
	fmt::println("Hello, world!")!;
};


#if niven number, return it.
(de niven (N)
   (if (=0 (% N (apply + (getN N)))) N) )

#function which creates a list of numbers from input
(de getN (N)
   (mapcar format (chop N)) )

#This function generates niven number list
(de nivGen (R N)
   (extract niven (range R N)) )

#print 1st 20 niven numbers and 1st niven number greater than 1000
(printsp ~(list ~(head 20
                    (nivGen 1 1000) ) (max ~(nivGen 1001 1010)) ) )


C :n=0
  :i=0
*first20
U :*harshad
C :i=i+1
T :#i: #n
J (i<20):*first20
C :n=1000
U :*harshad
T :First Harshad number greater than 1000: #n
E :
*harshad
C :n=n+1
  :r=n
  :s=0
*digit
C :a=r/10
  :s=s+(r-a*10)
  :r=a
J (r):*digit
J (n<>s*(n/s)):*harshad
E :


*process source or(!) xref attributes;
 niven: Proc Options(main);
 /*********************************************************************
 * 08-06.2013 Walter Pachl translated from Rexx
 *                         with a slight improvement:  Do j=y+1 By 1;
 *********************************************************************/
 Dcl (ADDR,HBOUND,MOD,SUBSTR,VERIFY) Builtin;
 Dcl SYSPRINT Print;

 Dcl (x,y) dec fixed(8);
 x=20;
 y=1000;
 Begin;
   Dcl (n(x),j) Dec Fixed(8);
   Dcl ni Bin Fixed(31) Init(0);
   Dcl result Char(100) Var Init('');
 loop:
   Do j=1 By 1;
     If mod(j,sumdigs(j))=0 Then Do;
       ni+=1;
       n(ni)=j;
       result=result!!' '!!d2c(j);
       If ni=x Then Leave loop;
       End;
     End;
   Put Edit('first 20 Niven numbers: ',result)(Skip,a,a);
   Do j=y+1 By 1;
     If mod(j,sumdigs(j))=0 Then
       Leave;
     End;
   Put Edit('first Niven number > ',d2c(y),' is: ',d2c(j))(Skip,4(a));
   End;

 sumDigs: proc(z) Returns(Dec Fixed(3));
 Dcl z Pic'(8)9';
 Dcl d(8) Pic'9' Based(addr(z));
 Dcl i Bin Fixed(31);
 Dcl sd Dec Fixed(3) Init(0);
 Do i=1 To hbound(d);
   sd+=d(i);
   End;
 Return(sd);
 End;

 d2c: Proc(z) Returns(char(8) Var);
 Dcl z Pic'(8)z';
 Dcl p Bin Fixed(31);
 p=verify(z,' ');
 Return(substr(z,p));
 End;

 End;


keys:=T("a","b","c","d"); vals:=T(1,2,3,4);
d:=keys.zip(vals).toDictionary();
d.println();
d["b"].println();


100H:

/* FIND THE SUM OF THE DIGITS OF A 16-BIT NUMBER */
DIGIT$SUM: PROCEDURE(N) BYTE;
    DECLARE N ADDRESS, SUM BYTE;
    SUM = 0;
    DO WHILE N > 0;
        SUM = SUM + (N MOD 10);
        N = N / 10;
    END;
    RETURN SUM;
END DIGIT$SUM;

/* FIND THE NEXT HARSHAD NUMBER ABOVE N */
NEXT$HARSHAD: PROCEDURE(N) ADDRESS;
    DECLARE N ADDRESS;
NEXT:
    N = N + 1;
    IF N MOD DIGIT$SUM(N) = 0 THEN
        RETURN N;
    ELSE
        GO TO NEXT;
END NEXT$HARSHAD;

/* CP/M SYSCALL */
BDOS: PROCEDURE(FUNC, ARG);
    DECLARE FUNC BYTE, ARG ADDRESS;
    GO TO 5;
END BDOS;

/* PRINT A STRING */
PRINT$STRING: PROCEDURE(STRING);
    DECLARE STRING ADDRESS;
    CALL BDOS(9, STRING);
END PRINT$STRING;

/* PRINT A NUMBER */
PRINT$NUMBER: PROCEDURE(N);
    DECLARE S (7) BYTE INITIAL ('..... $');
    DECLARE (N, P) ADDRESS, (C BASED P) BYTE;
    P = .S(5);
DIGIT:
    P = P - 1;
    C = (N MOD 10) + '0';
    N = N / 10;
    IF N > 0 THEN GO TO DIGIT;
    CALL PRINT$STRING(P);
END PRINT$NUMBER;

DECLARE CRLF DATA (13,10,'$');
DECLARE N ADDRESS INITIAL (0), S BYTE;

/* PRINT FIRST 20 HARSHADS */
CALL PRINT$STRING(.'FIRST 20: $');
DO S = 1 TO 20;
    CALL PRINT$NUMBER(N := NEXT$HARSHAD(N));
END;
CALL PRINT$STRING(.CRLF);

/* PRINT HARSHAD NUMBER ABOVE 1000 */
CALL PRINT$STRING(.'FIRST ABOVE 1000: $');
CALL PRINT$NUMBER(NEXT$HARSHAD(1000));
CALL PRINT$STRING(.CRLF);

CALL BDOS(0,0);
EOF


   1..1000 | Where { $_ % ( [int[]][string[]][char[]][string]$_ | Measure -Sum ).Sum -eq 0 } | Select -First 20
1001..2000 | Where { $_ % ( [int[]][string[]][char[]][string]$_ | Measure -Sum ).Sum -eq 0 } | Select -First 1


program goodbyeWorld;
#include("stdlib.hhf")
begin goodbyeWorld;

  stdout.put( "Hello world!" nl );

end goodbyeWorld;


:- use_module(library(lambda)).

niven :-
	nb_setval(go, 1),

	L = [1 | _],
	print_niven(L, 1),
	gen_niven(1, L).

print_niven([X|T], N) :-
	when(ground(X),
	     (	 (   nb_getval(go, 1)
		 ->  (   N < 20
		     ->  writeln(X),
			 N1 is N+1,
			 print_niven(T, N1)
		     ;	 (   X > 1000
			 ->  writeln(X),
			     nb_setval(go, 0)
			 ;   N1 is N+1,
			     print_niven(T, N1)))
		 ;   true))).

gen_niven(X, [N | T]) :-
	(   nb_getval(go, 1)
	->  X1 is X+1,
	    sum_of_digit(X, S),
	    (   X mod S =:= 0
	    ->  N = X,
		gen_niven(X1, T)
	    ;	gen_niven(X1, [N | T]))
	;   true).

sum_of_digit(N, S) :-
	number_chars(N, LC),
	maplist(\X^Y^number_chars(Y, [X]), LC, LN),
	sum_list(LN, S).


If OpenConsole()=0 : End 1 : EndIf

Procedure.i Niven(v.i)
  w=v
  While v : s+v%10 : v/10 : Wend
  If w%s=0 : ProcedureReturn w : EndIf
EndProcedure

Repeat
  i+1
  If Niven(i) : c+1 : Print(Str(i)+" ") : EndIf
  If c=20 And i<1000 : Print("... ") : i=1000 : EndIf
  If c=21 : Break : EndIf
ForEver

Input()


>>> import itertools
>>> def harshad():
	for n in itertools.count(1):
		if n % sum(int(ch) for ch in str(n)) == 0:
			yield n

>>> list(itertools.islice(harshad(), 0, 20))
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 18, 20, 21, 24, 27, 30, 36, 40, 42]
>>> for n in harshad():
	if n > 1000:
		print(n)
		break

1002
>>>


[ number$ $ "0 " swap
  witheach
    [ join $ " + " join ]
  quackery ]               is digitsum  ( n --> n )

[ dup digitsum
  mod 0 = ]                is isharshad ( n --> b )

say "The first 20 Harshad numbers are: "

0 1
  [ dup isharshad if
     [ dup echo sp dip 1+ ]
    1+
    over 20 = until ]
2drop
cr
cr
say "The first Harshad number greater than 1000 is: "

1000 [ 1+ dup isharshad
       iff echo done
       again ]
cr


#lang racket

(define (digsum n)
  (for/sum ([c (number->string n)]) (string->number [string c])))

(define harshads
  (stream-filter (λ (n) (= (modulo n (digsum n)) 0)) (in-naturals 1)))

; First 20 harshad numbers
(displayln (for/list ([i 20]) (stream-ref harshads i)))

; First harshad greater than 1000
(displayln (for/first ([h harshads] #:when(> h 1000)) h))


#! /bin/sh
exec huginn --no-argv -E "${0}" "${@}"
#! huginn

main() {
	print( "Hello World!\n" );
	return ( 0 );
}


constant @harshad = grep { $_ %% .comb.sum }, 1 .. *;

say @harshad[^20];
say @harshad.first: * > 1000;


/*REXX program finds the first  A  Niven numbers;  it also finds first Niven number > B.*/
parse arg A B .                                  /*obtain optional arguments from the CL*/
if A=='' | A==','  then A=   20                  /*Not specified?  Then use the default.*/
if B=='' | B==','  then B= 1000                  /* "      "         "   "    "     "   */
numeric digits 1+max(8, length(A), length(B) )   /*enable the use of any sized numbers. */
#= 0;      $=                                    /*set Niven numbers count;  Niven list.*/
                        do j=1  until  #==A      /*◄───── let's go Niven number hunting.*/
                        if j // sumDigs(j)==0  then do;   #= #+1;   $= $ j;    end
                        end   /*j*/              /* [↑]   bump count; append J ──► list.*/
say 'first'   A   'Niven numbers:'   $           /*display list of Niven numbers──►term.*/
                do t=B+1  until t//sumDigs(t)==0 /*hunt for a Niven (or Harshad) number.*/
                end   /*t*/
say 'first Niven number >'   B    " is: "     t  /*display 1st Niven number >   B.      */
exit                                             /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
sumDigs: parse arg x 1 s 2 q;   do k=1  for length(q); s= s+substr(q,k,1); end;   return s


i = 1
count = 0
while true
      sum = 0
      if niven(i) = 1
         if count < 20 see "" + i + " is a Niven number" + nl count +=1 ok
         if i > 1000 see "" + i + " is a Niven number" exit ok ok
      i + =1
end

func niven nr
     nrString = string(nr)
     for j = 1 to len(nrString)
         sum = sum + number(nrString[j])
     next
     niv = ((nr % sum) = 0)
     return niv


harshad = 1.step.lazy.select { |n| n % n.digits.sum == 0 }

puts "The first 20 harshard numbers are: \n#{ harshad.first(20) }"
puts "The first harshard number > 1000 is #{ harshad.find { |n| n > 1000 } }"


procedure main()
  write( "Hello world!" )
end


while count < 20
  h = h + 1
  if neven(h) = 0 then
    count = count + 1
    print count;": ";h
  end if
wend

h = 1000
while 1 = 1
  h = h + 1
  if neven(h) = 0 then
    print h
    exit while
  end if
wend

function neven(h)
h$ = str$(h)
for i = 1 to len(h$)
 d = d + val(mid$(h$,i,1))
next i
neven = h mod d
end function


fn is_harshad (n : u32) -> bool {
    let sum_digits = n.to_string()
                      .chars()
                      .map(|c| c.to_digit(10).unwrap())
                      .fold(0, |a, b| a+b);
    n % sum_digits == 0
}

fn main() {
    for i in (1u32..).filter(|num| is_harshad(*num)).take(20) {
        println!("Harshad : {}", i);
    }
    for i in (1_001u32..).filter(|num| is_harshad(*num)).take(1) {
        println!("First Harshad bigger than 1_000 : {}", i);
    }
}


object Harshad extends App {
  val harshads = Stream.from(1).filter(i => i % i.toString.map(_.asDigit).sum == 0)

  println(harshads.take(20).toList)
  println(harshads.filter(_ > 1000).head)
}


module Main

main : IO ()
main = putStrLn "Hello world!"


#!/usr/local/bin/gosh

;; Show the first 20 niven numbers and the
;; first one greater than 1000.
(define (main args)
    (display (iota-filtered 20 1 niven?))(newline)
    (display (iota-filtered 1 1001 niven?))(newline))

;; Return a list of length n
;; for numbers starting at start
;; that satisfy the predicate fn.
(define (iota-filtered n start fn)
    (let loop ((num start)(lst (list)))
        (if (= (length lst) n)
            lst
            (loop (+ 1 num) (if (fn num) (append lst (list num)) lst)))))

;; Is a number a niven number?
(define (niven? n)
    (and (> n 0) (= 0 (remainder n (sum-of-digits n)))))

;; Get the sum of the digits of a number.
(define (sum-of-digits n)
    (apply + (map string->number (map string (string->list (number->string n))))))


$ include "seed7_05.s7i";

const func integer: sumOfDigits (in var integer: num) is func
  result
    var integer: sum is 0;
  begin
    repeat
      sum +:= num rem 10;
      num := num div 10;
    until num = 0;
  end func;

const func integer: nextHarshadNum (inout integer: num) is func
  result
    var integer: harshadNumber is 0;
  begin
    while num mod sumOfDigits(num) <> 0 do
      incr(num);
    end while;
    harshadNumber := num;
  end func;

const proc: main is func
  local
    var integer: current is 1;
    var integer: count is 0;
  begin
    for count range 1 to 20 do
      write(nextHarshadNum(current) <& " ");
      incr(current);
    end for;
    current := 1001;
    writeln(" ... " <& nextHarshadNum(current));
  end func;


import std::stdio::stdout

stdout.print('Hello, world!')


func harshad() {
    var n = 0;
    {
        ++n while !(n %% n.digits.sum);
        n;
    }
}

var iter = harshad();
say 20.of { iter.run };

var n;
do {
    n = iter.run
} while (n <= 1000);

say n;


 10 FAST
 20 LET N=0
 30 LET H=0
 40 LET N=N+1
 50 LET N$=STR$ N
 60 LET SD=0
 70 FOR I=1 TO LEN N$
 80 LET SD=SD+VAL N$(I)
 90 NEXT I
100 IF N/SD<>INT (N/SD) THEN GOTO 40
110 LET H=H+1
120 IF H<=20 OR N>1000 THEN PRINT N
130 IF N>1000 THEN GOTO 150
140 GOTO 40
150 SLOW


struct Harshad: Sequence, IteratorProtocol {
  private var i = 0

  mutating func next() -> Int? {
    while true {
      i += 1

      if i % Array(String(i)).map(String.init).compactMap(Int.init).reduce(0, +) == 0 {
        return i
      }
    }
  }
}

print("First 20: \(Array(Harshad().prefix(20)))")
print("First over a 1000: \(Harshad().first(where: { $0 > 1000 })!)")


# Determine if the given number is a member of the class of Harshad numbers
proc isHarshad {n} {
    if {$n < 1} {return false}
    set sum [tcl::mathop::+ {*}[split $n ""]]
    return [expr {$n%$sum == 0}]
}

# Get the first 20 numbers that satisfy the condition
for {set n 1; set harshads {}} {[llength $harshads] < 20} {incr n} {
    if {[isHarshad $n]} {
	lappend harshads $n
    }
}
puts [format "First twenty Harshads: %s" [join $harshads ", "]]

# Get the first value greater than 1000 that satisfies the condition
for {set n 1000} {![isHarshad [incr n]]} {} {}
puts "First Harshad > 1000 = $n"


theory Scratch
  imports Main
begin
  value ‹''Hello world!''›
end


C=0

For I = 1 Step 1 Until C = 20          ' First 20 Harshad numbers
  If FUNC(_FNHarshad(I)) Then Print I;" "; : C = C + 1
Next

For I = 1001 Step 1                    ' First Harshad greater than 1000
  If FUNC(_FNHarshad(I)) Then Print I;" " : Break
Next

End

_FNHarshad Param(1)
  Local(2)

  [email protected] = [email protected]
  [email protected] = 0
  Do While ([email protected] > 0)
     [email protected] = [email protected] + ([email protected] % 10)
     [email protected] = [email protected] / 10
  Loop

Return (([email protected] % [email protected]) = 0)


Option Explicit

Sub Main()
Dim i As Long, out As String, Count As Integer
   Do
      i = i + 1
      If IsHarshad(i) Then out = out & i & ", ": Count = Count + 1
   Loop While Count < 20
   Debug.Print "First twenty Harshad numbers are : " & vbCrLf & out & "..."

   i = 1000
   Do
      i = i + 1
   Loop While Not IsHarshad(i)
   Debug.Print "The first harshad number after 1000 is : " & i
End Sub

Function IsHarshad(sNumber As Long) As Boolean
Dim Summ As Long, i As Long, temp
   temp = Split(StrConv(sNumber, vbUnicode), Chr(0))
   For i = LBound(temp) To UBound(temp) - 1
      Summ = Summ + temp(i)
   Next i
   IsHarshad = sNumber Mod Summ = 0
End Function


OPENCONSOLE

PRINT"Hello world!"

'This line could be left out.
PRINT:PRINT:PRINT"Press any key to end."

'Keep the console from closing right away so the text can be read.
DO:UNTIL INKEY$<>""

CLOSECONSOLE

END


n = 0
m = 1
first20 = ""
after1k = ""

Do
	If IsHarshad(m) And n <= 20 Then
		first20 = first20 & m & ", "
		n = n + 1
		m = m + 1
	ElseIf IsHarshad(m) And m > 1000 Then
		after1k = m
		Exit Do
	Else
		m = m + 1
	End If
Loop

WScript.StdOut.Write "First twenty Harshad numbers are: "
WScript.StdOut.WriteLine
WScript.StdOut.Write first20
WScript.StdOut.WriteLine
WScript.StdOut.Write "The first Harshad number after 1000 is: "
WScript.StdOut.WriteLine
WScript.StdOut.Write after1k

Function IsHarshad(s)
	IsHarshad = False
	sum = 0
	For i = 1 To Len(s)
		sum = sum + CInt(Mid(s,i,1))
	Next
	If s Mod sum = 0 Then
		IsHarshad = True
	End If
End Function


LOCAL lnCount As Integer, k As Integer
CLEAR
lnCount = 0
k = 0
*!* First 20 numbers
? "First 20 numbers:"
DO WHILE lnCount < 20
    k = k + 1
    IF Harshad(k)
	lnCount = lnCount + 1
	? lnCount, k
    ENDIF
ENDDO
*!* First such number > 1000
k = 1001
DO WHILE NOT Harshad(k)
    k = k + 1
ENDDO
? "First such number > 1000", k

FUNCTION Harshad(n As Integer) As Boolean
LOCAL cn As String, d As Integer, i As Integer
cn = TRANSFORM(n)
d = 0
FOR i = 1 TO LEN(cn)
    d = d + VAL(SUBSTR(cn, i, 1))
ENDFOR
RETURN n % d = 0
ENDFUNC


class Main {
  function void main () {
    do Output.printString("Hello world!");
    do Output.println();
    return;
  }
}


public class HelloWorld
{
 public static void main(String[] args)
 {
  System.out.println("Hello world!");
 }
}


from jinja2 import Template
print(Template("Hello World!").render())


var niven = Fiber.new {
    var n = 1
    while (true) {
        var i = n
        var sum = 0
        while (i > 0) {
            sum = sum + i%10
            i = (i/10).floor
        }
        if (n%sum == 0) Fiber.yield(n)
        n = n + 1
   }
}

System.print("The first 20 Niven numbers are:")
for (i in 1..20) {
    System.write("%(niven.call()) ")
}
System.write("\n\nThe first Niven number greater than 1000 is: ")
while (true) {
    var niv = niven.call()
    if (niv > 1000) {
        System.print(niv)
        break
    }
}


include c:\cxpl\codes;          \intrinsic 'code' declarations
int H, C, N, S;                 \Harshad number, Counter, Number, Sum
[H:= 1;  C:= 0;
loop    [N:= H;  S:= 0;         \sum digits
        repeat  N:= N/10;
                S:= S + rem(0);
        until   N = 0;
        if rem(H/S) = 0 then    \Harshad no.is evenly divisible by sum of digits
                [if C < 20 then [IntOut(0, H);  ChOut(0, ^ );  C:= C+1];
                if H > 1000 then [IntOut(0, H);  CrLf(0);  quit];
                ];
        H:= H+1;
        ];
]


sub sumDigits(n)
    if n < 0 then return 0 : endif
    local sum
    while n > 0
        sum = sum + mod(n, 10)
        n = int(n / 10)
    wend
    return sum
end sub

sub isHarshad(n)
    return mod(n, sumDigits(n)) = 0
end sub

print "Los primeros 20 numeros de Harshad o Niven son:"
contar = 0
i = 1

repeat
    if isHarshad(i) then
        print i, " ",
        contar = contar + 1
    end if
    i = i + 1
until contar = 20

print : print
print "El primero de esos numeros por encima de 1000 es:"
i = 1001

do
    if isHarshad(i) then
        print i, " "
        break
    end if
    i = i + 1
loop
print
end


fcn harshad(n){ 0==n%(n.split().sum(0)) }
[1..].tweak(fcn(n){ if(not harshad(n)) return(Void.Skip); n })
   .walk(20).println();
[1..].filter(20,harshad).println();
[1001..].filter1(harshad).println();


10 LET k=0: LET n=0
20 IF k=20 THEN GO TO 60
30 LET n=n+1: GO SUB 1000
40 IF isHarshad THEN PRINT n;" ";: LET k=k+1
50 GO TO 20
60 LET n=1001
70 GO SUB 1000: IF NOT isHarshad THEN LET n=n+1: GO TO 70
80 PRINT '"First Harshad number larger than 1000 is ";n
90 STOP
1000 REM is Harshad?
1010 LET s=0: LET n$=STR$ n
1020 FOR i=1 TO LEN n$
1030 LET s=s+VAL n$(i)
1040 NEXT i
1050 LET isHarshad=NOT FN m(n,s)
1060 RETURN
1100 DEF FN m(a,b)=a-INT (a/b)*b


program hello;

Void main() {
    // My first program!
    putStrLn("Hello world!");
}


V2; W0;
RESTART; J999; J999;
PROGRAM;                   (main program);
   V0 = Q0/AV1/AV2;
   V1 = B0750064554545700; ("Hello" in Flexowriter code);
   V2 = B0767065762544477; ("World" in Flexowriter code);
   V0; =Q9; POAQ9;         (write "Hello World" to Flexowriter);
999;  OUT;
   FINISH;


"#!/usr/local/bin/kite

"Hello world!"|print;


fun main() {
  println("Hello world!")
}


function main() {
  Konsol:Log("Hello world!")
}


fun main() {
    println("Hello world!")
}


Hello world!
{h1 Hello world!}
_h1 Hello world!\n


\documentclass{minimal}
\begin{document}
Hello World!
\end{document}


.orig x3000
LEA R0, hello    ; R0 = &hello
TRAP x22         ; PUTS (print char array at addr in R0)
HALT
hello .stringz "Hello World!"
.end


#
# Hello world in lil
#

print "Hello, world!"


\version "2.18.2"
global = {
  \time 4/4
  \key c \major
  \tempo 4=100
}
\relative c''{ g e e( g2)
}
\addlyrics {
  Hel -- lo,   World!
}


implement Command;

 include "sys.m";
     sys: Sys;

 include "draw.m";

 include "sh.m";

 init(nil: ref Draw->Context, nil: list of string)
 {
     sys = load Sys Sys->PATH;
     sys->print("Hello world!\n");
 }


Section Header          // The Header section is required.
  + name := GOODBYE;    // Define the name of this object.

Section Public
  - main <- ("Hello world!\n".print;);


; const char str[14] = "Hello World!\00"
@.str = private unnamed_addr constant  [14 x i8] c"Hello, world!\00"

; declare extern `puts` method
declare i32 @puts(i8*) nounwind

define i32 @main()
{
  call i32 @puts( i8* getelementptr ([14 x i8]* @str, i32 0,i32 0))
  ret i32 0
}


:- object(hello_world).

    % the initialization/1 directive argument is automatically executed
    % when the object is loaded into memory:
    :- initialization(write('Hello world!\n')).

:- end_object.


HAI
CAN HAS STDIO?
VISIBLE "Hello world!"
KTHXBYE


:- object(hello_world).
    'This will send the output to the status bar at the bottom of the Notes client screen
    print "Hello world!"

:- end_object.


def main:
    hello = "Hello, World!"
    print hello


Print "Hello World!" \\ printing on columns, in various ways defined by last $() for specific layer
Print $(4),"Hello World!" \\ proportional printing using columns, expanded to a number of columns as the length of string indicates.
Report "Hello World!"  \\ proportional printing with word wrap, for text, can apply justification and rendering a range of text lines


        TITLE HELLO

COMMENT !
  Hello-World program, PDP-10 assembly language, written by kjx, 2022.
           Assembler: MACRO-10    Operating system: TOPS-20
!

        SEARCH MONSYM                      ;Get symbolic names for system-calls.

GO::    RESET%                             ;System call: Initialize process.

        HRROI 1,[ASCIZ /Hello World!/]     ;Put pointer to string into register 1.
        PSOUT%                             ;System call: Print string.
        HALTF%                             ;System call: Halt program.

        JRST GO                            ;Unconditional jump to GO (in case the
                                           ;user uses the CONTINUE-command while this
                                           ;program is still loaded).

        END GO


;
;          TEXT BASED HELLO WORLD
;          WRITTEN  BY:  BILL GUNSHANNON
;

           .MCALL  .PRINT .EXIT
           .RADIX  10

MESG1:     .ASCII  "  "
           .ASCII  " HELLO WORLD "
           .EVEN

START:
           .PRINT  #MESG1

DONE:

;   CLEAN UP AND GO BACK TO KMON

           .EXIT

           .END     START


           VECTOR VALUES HELLO = $11HHELLO WORLD*$
           PRINT FORMAT HELLO
           END OF PROGRAM


{{extern "manool.org.18/std/0.3/all"} in WriteLine[Out; "Hello world!"]}


> printf( "Hello world!\n" ): # print without quotes
Hello world!


fmod BYE-WORLD is

	protecting STRING .

	op sayBye : -> String .

	eq sayBye = "Hello world!" .

endfm

red sayBye .


:- module hello.
:- interface.
:- import_module io.
:- pred main(io::di, io::uo) is det.

:- implementation.
main(!IO) :-
    io.write_string("Hello world!\n", !IO).


   .data #section for declaring variables
hello:  .asciiz "Hello world!" #asciiz automatically adds the null terminator. If it's .ascii it doesn't have it.

   .text # beginning of code
main: # a label, which can be used with jump and branching instructions.
   la $a0, hello # load the address of hello into $a0
   li $v0, 4 # set the syscall to print the string at the address $a0
   syscall # make the system call

   li $v0, 10 # set the syscall to exit
   syscall # make the system call


MODULE Hello;
IMPORT InOut;

BEGIN
  InOut.WriteString('Hello world!');
  InOut.WriteLn
END Hello.


MODULE Goodbye EXPORTS Main;

IMPORT IO;

BEGIN
  IO.Put("Hello world!\n");
END Goodbye.


import morfa.io.print;
func main(): void
{
    println("Hello world!");
}


proc start =
      println "Hello, world"
end


: main[ -- ]
me @ "Hello world!" notify
exit
;


script HelloWorld {
    func main returns: int {
        print("Hello World!")
    }
}


class Hello
{
  static Main () : void
  {
    System.Console.WriteLine ("Hello world!");
  }
}


func main() -> int {
    prints("Hello world!\n");
    0
}


@CODE
"output.txt" << "Hello world!";
@@CODE


MODULE Goodbye;
IMPORT Out;
  PROCEDURE World*;
  BEGIN
    Out.String("Hello world!");Out.Ln
  END World;
BEGIN
  World;
END Goodbye.


class Hello {
  function : Main(args : String[]) ~ Nil {
    "Hello world!"->PrintLine();
  }
}


#import <Foundation/Foundation.h>

int main() {
    @autoreleasepool {
        NSLog(@"Hello, World!");
    }
}


#USE "course.lib"
PROC main (CHAN BYTE screen!)
  out.string("Hello world!*c*n", 0, screen)
:


package main
import "core:fmt"

main :: proc() {
  fmt.println("Hellope!");
}


F haversine(=lat1, lon1, =lat2, lon2)
   V r = 6372.8
   V dLat = radians(lat2 - lat1)
   V dLon = radians(lon2 - lon1)
   lat1 = radians(lat1)
   lat2 = radians(lat2)
   V a = sin(dLat / 2) ^ 2 + cos(lat1) * cos(lat2) * sin(dLon / 2) ^ 2
   V c = 2 * asin(sqrt(a))
   R r * c

print(haversine(36.12, -86.67, 33.94, -118.40))


  DATA: X1 TYPE F, Y1 TYPE F,
        X2 TYPE F, Y2 TYPE F, YD TYPE F,
        PI TYPE F,
        PI_180 TYPE F,
        MINUS_1 TYPE F VALUE '-1'.

PI     = ACOS( MINUS_1 ).
PI_180 = PI / 180.

LATITUDE1 = 36,12 . LONGITUDE1 = -86,67 .
LATITUDE2 = 33,94 . LONGITUDE2 = -118,4 .

  X1 = LATITUDE1  * PI_180.
  Y1 = LONGITUDE1 * PI_180.
  X2 = LATITUDE2  * PI_180.
  Y2 = LONGITUDE2 * PI_180.
  YD = Y2 - Y1.

  DISTANCE = 20000 / PI *
    ACOS( SIN( X1 ) * SIN( X2 ) + COS( X1 ) * COS( X2 ) * COS( YD ) ).

WRITE : 'Distance between given points = ' , distance , 'km .' .


with Ada.Text_IO; use Ada.Text_IO;
with Ada.Long_Float_Text_IO; use Ada.Long_Float_Text_IO;
with Ada.Numerics.Generic_Elementary_Functions;

procedure Haversine_Formula is

   package Math is new Ada.Numerics.Generic_Elementary_Functions (Long_Float); use Math;

   -- Compute great circle distance, given latitude and longitude of two points, in radians
   function Great_Circle_Distance (lat1, long1, lat2, long2 : Long_Float) return Long_Float is
      Earth_Radius : constant := 6371.0; -- in kilometers
      a : Long_Float := Sin (0.5 * (lat2 - lat1));
      b : Long_Float := Sin (0.5 * (long2 - long1));
   begin
      return 2.0 * Earth_Radius * ArcSin (Sqrt (a * a + Cos (lat1) * Cos (lat2) * b * b));
   end Great_Circle_Distance;

   -- convert degrees, minutes and seconds to radians
   function DMS_To_Radians (Deg, Min, Sec : Long_Float := 0.0) return Long_Float is
      Pi_Over_180 : constant := 0.017453_292519_943295_769236_907684_886127;
   begin
      return (Deg + Min/60.0 + Sec/3600.0) * Pi_Over_180;
   end DMS_To_Radians;

begin
   Put_Line("Distance in kilometers between BNA and LAX");
   Put (Great_Circle_Distance (
         DMS_To_Radians (36.0, 7.2), DMS_To_Radians (86.0, 40.2),       -- Nashville International Airport (BNA)
         DMS_To_Radians (33.0, 56.4), DMS_To_Radians (118.0, 24.0)),    -- Los Angeles International Airport (LAX)
      Aft=>3, Exp=>0);
end Haversine_Formula;


main: func {
  "Hello world!" println()
}


#!/usr/local/bin/a68g --script #

REAL r = 20 000/pi + 6.6 # km #,
     to rad = pi/180;

PROC dist = (REAL th1 deg, ph1 deg, th2 deg, ph2 deg)REAL:
(
        REAL ph1 = (ph1 deg - ph2 deg) * to rad,
             th1 = th1 deg * to rad, th2 = th2 deg * to rad,

             dz = sin(th1) - sin(th2),
             dx = cos(ph1) * cos(th1) - cos(th2),
             dy = sin(ph1) * cos(th1);
        arc sin(sqrt(dx * dx + dy * dy + dz * dz) / 2) * 2 * r
);

main:
(
        REAL d = dist(36.12, -86.67, 33.94, -118.4);
        # Americans don't know kilometers #
        printf(($"dist: "g(0,1)" km ("g(0,1)" mi.)"l$, d, d / 1.609344))
)


begin % compute the distance between places using the Haversine formula %
    real procedure arcsin( real value x ) ; arctan( x / sqrt( 1 - ( x * x ) ) );
    real procedure distance ( real value th1Deg, ph1Deg, th2Deg, ph2Deg ) ;
    begin
        real ph1, th1, th2, toRad, dz, dx, dy;
        toRad := pi / 180;
        ph1   := ( ph1Deg - ph2Deg ) * toRad;
        th1   := th1Deg * toRad;
        th2   := th2Deg * toRad;
        dz    := sin( th1 ) - sin( th2 );
        dx    := cos( ph1 ) * cos( th1 ) - cos( th2 );
        dy    := sin( ph1 ) * cos( th1 );
        arcsin( sqrt( dx * dx + dy * dy + dz * dz ) / 2 ) * 2 * 6371
    end distance ;
    begin
        real d;
        integer mi, km;
        d  := distance( 36.12, -86.67, 33.94, -118.4 );
        mi := round( d );
        km := round( d / 1.609344 );
        writeon( i_w := 4, s_w := 0, "distance: ", mi, " km (", km, " mi.)" )
    end
end.


#!/openlisp/uxlisp -shell
(format t "Hello world!~%")
(print "Hello world!")


echo("Hello world!");  // writes to the console
text("Hello world!");  // creates 2D text in the object space
linear_extrude(height=10) text("Hello world!"); // creates 3D text in the object space


namespace HelloWorld;

interface

type
  HelloClass = class
  public
    class method Main;
  end;

implementation

class method HelloClass.Main;
begin
  writeLn('Hello world!');
end;

end.


set location;
set geo;

param coord{i in location, j in geo};
param dist{i in location, j in location};

data;

set location := BNA LAX;
set geo := LAT LON;

param coord:
               LAT      LON :=
      BNA    36.12   -86.67
      LAX    33.94   -118.4
;

let dist['BNA','LAX'] := 2 * 6372.8 * asin (sqrt(sin(atan(1)/45*(coord['LAX','LAT']-coord['BNA','LAT'])/2)^2 + cos(atan(1)/45*coord['BNA','LAT']) * cos(atan(1)/45*coord['LAX','LAT']) * sin(atan(1)/45*(coord['LAX','LON'] - coord
['BNA','LON'])/2)^2));

printf "The distance between the two points is approximately %f km.\n", dist['BNA','LAX'];


use AppleScript version "2.4" -- Yosemite (10.10) or later
use framework "Foundation"
use framework "JavaScriptCore"
use scripting additions

property js : missing value

-- haversine :: (Num, Num) -> (Num, Num) -> Num
on haversine(latLong, latLong2)
    set {lat, lon} to latLong
    set {lat2, lon2} to latLong2

    set {rlat1, rlat2, rlon1, rlon2} to ¬
        map(my radians, {lat, lat2, lon, lon2})

    set dLat to rlat2 - rlat1
    set dLon to rlon2 - rlon1
    set radius to 6372.8 -- km

    set asin to math("asin")
    set sin to math("sin")
    set cos to math("cos")

    |round|((2 * radius * ¬
        (asin's |λ|((sqrt(((sin's |λ|(dLat / 2)) ^ 2) + ¬
            (((sin's |λ|(dLon / 2)) ^ 2) * ¬
                (cos's |λ|(rlat1)) * (cos's |λ|(rlat2)))))))) * 100) / 100
end haversine

-- math :: String -> Num -> Num
on math(f)
    script
        on |λ|(x)
            if missing value is js then ¬
                set js to current application's JSContext's new()
            (js's evaluateScript:("Math." & f & "(" & x & ")"))'s toDouble()
        end |λ|
    end script
end math

-------------------------- TEST ---------------------------
on run
    set distance to haversine({36.12, -86.67}, {33.94, -118.4})

    set js to missing value -- Clearing a c pointer.
    return distance
end run

-------------------- GENERIC FUNCTIONS --------------------

-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
    -- The list obtained by applying f
    -- to each element of xs.
    tell mReturn(f)
        set lng to length of xs
        set lst to {}
        repeat with i from 1 to lng
            set end of lst to |λ|(item i of xs, i, xs)
        end repeat
        return lst
    end tell
end map

-- mReturn :: First-class m => (a -> b) -> m (a -> b)
on mReturn(f)
    -- 2nd class handler function lifted into 1st class script wrapper.
    if script is class of f then
        f
    else
        script
            property |λ| : f
        end script
    end if
end mReturn

-- radians :: Float x => Degrees x -> Radians x
on radians(x)
    (pi / 180) * x
end radians

-- round :: a -> Int
on |round|(n)
    round n
end |round|

-- sqrt :: Num -> Num
on sqrt(n)
    if n ≥ 0 then
        n ^ (1 / 2)
    else
        missing value
    end if
end sqrt


program byeworld;
begin
 writeln('Hello world!');
end.


radians: function [x]-> x * pi // 180

haversine: function [src,tgt][
    dLat: radians tgt\0 - src\0
    dLon: radians tgt\1 - src\1
    lat1: radians src\0
    lat2: radians tgt\0

    a: add product @[cos lat1, cos lat2, sin dLon/2, sin dLon/2] (sin dLat/2) ^ 2
    c: 2 * asin sqrt a
    return 6372.8 * c
]

print haversine @[36.12 neg 86.67] @[33.94, neg 118.40]


#include
"share/atspre_staload.hats"

staload "libc/SATS/math.sats"
staload _ = "libc/DATS/math.dats"
staload "libc/SATS/stdio.sats"
staload "libc/SATS/stdlib.sats"

#define R 6372.8
#define TO_RAD (3.1415926536 / 180)

typedef d = double

fun
dist
(
  th1: d, ph1: d, th2: d, ph2: d
) : d = let
  val ph1 = ph1 - ph2
  val ph1 = TO_RAD * ph1
  val th1 = TO_RAD * th1
  val th2 = TO_RAD * th2
  val dz = sin(th1) - sin(th2)
  val dx = cos(ph1) * cos(th1) - cos(th2)
  val dy = sin(ph1) * cos(th1)
in
  asin(sqrt(dx*dx + dy*dy + dz*dz)/2)*2*R
end // end of [dist]

implement
main0((*void*)) = let
  val d = dist(36.12, ~86.67, 33.94, ~118.4);
  /* Americans don't know kilometers */
in
  $extfcall(void, "printf", "dist: %.1f km (%.1f mi.)\n", d, d / 1.609344)
end // end of [main0]


MsgBox, % GreatCircleDist(36.12, 33.94, -86.67, -118.40, 6372.8, "km")

GreatCircleDist(La1, La2, Lo1, Lo2, R, U) {
	return, 2 * R * ASin(Sqrt(Hs(Rad(La2 - La1)) + Cos(Rad(La1)) * Cos(Rad(La2)) * Hs(Rad(Lo2 - Lo1)))) A_Space U
}

Hs(n) {
	return, (1 - Cos(n)) / 2
}

Rad(Deg) {
	return, Deg * 4 * ATan(1) / 180
}


hello
/ above: title line - was punched in human readable letters on paper tape
/ below: location specifier - told assembler what address to assemble to
100/
lup,	lac i ptr		/ load ac from address stored in pointer
	cli			/ clear io register
lu2,	rcl 6s			/ rotate combined ac + io reg 6 bits to the left
				/ left 6 bits in ac move into right 6 bits of io reg
	tyo			/ type out character in 6 right-most bits of io reg
	sza			/ skip next instr if accumulator is zero
	jmp lu2			/ otherwise do next character in current word
	idx ptr			/ increment pointer to next word in message
	sas end			/ skip next instr if pointer passes the end of message
	jmp lup			/ otherwise do next word in message
	hlt			/ halt machine
ptr,	msg			/ pointer to current word in message
msg,	text "hello, world"	/ 3 6-bit fiodec chars packed into each 18-bit word
end,	.         		/ sentinel for end of message
start 100			/ tells assembler where program starts


.globl  start
	.text
start:
        mov	$1,r0               / r0=stream, STDOUT=$1
	sys	4; outtext; outlen  / sys 4 is write
	sys	1                   / sys 1 is exit
	rts	pc                  / in case exit returns

	.data
outtext: <Hello world!\n>
outlen = . - outtext


# syntax: GAWK -f HAVERSINE_FORMULA.AWK
# converted from Python
BEGIN {
    distance(36.12,-86.67,33.94,-118.40) # BNA to LAX
    exit(0)
}
function distance(lat1,lon1,lat2,lon2,  a,c,dlat,dlon) {
    dlat = radians(lat2-lat1)
    dlon = radians(lon2-lon1)
    lat1 = radians(lat1)
    lat2 = radians(lat2)
    a = (sin(dlat/2))^2 + cos(lat1) * cos(lat2) * (sin(dlon/2))^2
    c = 2 * atan2(sqrt(a),sqrt(1-a))
    printf("distance: %.4f km\n",6372.8 * c)
}
function radians(degree) { # degrees to radians
    return degree * (3.1415926 / 180.)
}


CONST pi = 3.141593     ' define pi
CONST radio = 6372.8    ' radio de la tierra en km

PRINT : PRINT " Distancia de Haversine:";
PRINT Haversine!(36.12, -86.67, 33.94, -118.4); "km"
END

FUNCTION Haversine! (lat1!, long1!, lat2!, long2!)
    deg2rad! = pi / 180    ' define grados a radianes 0.01745..

    dLong! = deg2rad! * (long1! - long2!)
    theta1! = deg2rad! * lat1!
    theta2! = deg2rad! * lat2!
    dx! = COS(dLong!) * COS(theta1!) - COS(theta2!)
    dy! = SIN(dLong!) * COS(theta1!)
    dz! = SIN(theta1!) - SIN(theta2!)

    Haversine! = (SQR(dx! * dx! + dy! * dy! + dz! * dz!) / 2) * radio * 2
END FUNCTION


#include default-libraries

#author Childishbeat

class Hello world/Text:
function Hello world/Text:

print "Hello world!"

end


global radioTierra    # radio de la tierra en km
radioTierra = 6372.8

function Haversine(lat1, long1, lat2, long2 , radio)
	d_long = radians(long1 - long2)
	theta1 = radians(lat1)
	theta2 = radians(lat2)
	dx = cos(d_long) * cos(theta1) - cos(theta2)
	dy = sin(d_long) * cos(theta1)
	dz = sin(theta1) - sin(theta2)
	return asin(sqr(dx*dx + dy*dy + dz*dz) / 2) * radio * 2
end function

print
print " Distancia de Haversine entre BNA y LAX = ";
print Haversine(36.12, -86.67, 33.94, -118.4, radioTierra); " km"
end


      PRINT "Distance = " ; FNhaversine(36.12, -86.67, 33.94, -118.4) " km"
      END

      DEF FNhaversine(n1, e1, n2, e2)
      LOCAL d() : DIM d(2)
      d() = COSRAD(e1-e2) * COSRAD(n1) - COSRAD(n2), \
      \     SINRAD(e1-e2) * COSRAD(n1), \
      \     SINRAD(n1) - SINRAD(n2)
      = ASN(MOD(d()) / 2) * 6372.8 * 2


#!/bin/sh
#-
# © 2021 mirabilos Ⓕ CC0; implementation of Haversine GCD from public sources
#
# now developed online:
# https://evolvis.org/plugins/scmgit/cgi-bin/gitweb.cgi?p=useful-scripts/mirkarte.git;a=blob;f=geo.sh;hb=HEAD

if test "$#" -ne 4; then
	echo >&2 "E: syntax: $0 lat1 lon1 lat2 lon2"
	exit 1
fi

set -e

# make GNU bc use POSIX mode and shut up
BC_ENV_ARGS=-qs
export BC_ENV_ARGS

# assignment of constants, variables and functions
# p: multiply with to convert from degrees to radians (π/180)
# r: earth radius in metres
# d: distance
# h: haversine intermediate
# i,j: (lat,lon) point 1
# x,y: (lat,lon) point 2
# k: delta lat
# l: delta lon
# m: sin(k/2) (square root of hav(k))
# n: sin(l/2) (  partial haversine  )
# n(x): arcsin(x)
# r(x,n): round x to n decimal digits
# v(x): sign (Vorzeichen)
# w(x): min(1, sqrt(x)) (Wurzel)

bc -l <<-EOF
scale=64
define n(x) {
	if (x == -1) return (-2 * a(1))
	if (x == 1) return (2 * a(1))
	return (a(x / sqrt(1 - x*x)))
}
define v(x) {
	if (x < 0) return (-1)
	if (x > 0) return (1)
	return (0)
}
define r(x, n) {
	auto o
	o = scale
	if (scale < (n + 1)) scale = (n + 1)
	x += v(x) * 0.5 * A^-n
	scale = n
	x /= 1
	scale = o
	return (x)
}
define w(x) {
	if (x >= 1) return (1)
	return (sqrt(x))
}
/* WGS84 reference ellipsoid: große Halbachse (metres), Abplattung */
i = 6378137.000
x = 1/298.257223563
/* other axis */
j = i * (1 - x)
/* mean radius resulting */
r = (2 * i + j) / 3
/* coordinates */
p = (4 * a(1) / 180)
i = (p * $1)
j = (p * $2)
x = (p * $3)
y = (p * $4)
/* calculation */
k = (x - i)
l = (y - j)
m = s(k / 2)
n = s(l / 2)
h = ((m * m) + (c(i) * c(x) * n * n))
d = 2 * r * n(w(h))
r(d, 3)
EOF

# output is in metres, rounded to millimetres, error < ¼% in WGS84


#include <stdio.h>
#include <stdlib.h>
#include <math.h>

#define R 6371
#define TO_RAD (3.1415926536 / 180)
double dist(double th1, double ph1, double th2, double ph2)
{
	double dx, dy, dz;
	ph1 -= ph2;
	ph1 *= TO_RAD, th1 *= TO_RAD, th2 *= TO_RAD;

	dz = sin(th1) - sin(th2);
	dx = cos(ph1) * cos(th1) - cos(th2);
	dy = sin(ph1) * cos(th1);
	return asin(sqrt(dx * dx + dy * dy + dz * dz) / 2) * 2 * R;
}

int main()
{
	double d = dist(36.12, -86.67, 33.94, -118.4);
	/* Americans don't know kilometers */
	printf("dist: %.1f km (%.1f mi.)\n", d, d / 1.609344);

	return 0;
}


"Comments are in double quotes"
"Sending message printString to 'Hello World' string"

'Hello World' printString


module helloworld;
extern printf;

@Integer main [
    printf("Hello world!");
    return 0;
]


public static class Haversine {
  public static double calculate(double lat1, double lon1, double lat2, double lon2) {
    var R = 6372.8; // In kilometers
    var dLat = toRadians(lat2 - lat1);
    var dLon = toRadians(lon2 - lon1);
    lat1 = toRadians(lat1);
    lat2 = toRadians(lat2);

    var a = Math.Sin(dLat / 2) * Math.Sin(dLat / 2) + Math.Sin(dLon / 2) * Math.Sin(dLon / 2) * Math.Cos(lat1) * Math.Cos(lat2);
    var c = 2 * Math.Asin(Math.Sqrt(a));
    return R * 2 * Math.Asin(Math.Sqrt(a));
  }

  public static double toRadians(double angle) {
    return Math.PI * angle / 180.0;
  }
}

void Main() {
  Console.WriteLine(String.Format("The distance between coordinates {0},{1} and {2},{3} is: {4}", 36.12, -86.67, 33.94, -118.40, Haversine.calculate(36.12, -86.67, 33.94, -118.40)));
}

// Returns: The distance between coordinates 36.12,-86.67 and 33.94,-118.4 is: 2887.25995060711


#define _USE_MATH_DEFINES

#include <math.h>
#include <iostream>

const static double EarthRadiusKm = 6372.8;

inline double DegreeToRadian(double angle)
{
	return M_PI * angle / 180.0;
}

class Coordinate
{
public:
	Coordinate(double latitude ,double longitude):myLatitude(latitude), myLongitude(longitude)
	{}

	double Latitude() const
	{
		return myLatitude;
	}

	double Longitude() const
	{
		return myLongitude;
	}

private:

	double myLatitude;
	double myLongitude;
};

double HaversineDistance(const Coordinate& p1, const Coordinate& p2)
{
	double latRad1 = DegreeToRadian(p1.Latitude());
	double latRad2 = DegreeToRadian(p2.Latitude());
	double lonRad1 = DegreeToRadian(p1.Longitude());
	double lonRad2 = DegreeToRadian(p2.Longitude());

	double diffLa = latRad2 - latRad1;
	double doffLo = lonRad2 - lonRad1;

	double computation = asin(sqrt(sin(diffLa / 2) * sin(diffLa / 2) + cos(latRad1) * cos(latRad2) * sin(doffLo / 2) * sin(doffLo / 2)));
	return 2 * EarthRadiusKm * computation;
}

int main()
{
	Coordinate c1(36.12, -86.67);
	Coordinate c2(33.94, -118.4);

	std::cout << "Distance = " << HaversineDistance(c1, c2) << std::endl;
	return 0;
}


(defn haversine
  [{lon1 :longitude lat1 :latitude} {lon2 :longitude lat2 :latitude}]
  (let [R 6372.8 ; kilometers
        dlat (Math/toRadians (- lat2 lat1))
        dlon (Math/toRadians (- lon2 lon1))
        lat1 (Math/toRadians lat1)
        lat2 (Math/toRadians lat2)
        a (+ (* (Math/sin (/ dlat 2)) (Math/sin (/ dlat 2))) (* (Math/sin (/ dlon 2)) (Math/sin (/ dlon 2)) (Math/cos lat1) (Math/cos lat2)))]
    (* R 2 (Math/asin (Math/sqrt a)))))

(haversine {:latitude 36.12 :longitude -86.67} {:latitude 33.94 :longitude -118.40})
;=> 2887.2599506071106


haversine = (args...) ->
  R = 6372.8; # km
  radians = args.map (deg) -> deg/180.0 * Math.PI
  lat1 = radians[0]; lon1 = radians[1]; lat2 = radians[2]; lon2 = radians[3]
  dLat = lat2 - lat1
  dLon = lon2 - lon1
  a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.sin(dLon / 2) * Math.sin(dLon / 2) * Math.cos(lat1) * Math.cos(lat2)
  R * 2 * Math.asin(Math.sqrt(a))

console.log haversine(36.12, -86.67, 33.94, -118.40)


pikachu pika pikachu pika pika pi pi pika pikachu pika pikachu pi pikachu pi pikachu pi pika pi pikachu pikachu pi pi pika pika pikachu pika pikachu pikachu pi pika pi pika pika pi pikachu pikachu pi pikachu pi pika pikachu pi pikachu pika pikachu pi pikachu pikachu pi pikachu pika pika pikachu pi pikachu pi pi pikachu pikachu pika pikachu pi pika pi pi pika pika pikachu pikachu pi pi pikachu pi pikachu
pikachu pikachu pi pikachu
pikachu pika pika pikachu pika pikachu pikachu pika pika pikachu pikachu pi pi pikachu pika pikachu pika pika pi pika pikachu pikachu pi pika pika pikachu pi pika pi pika pi pikachu pi pikachu pika pika pi pi pika pi pika pika pikachu pikachu pika pikachu pikachu pika pi pikachu pika pi pikachu pi pika pika pi pikachu pika pi pika pikachu pi pi pikachu pika pika pi pika pi pikachu
pikachu pikachu pi pikachu
pikachu pika pi pika pika pikachu pika pikachu pi pikachu pi pi pika pi pikachu pika pi pi pika pikachu pi pikachu pi pi pikachu pikachu pika pikachu pikachu pika pi pikachu pi pika pikachu pi pikachu pika pika pikachu pika pi pi pikachu pikachu pika pika pikachu pi pika pikachu pikachu pi pika pikachu pikachu pika pi pi pikachu pikachu pi pikachu pi pikachu pi pikachu pi pika pikachu pi pikachu pika pikachu pi pika pi pikachu
pi pika
pikachu pikachu pi pikachu
pika pi
pikachu pikachu pi pikachu
pikachu pi pikachu pi pi pikachu pi pikachu pika pikachu pikachu pi pikachu pikachu pika pi pi pika pikachu pika pikachu pi pi pikachu pika pi pi pikachu pika pika pi pika pika pikachu pika pikachu pi pi pika pikachu pika pi pikachu pikachu pi pikachu pika pikachu pikachu pika pi pi pikachu pikachu pi pika pikachu pi pikachu pika pikachu pikachu pika pi pikachu pikachu pika pikachu pi pikachu pika pika pi pikachu pi pika pi pikachu pikachu pi pikachu
pi pika
pikachu pikachu pi pikachu
pikachu pikachu pi pika pikachu pi pika pika pi pi pika pi pikachu pi pika pi pika pi pika pikachu pika pi pi pikachu pi pikachu pi pika pi pika pika pikachu pi pikachu
pikachu pikachu pi pikachu
pikachu pi pikachu pika pikachu pi pika pi pikachu pikachu pika pika pi pi pikachu pi pika pi pikachu pi pika pikachu pi pika pi pi pikachu pikachu pika pika pikachu pikachu pi pi pikachu pi pikachu pi pikachu pi pi pikachu pikachu pi pikachu pi pikachu pi pika pika pikachu pikachu pika pi pika pikachu pi pikachu pi pi pika pikachu pika pi pikachu pi pika pi pi pikachu pikachu pika pika pikachu pika pika pikachu pi pika pi pika pikachu pi pika pikachu pika pi pika pikachu
pikachu pikachu pika pikachu
pikachu pikachu pika pikachu
pi pi pikachu pi pikachu pika pika pi pikachu pika pika pi pi pika pika pikachu pi pi pikachu pi pika pi pika pikachu pi pikachu pi pikachu pikachu pi pi pika pika pi pika pika pi pika pikachu pikachu pi pikachu pika pi pi pika pi pi pikachu pikachu pika pi pi pika pika pi pika pikachu pi pikachu pi pi pika pi pika pika pikachu pika pi pika pikachu pi pikachu pikachu pi pi pika pi pika pika pikachu pikachu pi pikachu
pikachu pikachu pi pikachu
pikachu pi pikachu pikachu pika pikachu pikachu pika pika pikachu pikachu pika pikachu pi pika pikachu pika pika pi pikachu pi pi pika pi pi pikachu pika pika pikachu pikachu pika pikachu pikachu pi pika pi pi pikachu pikachu pika pi pi pikachu pikachu pika pikachu pika pi pikachu pi pika pi pika pikachu pika pi pikachu pi pikachu pikachu pi pika pikachu pi pikachu pikachu pi pika pi pikachu pikachu pi pikachu pika pika pi pi pikachu
pikachu pi pi pika pi pi pikachu pika pikachu pikachu pika pika pi pi pika pikachu pi pikachu pi pi pika pi pika pi pi pika pikachu pi pika pi pikachu pika pikachu pika pi pi pika pi pi pikachu pi pikachu pikachu pika pi pikachu pi pi pika pi pikachu pi pi pika pi pi pikachu pika pikachu pika pikachu pika pi pikachu pikachu pi pi pika pika pikachu
pikachu pikachu pi pikachu
pikachu pikachu pika pikachu


10 REM================================
15 REM HAVERSINE FORMULA
20 REM
25 REM 2021-09-24
30 REM EN.WIKIPEDIA.ORG/WIKI/HAVERSINE_FORMULA
35 REM
40 REM C64 HAS PI CONSTANT
45 REM X1 LONGITUDE 1
50 REM Y1 LATITUDE 1
55 REM X2 LONGITUDE 2
60 REM Y2 LATITUDE 2
65 REM
70 REM V1, 2021-10-02, ALVALONGO
75 REM ===============================
100 REM MAIN
105 DR=π/180:REM DEGREES TO RADIANS
110 PRINT CHR$(147);CHR$(5);"HAVERSINE FORMULA"
120 PRINT "GREAT-CIRCLE DISTANCE"
130 R=6372.8:REM AVERAGE EARTH RADIUS IN KILOMETERS
200 REM GET DATA
210 PRINT
220 INPUT "LONGITUDE 1=";X1
230 INPUT "LATITUDE  1=";Y1
240 PRINT
250 INPUT "LONGITUDE 2=";X2
260 INPUT "LATITUDE  2=";Y2
270 GOSUB 500
280 PRINT
290 PRINT "DISTANCE=";D;"KM"
300 GET K$:IF K$="" THEN 300
310 GOTO 210
490 END
500 REM HAVERSINE FORMULA ------------
520 A=SIN((X2-X1)*DR/2)
530 A=A*A
540 B=COS(Y1*DR)*COS(Y2*DR)
550 C=SIN((Y2-Y1)*DR/2)
560 C=C*C
570 D=SQR(C+B*A)
580 E=D/SQR(1-D*D)
590 F=ATN(E)
600 D=2*R*F
610 RETURN


(defparameter *earth-radius* 6372.8)

(defparameter *rad-conv* (/ pi 180))

(defun deg->rad (x)
  (* x *rad-conv*))

(defun haversine (x)
  (expt (sin (/ x 2)) 2))

(defun dist-rad (lat1 lng1 lat2 lng2)
  (let* ((hlat (haversine (- lat2 lat1)))
         (hlng (haversine (- lng2 lng1)))
         (root (sqrt (+ hlat (* (cos lat1) (cos lat2) hlng)))))
    (* 2 *earth-radius* (asin root))))

(defun dist-deg (lat1 lng1 lat2 lng2)
  (dist-rad (deg->rad lat1)
            (deg->rad lng1)
            (deg->rad lat2)
            (deg->rad lng2)))


include Math

def haversine(lat1, lon1, lat2, lon2)
    r = 6372.8        # Earth radius in kilometers
    deg2rad = PI/180  # convert degress to radians

    dLat = (lat2 - lat1) * deg2rad
    dLon = (lon2 - lon1) * deg2rad
    lat1 = lat1 * deg2rad
    lat2 = lat2 * deg2rad

    a = sin(dLat / 2)**2 + cos(lat1) * cos(lat2) * sin(dLon / 2)**2
    c = 2 * asin(sqrt(a))
    r * c
end

puts "distance is #{haversine(36.12, -86.67, 33.94, -118.40)} km "


int main(){
   write("Hello world!\n");
}


.sub hello_world_text :main
	print "Hello world!\n"
.end


import std.stdio, std.math;

real haversineDistance(in real dth1, in real dph1,
                       in real dth2, in real dph2)
pure nothrow @nogc {
    enum real R = 6371;
    enum real TO_RAD = PI / 180;

    alias imr = immutable real;
    imr ph1d = dph1 - dph2;
    imr ph1 = ph1d * TO_RAD;
    imr th1 = dth1 * TO_RAD;
    imr th2 = dth2 * TO_RAD;

    imr dz = th1.sin - th2.sin;
    imr dx = ph1.cos * th1.cos - th2.cos;
    imr dy = ph1.sin * th1.cos;
    return asin(sqrt(dx ^^ 2 + dy ^^ 2 + dz ^^ 2) / 2) * 2 * R;
}

void main() {
    writefln("Haversine distance: %.1f km",
             haversineDistance(36.12, -86.67, 33.94, -118.4));
}


import 'dart:math';

class Haversine {
  static final R = 6372.8; // In kilometers

  static double haversine(double lat1, lon1, lat2, lon2) {
    double dLat = _toRadians(lat2 - lat1);
    double dLon = _toRadians(lon2 - lon1);
    lat1 = _toRadians(lat1);
    lat2 = _toRadians(lat2);
    double a = pow(sin(dLat / 2), 2) + pow(sin(dLon / 2), 2) * cos(lat1) * cos(lat2);
    double c = 2 * asin(sqrt(a));
    return R * c;
  }

  static double _toRadians(double degree) {
    return degree * pi / 180;
  }

  static void main() {
    print(haversine(36.12, -86.67, 33.94, -118.40));
  }
}


goodbye:proc options(main);
     put list('Hello world!');
end goodbye;


100H:
   /* CP/M BDOS SYSTEM CALL */
   BDOS: PROCEDURE( FN, ARG ); DECLARE FN BYTE, ARG ADDRESS; GOTO 5; END;
   /* PRINT A $ TERMINATED STRING */
   PRINT$STRING: PROCEDURE( S ); DECLARE S ADDRESS; CALL BDOS( 9, S ); END;
   /* HELLO, WORLD! IN MIXED CASE */
   DECLARE HELLO$WORLD ( 14 ) BYTE
           INITIAL( 'H', 65H, 6CH, 6CH, 6FH, ',', ' '
                  , 'W', 6FH, 72H, 6CH, 64H, 21H, '$'
                  );
   CALL PRINT$STRING( .HELLO$WORLD );
EOF


program HaversineDemo;
uses Math;

function HaversineDist(th1, ph1, th2, ph2:double):double;
const diameter = 2 * 6372.8;
var   dx, dy, dz:double;
begin
  ph1    := degtorad(ph1 - ph2);
  th1    := degtorad(th1);
  th2    := degtorad(th2);

  dz     := sin(th1) - sin(th2);
  dx     := cos(ph1) * cos(th1) - cos(th2);
  dy     := sin(ph1) * cos(th1);
  Result := arcsin(sqrt(sqr(dx) + sqr(dy) + sqr(dz)) / 2) * diameter;
end;

begin
  Writeln('Haversine distance: ', HaversineDist(36.12, -86.67, 33.94, -118.4):7:2, ' km.');
end.


import extensions;
import system'math;

Haversine(lat1,lon1,lat2,lon2)
{
    var R := 6372.8r;
    var dLat := (lat2 - lat1).Radian;
    var dLon := (lon2 - lon1).Radian;

    var dLat1 := lat1.Radian;
    var dLat2 := lat2.Radian;

    var a := (dLat / 2).sin() * (dLat / 2).sin() + (dLon / 2).sin() * (dLon / 2).sin() * dLat1.cos() * dLat2.cos();

    ^ R * 2 * a.sqrt().arcsin()
}

public program()
{
    console.printLineFormatted("The distance between coordinates {0},{1} and {2},{3} is: {4}", 36.12r, -86.67r, 33.94r, -118.40r,
        Haversine(36.12r, -86.67r, 33.94r, -118.40r))
}


SET serveroutput ON

BEGIN
  DBMS_OUTPUT.PUT_LINE('Hello world!');
END;
/


\This prints Hello World within the CAL-4700 IDE.
\...and backslashes are comments!
To run:
Start up.
Write "Hello World!" to the console.
Wait for the escape key.
Shut down.


#STEER         LIST,BINARY
#PROGRAM       HLWD
#LOWER
MSG1A          11HHELLO WORLD
MSG1B          11/MSG1A
#PROGRAM
#ENTRY         0
      DISTY    MSG1B
      SUSWT    2HHH
#END
#FINISH
#STOP


defmodule Haversine do
  @v  :math.pi / 180
  @r  6372.8            # km for the earth radius
  def distance({lat1, long1}, {lat2, long2}) do
    dlat  = :math.sin((lat2 - lat1) * @v / 2)
    dlong = :math.sin((long2 - long1) * @v / 2)
    a = dlat * dlat + dlong * dlong * :math.cos(lat1 * @v) * :math.cos(lat2 * @v)
    @r * 2 * :math.asin(:math.sqrt(a))
  end
end

bna = {36.12,  -86.67}
lax = {33.94, -118.40}
IO.puts Haversine.distance(bna, lax)


haversine : ( Float, Float ) -> ( Float, Float ) -> Float
haversine ( lat1, lon1 ) ( lat2, lon2 ) =
    let
        r =
            6372.8

        dLat =
            degrees (lat2 - lat1)

        dLon =
            degrees (lon2 - lon1)

        a =
            (sin (dLat / 2))
                ^ 2
                + (sin (dLon / 2))
                ^ 2
                * cos (degrees lat1)
                * cos (degrees lat2)
    in
        r * 2 * asin (sqrt a)

view =
    Html.div []
      [ Html.text (toString (haversine ( 36.12, -86.67 ) ( 33.94, -118.4 )))
      ]


% Implementer by Arjun Sunel
-module(haversine).
-export([main/0]).

main() ->
	haversine(36.12, -86.67, 33.94, -118.40).

haversine(Lat1, Long1, Lat2, Long2) ->
	V 	         =   math:pi()/180,
	R 		 =   6372.8, 	% In kilometers
	Diff_Lat 	 =   (Lat2 - Lat1)*V ,
	Diff_Long	 =   (Long2 - Long1)*V,
	NLat 		 =   Lat1*V,
	NLong 		 =   Lat2*V,
	A 		 =   math:sin(Diff_Lat/2) * math:sin(Diff_Lat/2) + math:sin(Diff_Long/2) * math:sin(Diff_Long/2) * math:cos(NLat) * math:cos(NLong),
	C 		 =   2 * math:asin(math:sqrt(A)),
	R*C.


F happy(=n)
   Set[Int] past
   L n != 1
      n = sum(String(n).map(с -> Int(с)^2))
      I n C past
         R 0B
      past.add(n)
   R 1B

print((0.<500).filter(x -> happy(x))[0.<8])


actor Main
  new create(env: Env) =>
    env.out.print("Hello world!")


programa {
// funcao defines a new function
// inicio is the entry point of the program, like main in C
    funcao inicio() {
        // escreva is used to print stuff to the screen
        escreva("Hello, world!\n") // no ';' needed
    }
}


% Implemented by Claudio Larini

PROGRAM HAVERSINE_DEMO

!$DOUBLE

CONST DIAMETER=12745.6

FUNCTION DEG2RAD(X)
    DEG2RAD=X*π/180
END FUNCTION

FUNCTION RAD2DEG(X)
    RAD2DEG=X*180/π
END FUNCTION

PROCEDURE HAVERSINE_DIST(TH1,PH1,TH2,PH2->RES)
    LOCAL DX,DY,DZ
    PH1=DEG2RAD(PH1-PH2)
    TH1=DEG2RAD(TH1)
    TH2=DEG2RAD(TH2)
    DZ=SIN(TH1)-SIN(TH2)
    DX=COS(PH1)*COS(TH1)-COS(TH2)
    DY=SIN(PH1)*COS(TH1)
    RES=ASN(SQR(DX^2+DY^2+DZ^2)/2)*DIAMETER
END PROCEDURE

BEGIN
    HAVERSINE_DIST(36.12,-86.67,33.94,-118.4->RES)
    PRINT("HAVERSINE DISTANCE: ";RES;" KM.")
END PROGRAM


>load spherical
 Spherical functions for Euler.
>TNA=[rad(36,7.2),-rad(86,40.2)];
>LAX=[rad(33,56.4),-rad(118,24)];
>esdist(TNA,LAX)->km
 2886.48817482
>type esdist
 function esdist (frompos: vector, topos: vector)
     r1=rearth(frompos[1]);
     r2=rearth(topos[1]);
     xfrom=spoint(frompos)*r1;
     xto=spoint(topos)*r2;
     delta=xto-xfrom;
     return asin(norm(delta)/(r1+r2))*(r1+r2);
 endfunction
>function overwrite rearth (x) := 6372.8*km$
>esdist(TNA,LAX)->km
 2887.25995061


HAVERSINE
=LAMBDA(lla,
    LAMBDA(llb,
        LET(
            REM, "Approximate radius of Earth in km.",
            earthRadius, 6372.8,

            sinHalfDeltaSquared, LAMBDA(x, SIN(x / 2) ^ 2)(
                RADIANS(llb - lla)
            ),

            2 * earthRadius * ASIN(
                SQRT(
                    INDEX(sinHalfDeltaSquared, 1) + (
                        PRODUCT(COS(RADIANS(
                            CHOOSE({1,2},
                                INDEX(lla, 1),
                                INDEX(llb, 1)
                            )
                        )))
                    ) * INDEX(sinHalfDeltaSquared, 2)
                )
            )
        )
    )
)


flags:	equ	2	; 256-byte page in which to keep track of cycles
puts:	equ	9	; CP/M print string
bdos:	equ	5 	; CP/M entry point
	org	100h
	lxi	d,0108h	; D=current number to test, E=amount of numbers
	;;;	Is D happy?
number:	mvi	a,1	; We haven't seen any numbers yet, set flags to 1
	lxi	h,256*flags
init:	mov	m,a
	inr	l
	jnz	init
	mov	a,d	; Get digits
step:	call	digits
	mov	l,a	; L = D1 * D1
	mov	h,a
	xra	a
sqr1:	add	h
	dcr	l
	jnz	sqr1
	mov	l,a
	mov	h,b	; L += D10 * D10
	xra	a
sqr10:	add	h
	dcr 	b
	jnz	sqr10
	add	l
	mov	l,a
	mov	h,c	; L += D100 * D100
	xra	a
sqr100:	add	h
	dcr	c
	jnz	sqr100
	add	l
	mov	l,a
	mvi	h,flags	; Look up corresponding flag
	dcr	m 	; Will give 0 the first time and not-0 afterwards
	mov	a,l	; If we haven't seen the number before, another step
	jz 	step
	dcr	l	; If we _had_ seen it, then is it 1?
	jz	happy	; If so, it is happy
next:	inr	d	; Afterwards, try next number
	jmp	number
happy:	mov	a,d	; D is happy - get its digits (for output)
	lxi	h,string+3
	call	digits	; Write digits into string for output
	call	sdgt	; Ones digit,
	mov	a,b	; Tens digit,
	call	sdgt
	mov	a,c	; Hundreds digit
	call	sdgt
	push	d	; Keep counters on stack
	mvi	c,puts	; Print string using CP/M call
	xchg
	call	bdos
	pop	d	; Restore counters
	dcr	e	; One fewer happy number left
	jnz	next	; If we need more, do the next one
	ret
	;;;	Store A as ASCII digit in [HL] and go to previous digit
sdgt:	adi	'0'
	dcx	h
	mov	m,a
	ret
	;;;	Get digits of 8-bit number in A.
	;;;	Input: A = number
	;;;	Output: C=100s digit, B=10s digit, A=1s digit
digits:	lxi	b,-1	; Set B and C to -1 (correct for extra loop cycle)
d100:	inr	c	; Calculate hundreds digit
	sui	100	; By trial subtraction of 100
	jnc	d100	; Until underflow occurs
	adi	100	; Loop runs one cycle too many, so add 100 back
d10:	inr	b	; Calculate 10s digit in the same way
	sui	10
	jnc	d10
	adi	10
	ret		; 1s digit is left in A afterwards
string:	db	'000',13,10,'$'


: until!  "not while!" eval i;

with: w
with: n

: sumsqd  \ n -- n
    0 swap repeat
        0; 10 /mod -rot sqr + swap
    again ;

: cycle \ n xt -- n
    >r
    dup [email protected] exec  \ -- tortoise, hare
    repeat
        swap [email protected] exec
        swap [email protected] exec [email protected] exec
    2dup = until!
    rdrop drop ;

: happy?  ' sumsqd cycle 1 = ;

: .happy \ n --
    1 repeat
        dup happy? if  dup . space  swap 1- swap  then 1+
    over 0 > while!
    2drop cr ;

;with
;with


%!PS
/Helvetica 20 selectfont
70 700 moveto
(Hello world!) show
showpage


#COMPILE EXE
#COMPILER PBCC 6

FUNCTION PBMAIN () AS LONG
  CON.PRINT "Hello world!"
  CON.WAITKEY$
END FUNCTION


open System

[<Measure>] type deg
[<Measure>] type rad
[<Measure>] type km

let haversine (θ: float<rad>) = 0.5 * (1.0 - Math.Cos(θ/1.0<rad>))

let radPerDeg =  (Math.PI / 180.0) * 1.0<rad/deg>

type pos(latitude: float<deg>, longitude: float<deg>) =
    member this.φ = latitude * radPerDeg
    member this.ψ = longitude * radPerDeg

let rEarth = 6372.8<km>

let hsDist (p1: pos) (p2: pos) =
    2.0 * rEarth *
        Math.Asin(Math.Sqrt(haversine(p2.φ - p1.φ)+
                    Math.Cos(p1.φ/1.0<rad>)*Math.Cos(p2.φ/1.0<rad>)*haversine(p2.ψ - p1.ψ)))

[<EntryPoint>]
let main argv =
    printfn "%A" (hsDist (pos(36.12<deg>, -86.67<deg>)) (pos(33.94<deg>, -118.40<deg>)))
    0


USING: arrays kernel math math.constants math.functions math.vectors sequences ;

: haversin ( x -- y ) cos 1 swap - 2 / ;
: haversininv ( y -- x ) 2 * 1 swap - acos ;
: haversineDist ( as bs -- d )
[ [ 180 / pi * ] map ] [email protected]
  [ [ swap - haversin ] 2map ]
  [ [ first cos ] [email protected] * 1 swap 2array ]
  2bi
v.
haversininv R_earth * ;


(include-book "arithmetic-3/top" :dir :system)

(defun sum-of-digit-squares (n)
   (if (zp n)
       0
       (+ (expt (mod n 10) 2)
          (sum-of-digit-squares (floor n 10)))))

(defun is-happy-r (n seen)
   (let ((next (sum-of-digit-squares n)))
        (cond ((= next 1) t)
              ((member next seen) nil)
              (t (is-happy-r next (cons next seen))))))

(defun is-happy (n)
   (is-happy-r n nil))

(defun first-happy-nums-r (n i)
   (cond ((zp n) nil)
         ((is-happy i)
          (cons i (first-happy-nums-r (1- n) (1+ i))))
         (t (first-happy-nums-r n (1+ i)))))

(defun first-happy-nums (n)
   (first-happy-nums-r n 1))


BYTE FUNC SumOfSquares(BYTE x)
  BYTE sum,d

  sum=0
  WHILE x#0
  DO
    d=x MOD 10
    d==*d
    sum==+d
    x==/10
  OD
RETURN (sum)

BYTE FUNC Contains(BYTE ARRAY a BYTE count,x)
  BYTE i

  FOR i=0 TO count-1
  DO
    IF a(i)=x THEN RETURN (1) FI
  OD
RETURN (0)

BYTE FUNC IsHappyNumber(BYTE x)
  BYTE ARRAY cache(100)
  BYTE count

  count=0
  WHILE x#1
  DO
    cache(count)=x
    count==+1
    x=SumOfSquares(x)
    IF Contains(cache,count,x) THEN
      RETURN (0)
    FI
  OD
RETURN (1)

PROC Main()
  BYTE x,count

  x=1 count=0
  WHILE count<8
  DO
    IF IsHappyNumber(x) THEN
      count==+1
      PrintF("%I: %I%E",count,x)
    FI
    x==+1
  OD
RETURN


#APPTYPE CONSOLE

PRINT "Distance = ", Haversine(36.12, -86.67, 33.94, -118.4), " km"
PAUSE

FUNCTION Haversine(DegLat1 AS DOUBLE, DegLon1 AS DOUBLE, DegLat2 AS DOUBLE, DegLon2 AS DOUBLE) AS DOUBLE
    CONST radius = 6372.8
    DIM dLat AS DOUBLE = D2R(DegLat2 - DegLat1)
    DIM dLon AS DOUBLE = D2R(DegLon2 - DegLon1)
    DIM lat1 AS DOUBLE = D2R(DegLat1)
    DIM lat2 AS DOUBLE = D2R(DegLat2)
    DIM a AS DOUBLE = SIN(dLat / 2) * SIN(dLat / 2) + SIN(dLon / 2) * SIN(dLon / 2) * COS(lat1) * COS(lat2)
    DIM c AS DOUBLE = 2 * ASIN(SQRT(a))
    RETURN radius * c
END FUNCTION


function sumOfSquares(n:uint)
{
	var sum:uint = 0;
	while(n != 0)
	{
		sum += (n%10)*(n%10);
		n /= 10;
	}
	return sum;
}
function isInArray(n:uint, array:Array)
{
	for(var k = 0; k < array.length; k++)
		if(n == array[k]) return true;
	return false;
}
function isHappy(n)
{
	var sequence:Array = new Array();
	while(n != 1)
	{
		sequence.push(n);
		n = sumOfSquares(n);
		if(isInArray(n,sequence))return false;
	}
	return true;
}
function printHappy()
{
	var numbersLeft:uint = 8;
	var numberToTest:uint = 1;
	while(numbersLeft != 0)
	{
		if(isHappy(numberToTest))
		{
			trace(numberToTest);
			numbersLeft--;
		}
		numberToTest++;
	}
}
printHappy();


with Ada.Text_IO;  use Ada.Text_IO;
with Ada.Containers.Ordered_Sets;

procedure Test_Happy_Digits is
   function Is_Happy (N : Positive) return Boolean is
      package Sets_Of_Positive is new Ada.Containers.Ordered_Sets (Positive);
      use Sets_Of_Positive;
      function Next (N : Positive) return Natural is
         Sum   : Natural := 0;
         Accum : Natural := N;
      begin
         while Accum > 0 loop
            Sum   := Sum + (Accum mod 10) ** 2;
            Accum := Accum / 10;
         end loop;
         return Sum;
      end Next;
      Current : Positive := N;
      Visited : Set;
   begin
      loop
         if Current = 1 then
            return True;
         elsif Visited.Contains (Current) then
            return False;
         else
            Visited.Insert (Current);
            Current := Next (Current);
         end if;
      end loop;
   end Is_Happy;
   Found : Natural := 0;
begin
   for N in Positive'Range loop
      if Is_Happy (N) then
         Put (Integer'Image (N));
         Found := Found + 1;
         exit when Found = 8;
      end if;
   end loop;
end Test_Happy_Digits;


program hello
include library
begin
output "Hello world!"
end


: s>f s>d d>f ;
: deg>rad 174532925199433e-16 f* ;
: difference f- deg>rad 2 s>f f/ fsin fdup f* ;

: haversine                            ( lat1 lon1 lat2 lon2 -- haversine)
  frot difference                      ( lat1 lat2 dLon^2)
  frot frot fover fover                ( dLon^2 lat1 lat2 lat1 lat2)
  fswap difference                     ( dLon^2 lat1 lat2 dLat^2)
  fswap deg>rad fcos                   ( dLon^2 lat1 dLat^2 lat2)
  frot  deg>rad fcos f*                ( dLon^2 dLat2 lat1*lat2)
  frot  f* f+                          ( lat1*lat2*dLon^2+dLat^2)
  fsqrt fasin 127456 s>f f* 10 s>f f/  ( haversine)
;

36.12e -86.67e 33.94e -118.40e haversine cr f.


program example
implicit none
real :: d

d = haversine(36.12,-86.67,33.94,-118.40) ! BNA to LAX
print '(A,F9.4,A)', 'distance: ',d,' km' ! distance: 2887.2600 km

contains

      function to_radian(degree) result(rad)
          ! degrees to radians
          real,intent(in) :: degree
          real, parameter :: deg_to_rad = atan(1.0)/45 ! exploit intrinsic atan to generate pi/180 runtime constant
          real :: rad

          rad = degree*deg_to_rad
      end function to_radian

      function haversine(deglat1,deglon1,deglat2,deglon2) result (dist)
          ! great circle distance -- adapted from Matlab
          real,intent(in) :: deglat1,deglon1,deglat2,deglon2
          real :: a,c,dist,dlat,dlon,lat1,lat2
          real,parameter :: radius = 6372.8

          dlat = to_radian(deglat2-deglat1)
          dlon = to_radian(deglon2-deglon1)
          lat1 = to_radian(deglat1)
          lat2 = to_radian(deglat2)
          a = (sin(dlat/2))**2 + cos(lat1)*cos(lat2)*(sin(dlon/2))**2
          c = 2*asin(sqrt(a))
          dist = radius*c
      end function haversine

end program example


INT base10 = 10, num happy = 8;

PROC next = (INT in n)INT: (
  INT n := in n;
  INT out := 0;
  WHILE n NE 0 DO
    out +:= ( n MOD base10 ) ** 2;
    n := n OVER base10
  OD;
  out
);

PROC is happy = (INT in n)BOOL: (
  INT n := in n;
  FOR i WHILE n NE 1 AND n NE 4 DO n := next(n) OD;
  n=1
);

INT count := 0;
FOR i WHILE count NE num happy DO
  IF is happy(i) THEN
    count +:= 1;
    print((i, new line))
  FI
OD


begin
integer function mod(a,b);
integer a,b;
mod := a-(a/b)*b;

integer function sumdgtsq(n);
integer n;
sumdgtsq :=
    if n = 0 then 0
    else mod(n,10)*mod(n,10) + sumdgtsq(n/10);

integer function happy(n);
integer n;
begin
    integer i;
    integer array seen[0:200];
    for i := 0 step 1 until 200 do seen[i] := 0;

    while seen[n] = 0 do
    begin
        seen[n] := 1;
        n := sumdgtsq(n);
    end;
    happy := if n = 1 then 1 else 0;
end;

integer i, n;
i := n := 0;
while n < 8 do
begin
    if happy(i) = 1 then
    begin
        write(i);
        n := n + 1;
    end;
    i := i + 1;
end;
end


 EXECUTE BLOCK
   RETURNS(S VARCHAR(40))
 AS
 BEGIN
   S = 'Hello world!';
   SUSPEND;
 END


OpenConsole()
PrintN("Hello world!")
Input() ; Wait for enter


program HaversineDemo;
uses
  Math;

function HaversineDistance(const lat1, lon1, lat2, lon2:double):double;inline;
const
  rads = pi / 180;
  dia  = 2 * 6372.8;
begin
  HaversineDistance := dia * arcsin(sqrt(sqr(cos(rads * (lon1 - lon2)) * cos(rads * lat1)
                     - cos(rads * lat2)) + sqr(sin(rads * (lon1 - lon2))
                     * cos(rads * lat1)) + sqr(sin(rads * lat1) - sin(rads * lat2))) / 2);
end;

begin
  Writeln('Haversine distance between BNA and LAX: ', HaversineDistance(36.12, -86.67, 33.94, -118.4):7:2, ' km.');
end.


' version 09-10-2016
' compile with: fbc -s console

' Nashville International Airport (BNA) in Nashville, TN, USA,
' N 36°07.2',  W  86°40.2' (36.12,  -86.67)
' Los Angeles International Airport (LAX) in Los Angeles, CA, USA,
' N 33°56.4', W 118°24.0'  (33.94, -118.40).
' 6372.8 km is an approximation of the radius of the average circumference

#Define Pi Atn(1) * 4        ' define Pi = 3.1415..
#Define deg2rad Pi / 180     ' define deg to rad 0.01745..
#Define earth_radius 6372.8  ' earth radius in km.

Function Haversine(lat1 As Double, long1 As Double, lat2 As Double, _
                                long2 As Double , radius As Double) As Double

  Dim As Double d_long = deg2rad * (long1 - long2)
  Dim As Double theta1 = deg2rad * lat1
  Dim As Double theta2 = deg2rad * lat2
  Dim As Double dx = Cos(d_long) * Cos(theta1) - Cos(theta2)
  Dim As Double dy = Sin(d_long) * Cos(theta1)
  Dim As Double dz = Sin(theta1) - Sin(theta2)
  Return Asin(Sqr(dx*dx + dy*dy + dz*dz) / 2) * radius * 2

End Function

Print
Print " Haversine distance between BNA and LAX = "; _
      Haversine(36.12, -86.67, 33.94, -118.4, earth_radius); " km."

' empty keyboard buffer
While Inkey <> "" : Wend
Print : Print "hit any key to end program"
Sleep
End


begin
    % find some happy numbers                                      %
    % returns true if n is happy, false otherwise; n must be >= 0  %
    logical procedure isHappy( integer value n ) ;
        if n < 2 then true
        else begin
            % seen is used to hold the values of the cycle of the  %
            % digit square sums, as noted in the Batch File        %
            % version, we do not need a large array. The digit     %
            % square sum of 9 999 999 999 is 810...                %
            integer array seen( 0 :: 32 );
            integer number, trys;
            number             := n;
            trys               := -1;
            while begin
                logical terminated;
                integer tPos;
                terminated     := false;
                tPos           := 0;
                while not terminated and tPos <= trys do begin
                    terminated := seen( tPos ) = number;
                    tPos       := tPos + 1
                end while_not_terminated_and_tPos_lt_trys ;
                number > 1 and not terminated
            end do begin
                integer sum;
                trys           := trys + 1;
                seen( trys )   := number;
                sum            := 0;
                while number > 0 do begin
                    integer digit;
                    digit      := number rem 10;
                    number     := number div 10;
                    sum        := sum + ( digit * digit )
                end while_number_gt_0 ;
                number         := sum
            end while_number_gt_1_and_not_terminated ;
            number = 1
        end isHappy ;
    % print the first 8 happy numbers                               %
    begin
        integer       happyCount, n;
        happyCount := 0;
        n          := 1;
        write( "first 8 happy numbers: " );
        while happyCount < 8 do begin
            if isHappy( n ) then begin
                writeon( i_w := 1, " ", n );
                happyCount := happyCount + 1
            end if_isHappy_n ;
            n := n + 1
        end while_happyCount_lt_8
    end
end.


     ∇ HappyNumbers arg;⎕IO;∆roof;∆first;bin;iroof
[1]   ⍝0: Happy number
[2]   ⍝1: http://rosettacode.org/wiki/Happy_numbers
[3]    ⎕IO←1                              ⍝ Index origin
[4]    ∆roof ∆first←2↑arg,10              ⍝
[5]
[6]    bin←{
[7]        ⍺←⍬                            ⍝ Default left arg
[8]        ⍵=1:1                          ⍝ Always happy!
[9]
[10]       numbers←⍎¨1⊂⍕⍵                 ⍝ Split numbers into parts
[11]       next←+/{⍵*2}¨numbers           ⍝ Sum and square of numbers
[12]
[13]       next∊⍺:0                       ⍝ Return 0, if already exists
[14]       (⍺,next)∇ next                 ⍝ Check next number (recursive)
[15]
[16]   }¨iroof←⍳∆roof                     ⍝ Does all numbers upto ∆root smiles?
[17]
[18]   ⎕←~∘0¨∆first↑bin/iroof             ⍝ Show ∆first numbers, but not 0
     ∇


haversine[theta] := (1-cos[theta])/2

dist[lat1, long1, lat2, long2] := 2 earthradius arcsin[sqrt[haversine[lat2-lat1] + cos[lat1] cos[lat2] haversine[long2-long1]]]

d = dist[36.12 deg, -86.67 deg, 33.94 deg, -118.40 deg]
println[d-> "km"]


import math.*

def haversin( theta ) = (1 - cos( theta ))/2

def radians( deg ) = deg Pi/180

def haversine( (lat1, lon1), (lat2, lon2) ) =
  R = 6372.8
  h = haversin( radians(lat2 - lat1) ) + cos( radians(lat1) ) cos( radians(lat2) ) haversin( radians(lon2 - lon1) )
  2R asin( sqrt(h) )

println( haversine((36.12, -86.67), (33.94, -118.40)) )


window 1

local fn Haversine( lat1 as double, lon1 as double, lat2 as double, lon2 as double, miles as ^double, kilometers as ^double )
  double deg2rad, dLat, dLon, a, c, earth_radius_miles, earth_radius_kilometers

  earth_radius_miles = 3959.0 // Radius of the Earth in miles
  earth_radius_kilometers = 6372.8 // Radius of the Earth in kilometers
  deg2rad = Pi / 180 // Pi is predefined in FutureBasic

  dLat = deg2rad * ( lat2  - lat1 )
  dLon = deg2rad * ( lon2 - lon1 )
  a = sin( dLat / 2 ) * sin( dLat / 2 ) + cos( deg2rad * lat1 ) * cos( deg2rad * lat2 ) * sin( dLon / 2 ) * sin( dLon / 2 )
  c = 2 * asin( sqr(a) )

  miles.nil# =  earth_radius_miles * c
  kilometers.nil# = earth_radius_kilometers * c
end fn

double miles, kilometers

fn Haversine( 36.12, -86.67, 33.94, -118.4, @miles, @kilometers )

print "Distance in miles between BNA and LAX: "; using "####.####"; miles; " miles."
print "Distance in kilometers between BNA LAX: "; using "####.####"; kilometers; " km."

HandleEvents


on run
    set howManyHappyNumbers to 8
    set happyNumberList to {}
    set globalCounter to 1

    repeat howManyHappyNumbers times
        repeat while not isHappy(globalCounter)
            set globalCounter to globalCounter + 1
        end repeat
        set end of happyNumberList to globalCounter
        set globalCounter to globalCounter + 1
    end repeat
    log happyNumberList
end run

on isHappy(numberToCheck)
    set localCycle to {}
    repeat while (numberToCheck ≠ 1)
        if localCycle contains numberToCheck then
            exit repeat
        end if
        set end of localCycle to numberToCheck
        set tempNumber to 0
        repeat while (numberToCheck > 0)
            set digitOfNumber to numberToCheck mod 10
            set tempNumber to tempNumber + (digitOfNumber ^ 2)
            set numberToCheck to (numberToCheck - digitOfNumber) / 10
        end repeat
        set numberToCheck to tempNumber
    end repeat
    return (numberToCheck = 1)
end isHappy


 0 C = 8: DIM S(16):B = 10: PRINT "THE FIRST "C" HAPPY NUMBERS": FOR R = C TO 0 STEP 0:N = H: GOSUB 1: PRINT  MID$ (" " +  STR$ (H),1 + (R = C),255 * I);:R = R - I:H = H + 1: NEXT R: END
 1 S = 0: GOSUB 3:I = N = 1: IF  NOT Q THEN  RETURN
 2  FOR Q = 1 TO 0 STEP 0:S(S) = N:S = S + 1: GOSUB 6:N = T: GOSUB 3: NEXT Q:I = N = 1: RETURN
 3 Q = N > 1: IF  NOT Q OR  NOT S THEN  RETURN
 4 Q = 0: FOR I = 0 TO S - 1: IF N = S(I) THEN  RETURN
 5  NEXT I:Q = 1: RETURN
 6 T = 0: FOR I = N TO 0 STEP 0:M =  INT (I / B):T =  INT (T + (I - M * B) ^ 2):I = M: NEXT I: RETURN


package main

import (
    "fmt"
    "math"
)

func haversine(θ float64) float64 {
    return .5 * (1 - math.Cos(θ))
}

type pos struct {
    φ float64 // latitude, radians
    ψ float64 // longitude, radians
}

func degPos(lat, lon float64) pos {
    return pos{lat * math.Pi / 180, lon * math.Pi / 180}
}

const rEarth = 6372.8 // km

func hsDist(p1, p2 pos) float64 {
    return 2 * rEarth * math.Asin(math.Sqrt(haversine(p2.φ-p1.φ)+
        math.Cos(p1.φ)*math.Cos(p2.φ)*haversine(p2.ψ-p1.ψ)))
}

func main() {
    fmt.Println(hsDist(degPos(36.12, -86.67), degPos(33.94, -118.40)))
}


def haversine(lat1, lon1, lat2, lon2) {
  def R = 6372.8
  // In kilometers
  def dLat = Math.toRadians(lat2 - lat1)
  def dLon = Math.toRadians(lon2 - lon1)
  lat1 = Math.toRadians(lat1)
  lat2 = Math.toRadians(lat2)

  def a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.sin(dLon / 2) * Math.sin(dLon / 2) * Math.cos(lat1) * Math.cos(lat2)
  def c = 2 * Math.asin(Math.sqrt(a))
  R * c
}

haversine(36.12, -86.67, 33.94, -118.40)

> 2887.25995060711


ord0: to :integer `0`
happy?: function [x][
    n: x
    past: new []

    while [n <> 1][
        s: to :string n
        n: 0
        loop s 'c [
            i: (to :integer c) - ord0
            n: n + i * i
        ]
        if contains? past n -> return false
        'past ++ n
    ]
    return true
]

loop 0..31 'x [
    if happy? x -> print x
]


Loop {
  If isHappy(A_Index) {
    out .= (out="" ? "" : ",") . A_Index
    i ++
    If (i = 8) {
      MsgBox, The first 8 happy numbers are: %out%
      ExitApp
    }
  }
}

isHappy(num, list="") {
  list .= (list="" ? "" : ",") . num
  Loop, Parse, num
    sum += A_LoopField ** 2
  If (sum = 1)
    Return true
  Else If sum in %list%
    Return false
  Else Return isHappy(sum, list)
}


class HelloWorld
	**Prints "Hello world!"**

	on start

		print "Hello world!"


import Control.Monad (join)
import Data.Bifunctor (bimap)
import Text.Printf (printf)

-------------------- HAVERSINE FORMULA -------------------

-- The haversine of an angle.
haversine :: Float -> Float
haversine = (^ 2) . sin . (/ 2)

-- The approximate distance, in kilometers,
-- between two points on Earth.
-- The latitude and longtitude are assumed to be in degrees.
greatCircleDistance ::
  (Float, Float) ->
  (Float, Float) ->
  Float
greatCircleDistance = distDeg 6371
  where
    distDeg radius p1 p2 =
      distRad
        radius
        (deg2rad p1)
        (deg2rad p2)
    distRad radius (lat1, lng1) (lat2, lng2) =
      (2 * radius)
        * asin
          ( min
              1.0
              ( sqrt $
                  haversine (lat2 - lat1)
                    + ( (cos lat1 * cos lat2)
                          * haversine (lng2 - lng1)
                      )
              )
          )
    deg2rad = join bimap ((/ 180) . (pi *))

--------------------------- TEST -------------------------
main :: IO ()
main =
  printf
    "The distance between BNA and LAX is about %0.f km.\n"
    (greatCircleDistance bna lax)
  where
    bna = (36.12, -86.67)
    lax = (33.94, -118.40)


link printf

procedure main()  #: Haversine formula
   printf("BNA to LAX is %d km (%d miles)\n",
      d := gcdistance([36.12, -86.67],[33.94, -118.40]),d*3280/5280)  # with cute km2mi conversion
end

procedure gcdistance(a,b)
	a[2] -:= b[2]
   every (x := a|b)[i := 1 to 2] := dtor(x[i])
	dz := sin(a[1]) - sin(b[1])
	dx := cos(a[2]) * cos(a[1]) - cos(b[1])
	dy := sin(a[2]) * cos(a[1])
	return asin(sqrt(dx * dx + dy * dy + dz * dz) / 2) * 2 * 6371
end