$c = 0
$k = 0
While $c < 8
	$k += 1
	$n = $k
	While $n <> 1
		$s = StringSplit($n, "")
		$t = 0
		For $i = 1 To $s[0]
			$t += $s[$i] ^ 2
		Next
		$n = $t
		Switch $n
			Case 4,16,37,58,89,145,42,20
			ExitLoop
		EndSwitch
	WEnd
	If $n = 1 Then
		ConsoleWrite($k & " is Happy" & @CRLF)
		$c += 1
	EndIf
WEnd


function is_happy(n)
{
  if ( n in happy ) return 1;
  if ( n in unhappy ) return 0;
  cycle[""] = 0
  while( (n!=1) && !(n in cycle) ) {
    cycle[n] = n
    new_n = 0
    while(n>0) {
      d = n % 10
      new_n += d*d
      n = int(n/10)
    }
    n = new_n
  }
  if ( n == 1 ) {
    for (i_ in cycle) {
      happy[cycle[i_]] = 1
      delete cycle[i_]
    }
    return 1
  } else {
    for (i_ in cycle) {
      unhappy[cycle[i_]] = 1
      delete cycle[i_]
    }
    return 0
  }
}

BEGIN {
  cnt = 0
  happy[""] = 0
  unhappy[""] = 0
  for(j=1; (cnt < 8); j++) {
    if ( is_happy(j) == 1 ) {
      cnt++
      print j
    }
  }
}


program hello

write(*,101)"Hello World"
101 format(A)

end


module Main

-- The haversine of an angle.
hsin : Double -> Double
hsin t = let u = sin (t/2) in u*u

-- The distance between two points, given by latitude and longtitude, on a
-- circle.  The points are specified in radians.
distRad : Double -> (Double, Double) -> (Double, Double) -> Double
distRad radius (lat1, lng1) (lat2, lng2) =
  let hlat = hsin (lat2 - lat1)
      hlng = hsin (lng2 - lng1)
      root = sqrt (hlat + cos lat1 * cos lat2 * hlng)
  in 2 * radius * asin (min 1.0 root)

-- The distance between two points, given by latitude and longtitude, on a
-- circle.  The points are specified in degrees.
distDeg : Double -> (Double, Double) -> (Double, Double) -> Double
distDeg radius p1 p2 = distRad radius (deg2rad p1) (deg2rad p2)
  where
        d2r : Double -> Double
        d2r t = t * pi / 180
        deg2rad (t, u) = (d2r t, d2r u)

-- The approximate distance, in kilometers, between two points on Earth.
-- The latitude and longtitude are assumed to be in degrees.
earthDist : (Double, Double) -> (Double, Double) -> Double
earthDist = distDeg 6372.8

main : IO ()
main = putStrLn $ "The distance between BNA and LAX is about " ++ show (floor dst) ++ " km."
 where
      bna : (Double, Double)
      bna = (36.12,  -86.67)

      lax : (Double, Double)
      lax = (33.94, -118.40)

      dst : Double
      dst = earthDist bna lax


100 PROGRAM "Haversine.bas"
110 PRINT "Haversine distance:";HAVERSINE(36.12,-86.67,33.94,-118.4);"km"
120 DEF HAVERSINE(LAT1,LON1,LAT2,LON2)
130   OPTION ANGLE RADIANS
140   LET R=6372.8
150   LET DLAT=RAD(LAT2-LAT1):LET DLON=RAD(LON2-LON1)
160   LET LAT1=RAD(LAT1):LET LAT2=RAD(LAT2)
170   LET HAVERSINE=R*2*ASIN(SQR(SIN(DLAT/2)^2+SIN(DLON/2)^2*COS(LAT1)*COS(LAT2)))
190 END DEF


require 'trig'
haversin=: 0.5 * 1 - cos
Rearth=: 6372.8
haversineDist=: Rearth * haversin^:_1@((1 , *&([email protected]{.)) +/ .* [: haversin -)&rfd


n = 1 : cnt = 0
print "The first 8 isHappy numbers are:"
print

while cnt < 8
    if isHappy(n) = 1 then
        cnt += 1
        print cnt; " => "; n
    end if
    n += 1
end while

function isHappy(num)
    isHappy = 0
    cont = 0
    while cont < 50 and isHappy <> 1
        num$ = string(num)
        cont += 1
        isHappy	= 0
        for i = 1 to length(num$)
            isHappy += int(mid(num$,i,1)) ^ 2
        next i
        num = isHappy
    end while
end function


Function Run(args() as String) As Integer
  Print "Hello world!"
  Quit
End Function


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

        double a = Math.pow(Math.sin(dLat / 2),2) + Math.pow(Math.sin(dLon / 2),2) * Math.cos(lat1) * Math.cos(lat2);
        double c = 2 * Math.asin(Math.sqrt(a));
        return R * c;
    }
    public static void main(String[] args) {
        System.out.println(haversine(36.12, -86.67, 33.94, -118.40));
    }
}


function haversine() {
       var radians = Array.prototype.map.call(arguments, function(deg) { return deg/180.0 * Math.PI; });
       var lat1 = radians[0], lon1 = radians[1], lat2 = radians[2], lon2 = radians[3];
       var R = 6372.8; // km
       var dLat = lat2 - lat1;
       var dLon = lon2 - lon1;
       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 * c;
}
console.log(haversine(36.12, -86.67, 33.94, -118.40));


@echo off
setlocal enableDelayedExpansion
::Define a list with 10 terms as a convenience for defining a loop
set "L10=0 1 2 3 4 5 6 7 8 9"
shift /1 & goto %1
exit /b

:list min count
:: This routine prints all happy numbers > min (arg1)
:: until it finds count (arg2) happy numbers.
set /a "n=%~1, cnt=%~2"
call :listInternal
exit /b

:test min [max]
:: This routine sequentially tests numbers between min (arg1) and max (arg2)
:: to see if they are happy. If max is not specified then it defaults to min.
set /a "min=%~1"
if "%~2" neq "" (set /a "max=%~2") else set max=%min%
::The FOR /L loop does not detect integer overflow, so must protect against
::an infinite loop when max=0x7FFFFFFFF
set end=%max%
if %end% equ 2147483647 set /a end-=1
for /l %%N in (%min% 1 %end%) do (
  call :testInternal %%N && (echo %%N is happy :^)) || echo %%N is sad :(
)
if %end% neq %max% call :testInternal %max% && (echo %max% is happy :^)) || echo %max% is sad :(
exit /b

  :listInternal
  :: This loop sequentially tests each number >= n. The loop conditionally
  :: breaks within the body once cnt happy numbers have been found, or if
  :: the max integer value is reached. Performance is improved by using a
  :: FOR loop to perform most of the looping, with a GOTO only needed once
  :: per 100 iterations.
  for %%. in (
    %L10% %L10% %L10% %L10% %L10% %L10% %L10% %L10% %L10% %L10%
  ) do (
    call :testInternal !n! && (
      echo !n!
      set /a cnt-=1
      if !cnt! leq 0 exit /b 0
    )
    if !n! equ 2147483647 (
      >&2 echo ERROR: Maximum integer value reached
      exit /b 1
    )
    set /a n+=1
  )
  goto :listInternal

  :testInternal n
  :: This routine loops until the sum of squared digits converges on 1 (happy)
  :: or it detects a cycle (sad). It exits with errorlevel 0 for happy and 1 for sad.
  :: Performance is improved by using a FOR loop for the looping instead of a GOTO.
  :: Numbers less than 1000 never neeed more than 20 iterations, and any number
  :: with 4 or more digits shrinks by at least one digit each iteration.
  :: Since Windows batch can't handle more than 10 digits, allowance for 27
  :: iterations is enough, and 30 is more than adequate.
  setlocal
  set n=%1
  for %%. in (%L10% %L10% %L10%) do (
    if !n!==1 exit /b 0
    %= Only numbers < 1000 can cycle =%
    if !n! lss 1000 (
      if defined t.!n! exit /b 1
      set t.!n!=1
    )
    %= Sum the squared digits                                          =%
    %= Batch can't handle numbers greater than 10 digits so we can use =%
    %= a constrained FOR loop and avoid a slow goto                    =%
    set sum=0
    for /l %%N in (1 1 10) do (
      if !n! gtr 0 set /a "sum+=(n%%10)*(n%%10), n/=10"
    )
    set /a n=sum
  )


def haversine(lat1;lon1; lat2;lon2):
  def radians: . * (1|atan)/45;
  def sind: radians|sin;
  def cosd: radians|cos;
  def sq: . * .;

    (((lat2 - lat1)/2) | sind | sq) as $dlat
  | (((lon2 - lon1)/2) | sind | sq) as $dlon
  | 2 * 6372.8 * (( $dlat + (lat1|cosd) * (lat2|cosd) * $dlon ) | sqrt | asin) ;


/* Haversine formula, in Jsish */
function haversine() {
       var radians = arguments.map(function(deg) { return deg/180.0 * Math.PI; });
       var lat1 = radians[0], lon1 = radians[1], lat2 = radians[2], lon2 = radians[3];
       var R = 6372.8; // km
       var dLat = lat2 - lat1;
       var dLon = lon2 - lon1;
       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 * c;
}

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

/*
=!EXPECTSTART!=
haversine(36.12, -86.67, 33.94, -118.40) ==> 2887.259950607112
=!EXPECTEND!=
*/


with Gtk.Main;
with Glib;
with Gtk.Window;  use Gtk.Window;
with Gtk.Enums;   use Gtk.Enums;
with Ada.Text_IO; use Ada.Text_IO;

procedure Max_Size is

   Win          : Gtk_Window;
   Win_W, Win_H : Glib.Gint;
   package Int_Io is new Integer_IO (Glib.Gint);
   Hid : Gtk.Main.Quit_Handler_Id;

begin
   Gtk.Main.Init;
   Gtk_New (Win);
   Initialize (Win, Window_Toplevel);
   Maximize (Win);
   Show (Win);
   Get_Size (Win, Win_W, Win_H);
   Put ("Maximum dimensions of window : W ");
   Int_Io.Put (Win_W, Width => 4);
   Put (" x H ");
   Int_Io.Put (Win_H, Width => 4);
   New_Line;
   Hid := Gtk.Main.Quit_Add_Destroy (0, Win);
end Max_Size;


      number% = 0
      total% = 0
      REPEAT
        number% += 1
        IF FNhappy(number%) THEN
          PRINT number% " is a happy number"
          total% += 1
        ENDIF
      UNTIL total% = 8
      END

      DEF FNhappy(num%)
      LOCAL digit&()
      DIM digit&(10)
      REPEAT
        digit&() = 0
        $$^digit&(0) = STR$(num%)
        digit&() AND= 15
        num% = MOD(digit&())^2 + 0.5
      UNTIL num% = 1 OR num% = 4
      = (num% = 1)


get "libhdr"

let sumdigitsq(n) =
    n=0 -> 0, (n rem 10)*(n rem 10)+sumdigitsq(n/10)

let happy(n) = valof
$(  let seen = vec 255
    for i = 0 to 255 do i!seen := false
    $(  n!seen := true
        n := sumdigitsq(n)
    $) repeatuntil n!seen
    resultis 1!seen
$)

let start() be
$(  let n, i = 0, 0
    while n < 8 do
    $(  if happy(i) do
        $(  n := n + 1
            writef("%N ",i)
        $)
        i := i + 1
    $)
    wrch('*N')
$)


/*REXX program to show a line of text.  */
say 'Hello world!'


.data
hello:
.string "Hello World!\n\0"
.text
main:
la a0, hello
li a7, 4
ecall
li a7, 10
ecall


import java.lang.Math.*

const val R = 6372.8 // in kilometers

fun haversine(lat1: Double, lon1: Double, lat2: Double, lon2: Double): Double {
    val λ1 = toRadians(lat1)
    val λ2 = toRadians(lat2)
    val Δλ = toRadians(lat2 - lat1)
    val Δφ = toRadians(lon2 - lon1)
    return 2 * R * asin(sqrt(pow(sin(Δλ / 2), 2.0) + pow(sin(Δφ / 2), 2.0) * cos(λ1) * cos(λ2)))
}

fun main(args: Array<String>) = println("result: " + haversine(36.12, -86.67, 33.94, -118.40))


print "Haversine distance: "; using( "####.###########", havDist( 36.12, -86.67, 33.94, -118.4)); " km."
end
function havDist( th1, ph1, th2, ph2)
  degtorad   = acs(-1)/180
  diameter   = 2 * 6372.8
    LgD      = degtorad  * (ph1 - ph2)
    th1      = degtorad  * th1
    th2      = degtorad  * th2
    dz       = sin( th1) - sin( th2)
    dx       = cos( LgD) * cos( th1) - cos( th2)
    dy       = sin( LgD) * cos( th1)
    havDist  = asn( ( dx^2 +dy^2 +dz^2)^0.5 /2) *diameter
end function


SysGet, MonitorCount, MonitorCount
SysGet, MonitorPrimary, MonitorPrimary
MsgBox, Monitor Count:`t%MonitorCount%`nPrimary Monitor:`t%MonitorPrimary%
Loop, %MonitorCount%
{
    SysGet, MonitorName, MonitorName, %A_Index%
    SysGet, Monitor, Monitor, %A_Index%
    SysGet, MonitorWorkArea, MonitorWorkArea, %A_Index%
    MsgBox, % "Monitor:`t#" A_Index
            . "`nName:`t" MonitorName
            . "`nLeft:`t" MonitorLeft "(" MonitorWorkAreaLeft " work)"
            . "`nTop:`t" MonitorTop " (" MonitorWorkAreaTop " work)"
            . "`nRight:`t" MonitorRight " (" MonitorWorkAreaRight " work)"
            . "`nBottom:`t" MonitorBottom " (" MonitorWorkAreaBottom " work)"
}


OPTION GUI TRUE
PRAGMA GUI gtk3

FUNCTION Define_Window

    LOCAL (*max)() = gtk_window_maximize TYPE void
    LOCAL id

    id = GUIDEFINE("{ type=WINDOW name=window }")
    CALL GUIFN(id, "window", max)
    RETURN id

ENDFUNCTION

SUB Print_Dimensions

    LOCAL (*size)() = gtk_window_get_size TYPE void
    LOCAL x, y

    CALL GUIFN(gui, "window", size, &x, &y)
    PRINT x, "-", y
    END

ENDSUB

gui = Define_Window()
ALARM Print_Dimensions, 500
event$ = GUIEVENT$(gui)


      SPI_GETWORKAREA = 48
      DIM rc{l%,t%,r%,b%}
      SYS "SystemParametersInfo", SPI_GETWORKAREA, 0, rc{}, 0
      PRINT "Maximum width = " ; rc.r% - rc.l%
      PRINT "Maximum height = " ; rc.b% - rc.t%


#include<windows.h>
#include<stdio.h>

int main()
{
	printf("Dimensions of the screen are (w x h) : %d x %d pixels",GetSystemMetrics(SM_CXSCREEN),GetSystemMetrics(SM_CYSCREEN));
	return 0;
}


bool isHappy (int n)
{
   ints cache;

   while (n != 1)
   {
      int sum = 0;

      if (cache.contains(n))
         return false;

      cache.add(n);
      while (n != 0)
      {
         int digit = n % 10;
         sum += (digit * digit);
         n = (int)(n / 10);
      }
      n = sum;
   }
   return true;
}

void test ()
{
   int num = 1;
   ints happynums;

   while (happynums.count() < 8)
   {
      if (isHappy(num))
         happynums.add(num);
      num++;
   }
   puts("First 8 happy numbers : " + str.newline + happynums);
}


SumSqDgt ← +´2⋆˜ •Fmt-'0'˙
Happy ← ⟨⟩{𝕨((⊑∊˜ )◶⟨∾𝕊(SumSqDgt⊢),1=⊢⟩)𝕩}⊢
8↑Happy¨⊸/↕50


TITLE Goodbye World;

LET NL=10;

EXT PROC(REF ARRAY BYTE) TWRT;

ENT PROC INT RRJOB();

    TWRT("Hello world!#NL#");
    RETURN(1);

ENDPROC;


function radians n
    return n * (3.1415926 / 180)
end radians

function haversine lat1, lng1, lat2, lng2
    local radiusEarth
    local lat3, lng3
    local lat1Rad, lat2Rad, lat3Rad
    local lngRad1, lngRad2, lngRad3
    local haver
    put 6372.8 into radiusEarth
    put (lat2 - lat1) into lat3
    put (lng2 - lng1) into lng3
    put radians(lat1) into lat1Rad
    put radians(lat2) into lat2Rad
    put radians(lat3) into lat3Rad
    put radians(lng1) into lngRad1
    put radians(lng2) into lngRad2
    put radians(lng3) into lngRad3

    put (sin(lat3Rad/2.0)^2) + (cos(lat1Rad)) \
          * (cos(lat2Rad)) \
          * (sin(lngRad3/2.0)^2) \
          into haver
    return (radiusEarth * (2.0 * asin(sqrt(haver))))

end haversine


distance := (theta1, phi1, theta2, phi2)->2*6378.14*arcsin( sqrt((1-cos(theta2-theta1))/2 + cos(theta1)*cos(theta2)*(1-cos(phi2-phi1))/2) );


using System;
using System.Drawing;
using System.Windows.Forms;

static class Program
{
    static void Main()
    {
        Rectangle bounds = Screen.PrimaryScreen.Bounds;
        Console.WriteLine($"Primary screen bounds:  {bounds.Width}x{bounds.Height}");

        Rectangle workingArea = Screen.PrimaryScreen.WorkingArea;
        Console.WriteLine($"Primary screen working area:  {workingArea.Width}x{workingArea.Height}");
    }
}


DEF Win:WINDOW
DEF Close:CHAR

DEF ScreenSizeX,ScreenSizeY:INT
DEF L,T,ClientWidth,ClientHeight:INT

GETSCREENSIZE(ScreenSizeX,ScreenSizeY)

WINDOW Win,0,0,ScreenSizeX,ScreenSizeY,@MINBOX|@MAXBOX|@SIZE|@MAXIMIZED,0,"Get Client Size",MainHandler

'Left and top are always zero for this function.
GETCLIENTSIZE(Win,L,T,ClientWidth,ClientHeight)

PRINT Win,"Maximum drawing area values: width is"+STR$(ClientWidth)+" and height is"+STR$(ClientHeight)+"."

WAITUNTIL Close=1

CLOSEWINDOW Win

END

SUB MainHandler

	SELECT @CLASS

	CASE @IDCLOSEWINDOW

	Close=1

	ENDSELECT

RETURN

Output: Maximum drawing area values: width is 1280 and height is 749.


unit Main;

interface

uses
  Winapi.Windows, System.SysUtils, Vcl.Forms;

type
  TForm1 = class(TForm)
    procedure FormCreate(Sender: TObject);
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.FormCreate(Sender: TObject);
var
 w,h:Integer;
begin
  w := Screen.Monitors[0].WorkareaRect.Width;
  h := Screen.Monitors[0].WorkareaRect.Height;
  Caption:= format('%d x %d',[w,h]);
  SetBounds(0,0,w,h);
end;

end.


egl.defineClass(
	'utils', 'Browser',
{
	"getViewportWidth" : function () {
		return window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
	},
	"getViewportHeight" : function(){
		return window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
	}
});


#INCLUDE <Include\Windows.inc>
ShowWindow(ME, SW_MAXIMIZE)
BEGIN EVENTS
END EVENTS


include :set

happiness = set.new 1
sadness = set.new

sum_of_squares_of_digits = { num |
  num.to_s.dice.reduce 0 { sum, n | sum = sum + n.to_i ^ 2 }
}

happy? = { n, seen = set.new |
  when {true? happiness.include? n } { happiness.merge seen << n; true }
    { true? sadness.include? n } { sadness.merge seen; false }
    { true? seen.include? n } { sadness.merge seen; false }
    { true } { seen << n; happy? sum_of_squares_of_digits(n), seen }
}

num = 1
happies = []

while { happies.length < 8 } {
  true? happy?(num)
    { happies << num }

  num = num + 1
}

p "First eight happy numbers: #{happies}"
p "Happy numbers found: #{happiness.to_array.sort}"
p "Sad numbers found: #{sadness.to_array.sort}"


#include <stdio.h>

#define CACHE 256
enum { h_unknown = 0, h_yes, h_no };
unsigned char buf[CACHE] = {0, h_yes, 0};

int happy(int n)
{
	int sum = 0, x, nn;
	if (n < CACHE) {
		if (buf[n]) return 2 - buf[n];
		buf[n] = h_no;
	}

	for (nn = n; nn; nn /= 10) x = nn % 10, sum += x * x;

	x = happy(sum);
	if (n < CACHE) buf[n] = 2 - x;
	return x;
}

int main()
{
	int i, cnt = 8;
	for (i = 1; cnt || !printf("\n"); i++)
		if (happy(i)) --cnt, printf("%d ", i);

	printf("The %dth happy number: ", cnt = 1000000);
	for (i = 1; cnt; i++)
		if (happy(i)) --cnt || printf("%d\n", i);

	return 0;
}


fn main() {
   print!("Hello world!");
}


/* Using a data step. Will print the string in the log window */
data _null_;
put "Hello world!";
run;


distance[{theta1_, phi1_}, {theta2_, phi2_}] :=
 2*6378.14 [email protected]
   Sqrt[Haversine[(theta2 - theta1) Degree] +
     Cos[theta1*Degree] Cos[theta2*Degree] Haversine[(phi2 - phi1) Degree]]


function rad = radians(degree)
% degrees to radians
    rad = degree .* pi / 180;
end;

function [a,c,dlat,dlon]=haversine(lat1,lon1,lat2,lon2)
% HAVERSINE_FORMULA.AWK - converted from AWK
    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 .* asin(sqrt(a));
    arrayfun(@(x) printf("distance: %.4f km\n",6372.8 * x), c);
end;

[a,c,dlat,dlon] = haversine(36.12,-86.67,33.94,-118.40); % BNA to LAX


dms(d, m, s) := (d + m/60 + s/3600)*%pi/180$

great_circle_distance(lat1, long1, lat2, long2) :=
   12742*asin(sqrt(sin((lat2 - lat1)/2)^2 + cos(lat1)*cos(lat2)*sin((long2 - long1)/2)^2))$

/* Coordinates are found here:
      http://www.airport-data.com/airport/BNA/
      http://www.airport-data.com/airport/LAX/   */

great_circle_distance(dms( 36,  7, 28.10), -dms( 86, 40, 41.50),
                      dms( 33, 56, 32.98), -dms(118, 24, 29.05)), numer;
/* 2886.326609413624 */


' FB 1.05.0 Win64

' Using SystemParametersInfo function in Win32 API
Dim As Any Ptr library = DyLibLoad("user32")
Dim Shared SystemParametersInfo As Function (ByVal As ULong, ByVal As ULong, ByVal As Any Ptr, ByVal As ULong) As Long
SystemParametersInfo = DyLibSymbol(library, "SystemParametersInfoA")

Type Rect
  As Long left, top, right, bottom
End Type

#Define SPI_GETWORKAREA &H30
Dim r As Rect
SystemParametersInfo(SPI_GETWORKAREA, 0, @r, 0)
DyLibFree(library)
Print "Maximum usable desktop area :  W" ; r.right - r.left; " x H"; r.bottom - r.top; " pixels"
Print
Print "Press any key to quit"
Sleep


FMain.Maximized = True
FMain.Visible = False    ' The form can be invisible


Public Sub Form_Open()

Print Desktop.Width
Print Desktop.Height

End


package main

import (
    "fmt"
    "github.com/go-vgo/robotgo"
)

func main() {
    w, h := robotgo.GetScreenSize()
    fmt.Printf("Screen size: %d x %d\n", w, h)
    fpid, err := robotgo.FindIds("firefox")
    if err == nil && len(fpid) > 0 {
        pid := fpid[0]
        robotgo.ActivePID(pid)
        robotgo.MaxWindow(pid)
        _, _, w, h = robotgo.GetBounds(pid)
        fmt.Printf("Max usable : %d x %d\n", w, h)
    }
}


def window = java.awt.GraphicsEnvironment.localGraphicsEnvironment.maximumWindowBounds

println "width: $window.width, height: $window.height"


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace HappyNums
{
    class Program
    {
        public static bool ishappy(int n)
        {
            List<int> cache = new List<int>();
            int sum = 0;
            while (n != 1)
            {
                if (cache.Contains(n))
                {
                    return false;
                }
                cache.Add(n);
                while (n != 0)
                {
                    int digit = n % 10;
                    sum += digit * digit;
                    n /= 10;
                }
                n = sum;
                sum = 0;
            }
           return true;
        }

        static void Main(string[] args)
        {
            int num = 1;
            List<int> happynums = new List<int>();

            while (happynums.Count < 8)
            {
                if (ishappy(num))
                {
                    happynums.Add(num);
                }
                num++;
            }
            Console.WriteLine("First 8 happy numbers : " + string.Join(",", happynums));
        }
    }
}


class GOODBYE_WORLD is
 main is
  #OUT+"Hello world!\n";
 end;
end;


П3	->	П2	->	П1	->	П0
пи	1	8	0	/	П4
ИП1	МГ	ИП3	МГ	-	ИП4	*	П1	ИП0	МГ	ИП4	*	П0	ИП2	МГ	ИП4	*	П2
ИП0	sin	ИП2	sin	-	П8
ИП1	cos	ИП0	cos	*	ИП2	cos	-	П6
ИП1	sin	ИП0	cos	*	П7
ИП6	x^2	ИП7	x^2	ИП8	x^2	+	+	КвКор	2	/	arcsin	2	*	ИП5	*	С/П


DELIMITER $$

CREATE FUNCTION haversine (
		lat1 FLOAT, lon1 FLOAT,
		lat2 FLOAT, lon2 FLOAT
	) RETURNS FLOAT
	NO SQL DETERMINISTIC
BEGIN
	DECLARE r FLOAT unsigned DEFAULT 6372.8;
	DECLARE dLat FLOAT unsigned;
	DECLARE dLon FLOAT unsigned;
	DECLARE a FLOAT unsigned;
	DECLARE c FLOAT unsigned;

	SET dLat = ABS(RADIANS(lat2 - lat1));
	SET dLon = ABS(RADIANS(lon2 - lon1));
	SET lat1 = RADIANS(lat1);
	SET lat2 = RADIANS(lat2);

	SET a = POW(SIN(dLat / 2), 2) + COS(lat1) * COS(lat2) * POW(SIN(dLon / 2), 2);
	SET c = 2 * ASIN(SQRT(a));

	RETURN (r * c);
END$$

DELIMITER ;


import Graphics.UI.Gtk
import Control.Monad (when)
import Control.Monad.Trans (liftIO)

maximumWindowDimensions :: IO ()
maximumWindowDimensions = do
    -- initialize the internal state of the GTK toolkit
    initGUI
    -- create a window
    window <- windowNew
    -- quit the application when the window is closed
    on window objectDestroy mainQuit
    -- query the size of the window when its dimensions change
    on window configureEvent printSize
    -- get the screen the window will be drawn upon
    screen <- windowGetScreen window
    -- get the size of the screen
    x <- screenGetWidth screen
    y <- screenGetHeight screen
    -- print the dimensions of the screen
    putStrLn ("The screen is " ++ show x ++ " pixels wide and " ++
        show y ++ " pixels tall for an undecorated fullscreen window.")
    -- maximize the window and show it. printSize will then be called
    windowMaximize window
    widgetShowAll window
    -- run the main GTK loop.
    -- close the window manually.
    mainGUI

-- On my Xfce4 desktop, the configure_event is called three times when a
-- top level window is maximized. The first time, the window size
-- returned is the size prior to maximizing, and the last two times
-- it is the size after maximizing.
-- If the window is (un)maximized manually, the size returned is always
-- the size of the unmaximized window.
-- That means: either GTK or Xfce4 does not handle window maximization
-- correctly, or the GTK bindings for Haskell are buggy, or there is an
-- error in this program.

printSize :: EventM EConfigure Bool
printSize = do
    -- get the window that has been resized
    w <- eventWindow
    -- is the window maximized?
    s <- liftIO $ drawWindowGetState w
    when (WindowStateMaximized `elem` s) $ do
        -- get the size of the window that has been resized
        (x, y) <- eventSize
        -- print the dimensions out
        liftIO $ putStrLn ("The inner window region is now " ++ show x ++
            " pixels wide and " ++ show y ++ " pixels tall.")
    return True


link graphics

procedure main()  # Window size

W  := WOpen("canvas=hidden")
dh := WAttrib("displayheight")
dw := WAttrib("displaywidth")
WClose(W)

write("The display size is w=",dw,", h=",dh)
end


DEF Win:WINDOW
DEF Close:CHAR

DEF ScreenSizeX,ScreenSizeY:UINT
DEF L,T,ClientWidth,ClientHeight:INT

GETSCREENSIZE(ScreenSizeX,ScreenSizeY)

OPENWINDOW Win,0,0,ScreenSizeX,ScreenSizeY,@MAXBOX|@MINBOX|@SIZE|@MAXIMIZED,NULL,"Get client area",&MainHandler

'Left and top are always zero for this function.
GETCLIENTSIZE (Win,L,T,ClientWidth,ClientHeight)

PRINT Win,"Maximum drawing area values: width is"+STR$(ClientWidth)+" and height is"+STR$(ClientHeight)+"."

WAITUNTIL Close=1

CLOSEWINDOW WIN

END

SUB MainHandler

	SELECT @MESSAGE

	CASE @IDCLOSEWINDOW

	Close=1

	ENDSELECT

RETURN
ENDSUB

Output: Maximum drawing area values: width is 1280 and height is 749.


import java.awt.*;
import javax.swing.JFrame;

public class Test extends JFrame {

    public static void main(String[] args) {
        new Test();
    }

    Test() {
        Toolkit toolkit = Toolkit.getDefaultToolkit();

        Dimension screenSize = toolkit.getScreenSize();
        System.out.println("Physical screen size: " + screenSize);

        Insets insets = toolkit.getScreenInsets(getGraphicsConfiguration());
        System.out.println("Insets: " + insets);

        screenSize.width -= (insets.left + insets.right);
        screenSize.height -= (insets.top + insets.bottom);
        System.out.println("Max available: " + screenSize);
    }
}


#include <map>
#include <set>

bool happy(int number) {
  static std::map<int, bool> cache;

  std::set<int> cycle;
  while (number != 1 && !cycle.count(number)) {
    if (cache.count(number)) {
      number = cache[number] ? 1 : 0;
      break;
    }
    cycle.insert(number);
    int newnumber = 0;
    while (number > 0) {
      int digit = number % 10;
      newnumber += digit * digit;
      number /= 10;
    }
    number = newnumber;
  }
  bool happiness = number == 1;
  for (std::set<int>::const_iterator it = cycle.begin();
       it != cycle.end(); it++)
    cache[*it] = happiness;
  return happiness;
}

#include <iostream>

int main() {
  for (int i = 1; i < 50; i++)
    if (happy(i))
      std::cout << i << std::endl;
  return 0;
}


import math

proc radians(x): float = x * Pi / 180

proc haversine(lat1, lon1, lat2, lon2): float =
  const r = 6372.8 # Earth radius in kilometers
  let
    dLat = radians(lat2 - lat1)
    dLon = radians(lon2 - lon1)
    lat1 = radians(lat1)
    lat2 = radians(lat2)

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

  result = r * c

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


MODULE Haversines;
IMPORT
  LRealMath,
  Out;

  PROCEDURE Distance(lat1,lon1,lat2,lon2: LONGREAL): LONGREAL;
  CONST
    r = 6372.8D0; (* Earth radius as LONGREAL *)
    to_radians = LRealMath.pi / 180.0D0;
  VAR
    d,ph1,th1,th2: LONGREAL;
    dz,dx,dy: LONGREAL;
  BEGIN
    d := lon1 - lon2;
    ph1 := d * to_radians;
    th1 := lat1 * to_radians;
    th2 := lat2 * to_radians;

    dz := LRealMath.sin(th1) - LRealMath.sin(th2);
    dx := LRealMath.cos(ph1) * LRealMath.cos(th1) - LRealMath.cos(th2);
    dy := LRealMath.sin(ph1) * LRealMath.cos(th1);

    RETURN LRealMath.arcsin(LRealMath.sqrt(LRealMath.power(dx,2.0) + LRealMath.power(dy,2.0) + LRealMath.power(dz,2.0)) / 2.0) * 2.0 * r;
  END Distance;
BEGIN
  Out.LongRealFix(Distance(36.12,-86.67,33.94,-118.4),6,10);Out.Ln
END Haversines.


win = GtkWindow("hello", 100, 100)
fullscreen(win)
sleep(10)
println(width(win), " ", height(win))
destroy(win)


// version 1.1

import java.awt.Toolkit
import javax.swing.JFrame

class Test : JFrame() {
    init {
        val r = Regex("""\[.*\]""")
        val toolkit = Toolkit.getDefaultToolkit()
        val screenSize = toolkit.screenSize
        println("Physical screen size : ${formatOutput(screenSize, r)}")
        val insets = toolkit.getScreenInsets(graphicsConfiguration)
        println("Insets               : ${formatOutput(insets, r)}")
        screenSize.width  -= (insets.left + insets.right)
        screenSize.height -= (insets.top + insets.bottom)
        println("Max available        : ${formatOutput(screenSize, r)}")
    }

    private fun formatOutput(output: Any, r: Regex) = r.find(output.toString())!!.value.replace(",", ", ")
}

fun main(args: Array<String>) {
    Test()
}


Module CheckAllMonitors {
      mode  16 ' font size
      i=-1
      Flush
      Do {
            i++
            Window mode, i
            Print Window=i
            Wait 100
            Form ;   ' expand Background to fill monitor (form without arguments cut that frame)
            if window=i Then {
                  Background {
                        Cls 0, 0
                        data i,  scale.x, scale.y, motion.x, motion.y
                  }
            } else exit
      }  Always
      Dim Scrx(i), ScrY(i), ScrLeft(i), ScrTop(i)
      While Not Empty {
            Read i
            Read Scrx(i), ScrY(i), ScrLeft(i), ScrTop(i)
      }
      \\ check if we have same left top point
      For i=0 to Len(Scrx())-1 {
            Print "Monitor:", i, "left top (";ScrLeft(i);",";ScrTop(i);") size: (";Scrx(i);",";ScrY(i);")"
      }

      A=ScrLeft(0)
      B=ScrTop(0)
      LeftMargin=A
      TopMargin=B
      RightMargin=Scrx(0)+A
      BottomMargin=Scry(0)+B
      MaxArea=Scrx(0)*Scry(0)
      ChooseMonitor=0
      Out=True
      If Len(Scrx())>1 then {
            For i=1 to Len(Scrx())-1 {
                   LeftMargin=Min.Data(A, ScrLeft(i))
                   TopMargin=Min.Data(B, ScrTop(i))
                   RightMargin=Max.Data(RightMargin, Scrx(i)+Scrleft(i))
                   BottomMargin=Max.Data(BottomMargin, Scry(i)+ScrTop(i))
                   Out=Out and (A=ScrLeft(i) and  B=ScrTop(i))
                   if MaxArea<Scrx(i)*Scry(i) then MaxArea=Scrx(i)*Scry(i) : ChooseMonitor=i
            }
      }
      If Len(Scrx())=1 then {
            Print "One Monitor"
      } else  Print If$(Out ->"Clone Monitors", "Multiple Monitors ")
      Print "Left Top Corner:", LeftMargin, TopMargin
      Print "Width, Height", RightMargin-LeftMargin, BottomMargin-TopMargin
      Declare Form1 Form
      \\ After 100ms Form1 expand to all monitors
      After 100  {
            Method Form1,"Move", LeftMargin, TopMargin, RightMargin-LeftMargin, BottomMargin-TopMargin
      }
      \\ After 2000-100ms Form1 move to montior ChooseMonitor,  and has same width and height
      After 2000 {
                  Try {
                        Method Form1,"Move", ScrLeft(ChooseMonitor),ScrTop(ChooseMonitor), Scrx(ChooseMonitor), Scry(ChooseMonitor)
                  }
      }
      \\ after 4000 ms from other threads, form1 close
      After 4000 {
                  Try {
                        Method Form1, "CloseNow"
                  }
      }
      Method Form1, "Show", 1
      Declare Form1 Nothing
      Threads Erase
}
CheckAllMonitors


[email protected]@SystemInformation["Devices"][[1, 2, 1, 1, 2]]
->{{1260, 951}}


import
  gtk2, gdk2

nim_init()
var w = gdk2.screen_width()
var h = gdk2.screen_height()
echo("WxH=",w,"x",h)


(defn happy? [n]
  (loop [n n, seen #{}]
    (cond
      (= n 1)  true
      (seen n) false
      :else
        (recur (->> (str n)
                    (map #(Character/digit % 10))
                    (map #(* % %))
                    (reduce +))
               (conj seen n)))))

(def happy-numbers (filter happy? (iterate inc 1)))

(println (take 8 happy-numbers))


sum_dig_sq = proc (n: int) returns (int)
    sum_sq: int := 0
    while n > 0 do
        sum_sq := sum_sq + (n // 10) ** 2
        n := n / 10
    end
    return (sum_sq)
end sum_dig_sq

is_happy = proc (n: int) returns (bool)
    nn: int := sum_dig_sq(n)
    while nn ~= n cand nn ~= 1 do
        n := sum_dig_sq(n)
        nn := sum_dig_sq(sum_dig_sq(nn))
    end
    return (nn = 1)
end is_happy

happy_numbers = iter (start, num: int) yields (int)
    n: int := start
    while num > 0 do
        if is_happy(n) then
            yield (n)
            num := num-1
        end
        n := n+1
    end
end happy_numbers

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

    for i: int in happy_numbers(1, 8) do
        stream$putl(po, int$unparse(i))
    end
end start_up


$ include "seed7_05.s7i";

const proc: main is func
  begin
    writeln("Hello world!");
  end func;


bundle Default {
  class Haversine {
    function : Dist(th1 : Float, ph1 : Float, th2 : Float, ph2 : Float) ~ Float {
      ph1 -= ph2;
      ph1 := ph1->ToRadians();
      th1 := th1->ToRadians();
      th2 := th2->ToRadians();

      dz := th1->Sin()- th2->Sin();
      dx := ph1->Cos() * th1->Cos() - th2->Cos();
      dy := ph1->Sin() * th1->Cos();

      return ((dx * dx + dy * dy + dz * dz)->SquareRoot() / 2.0)->ArcSin() * 2 * 6371.0;
    }

    function : Main(args : String[]) ~ Nil {
      IO.Console->Print("distance: ")->PrintLine(Dist(36.12, -86.67, 33.94, -118.4));
    }
  }
}


+ (double) distanceBetweenLat1:(double)lat1 lon1:(double)lon1
                          lat2:(double)lat2 lon2:(double)lon2 {
    //degrees to radians
    double lat1rad = lat1 * M_PI/180;
    double lon1rad = lon1 * M_PI/180;
    double lat2rad = lat2 * M_PI/180;
    double lon2rad = lon2 * M_PI/180;

    //deltas
    double dLat = lat2rad - lat1rad;
    double dLon = lon2rad - lon1rad;

    double a = sin(dLat/2) * sin(dLat/2) + sin(dLon/2) * sin(dLon/2) * cos(lat1rad) * cos(lat2rad);
    double c = 2 * asin(sqrt(a));
    double R = 6372.8;
    return R * c;
}


use strict;
use warnings;
use Tk;

sub get_size {
	my $mw = MainWindow->new();
	return ($mw->maxsize);
}


include pGUI.e

IupOpen()

string scrnFullSize = IupGetGlobal("FULLSIZE")
string scrnSize = IupGetGlobal("SCREENSIZE")
string scrnMInfo = IupGetGlobal("MONITORSINFO")
string scrnVScreen = IupGetGlobal("VIRTUALSCREEN")

Ihandle dlg = IupDialog(NULL,"SIZE=FULL")
string scrnXSize = IupGetAttribute(dlg,"MAXSIZE")

?{scrnFullSize, scrnSize, scrnMInfo, scrnVScreen, scrnXSize}

IupClose()


(let Frame (java "javax.swing.JFrame" T "Window")
   (java Frame 'setExtendedState
      (java (public "javax.swing.JFrame" 'MAXIMIZED_BOTH)) )
   (java Frame 'setVisible T)
   (wait 200)
   (let Size (java (java Frame 'getContentPane) 'getSize)
      (prinl "Width: " (java (public Size 'width)))
      (prinl "Height: " (java (public Size 'height))) )
   (java Frame 'dispose) )


//Aamrun, 26th June 2022

fullScreen();
fill(0);
textSize(50);
text("Screen Height : " + str(height), 100, 100);
text("Screen Width : " + str(width), 100, 200);


happy = (n) ->
  seen = {}
  while true
    n = sum_digit_squares(n)
    return true if n == 1
    return false if seen[n]
    seen[n] = true

sum_digit_squares = (n) ->
  sum = 0
  for c in n.toString()
    d = parseInt(c)
    sum += d*d
  sum

i = 1
cnt = 0
while cnt < 8
  if happy(i)
    console.log i
    cnt += 1
  i += 1


(defun sqr (n)
  (* n n))

(defun sum-of-sqr-dgts (n)
  (loop for i = n then (floor i 10)
        while (plusp i)
        sum (sqr (mod i 10))))

(defun happy-p (n &optional cache)
  (or (= n 1)
      (unless (find n cache)
        (happy-p (sum-of-sqr-dgts n)
                 (cons n cache)))))

(defun happys (&aux (happys 0))
  (loop for i from 1
        while (< happys 8)
        when (happy-p i)
        collect i and do (incf happys)))

(print (happys))


set ! H
set ! E
set ! L
set ! L
set ! O
set ! 32
set ! W
set ! O
set ! R
set ! L
set ! D
set ! 33


(* Preamble -- some math, and an "angle" type which might be part of a common library. *)
let pi = 4. *. atan 1.
let radians_of_degrees = ( *. ) (pi /. 180.)
let haversin theta = 0.5 *. (1. -. cos theta)

(* The angle type can track radians or degrees, which I'll use for automatic conversion. *)
type angle = Deg of float | Rad of float
let as_radians = function
  | Deg d -> radians_of_degrees d
  | Rad r -> r

(* Demonstrating use of a module, and record type. *)
module LatLong = struct
  type t = { lat: float; lng: float }
  let of_angles lat lng = { lat = as_radians lat; lng = as_radians lng }
  let sub a b = { lat = a.lat-.b.lat; lng = a.lng-.b.lng }

  let dist radius a b =
    let d = sub b a in
    let h = haversin d.lat +. haversin d.lng *. cos a.lat *. cos b.lat in
    2. *. radius *. asin (sqrt h)
end

(* Now we can use the LatLong module to construct coordinates and calculate
 * great-circle distances.
 * NOTE radius and resulting distance are in the same measure, and units could
 * be tracked for this too... but who uses miles? ;) *)
let earth_dist = LatLong.dist 6372.8
and bna = LatLong.of_angles (Deg 36.12) (Deg (-86.67))
and lax = LatLong.of_angles (Deg 33.94) (Deg (-118.4))
in
earth_dist bna lax;;


import: math

: haversine(lat1, lon1, lat2, lon2)
| lat lon |

   lat2 lat1 - asRadian ->lat
   lon2 lon1 - asRadian ->lon

   lon 2 / sin sq lat1 asRadian cos * lat2 asRadian cos *
   lat 2 / sin sq + sqrt asin 2 * 6372.8 * ;

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


If OpenWindow(0, 0, 0, 5, 5, "", #PB_Window_Maximize + #PB_Window_Invisible)
  maxX = WindowWidth(0)
  maxY = WindowHeight(0)
  CloseWindow(0)
  MessageRequester("Result", "Maximum Window Width: " + Str(maxX) + ", Maximum Window Height: " + Str(maxY))
EndIf


#!/usr/bin/env python3

import tkinter as tk # import the module.

root = tk.Tk() # Create an instance of the class.
root.state('zoomed') # Maximized the window.
root.update_idletasks() # Update the display.
tk.Label(root, text=(str(root.winfo_width())+ " x " +str(root.winfo_height())),
         font=("Helvetica", 25)).pack() # add a label and set the size to text.
root.mainloop()


#lang racket/gui
(define-values [W H]
  (let ([f (new frame% [label "test"])])
    (begin0 (send* f (maximize #t) (show #t) (get-client-size))
      (send f show #f))))
(printf "~ax~a\n" W H)


use X11::libxdo;

my $xdo = Xdo.new;

my ($dw, $dh) = $xdo.get-desktop-dimensions( 0 );

say "Desktop viewport dimensions: (maximum-fullscreen size) $dw x $dh";


load "guilib.ring"
new qApp {
         win1 = new qWidget() {
                new qPushButton(win1) {
                    resize(200,200)
                    settext("Info")
                    setclickevent(' win1{ setwindowtitle("Width: " +  width() + " Height : " +  height() ) }')
                }
                showMaximized()}
                exec()
                }


include "cowgol.coh";

sub sumDigitSquare(n: uint8): (s: uint8) is
    s := 0;
    while n != 0 loop
        var d := n % 10;
        s := s + d * d;
        n := n / 10;
    end loop;
end sub;

sub isHappy(n: uint8): (h: uint8) is
    var seen: uint8[256];
    MemZero(&seen[0], @bytesof seen);

    while seen[n] == 0 loop
        seen[n] := 1;
        n := sumDigitSquare(n);
    end loop;

    if n == 1 then
        h := 1;
    else
        h := 0;
    end if;
end sub;

var n: uint8 := 1;
var seen: uint8 := 0;

while seen < 8 loop
    if isHappy(n) != 0 then
        print_i8(n);
        print_nl();
        seen := seen + 1;
    end if;
    n := n + 1;
end loop;


def happy?(n)
  past = [] of Int32 | Int64
  until n == 1
    sum = 0; while n > 0; sum += (n % 10) ** 2; n //= 10 end
    return false if past.includes? (n = sum)
    past << n
  end
  true
end

i = count = 0
until count == 8; (puts i; count += 1) if happy?(i += 1) end
puts
(99999999999900..99999999999999).each { |i| puts i if happy?(i) }


/*REXX pgm calculates distance between Nashville & Los Angles airports. */
say " Nashville:  north 36º  7.2', west  86º 40.2'   =   36.12º,  -86.67º"
say "Los Angles:  north 33º 56.4', west 118º 24.0'   =   33.94º, -118.40º"
say
dist=surfaceDistance(36.12,  -86.67,  33.94,  -118.4)
kdist=format(dist/1       ,,2)         /*show 2 digs past decimal point.*/
mdist=format(dist/1.609344,,2)         /*  "  "   "    "     "      "   */
ndist=format(mdist*5280/6076.1,,2)     /*  "  "   "    "     "      "   */
say ' distance between=  '  kdist  " kilometers,"
say '               or   '  mdist  " statute miles,"
say '               or   '  ndist  " nautical or air miles."
exit                                   /*stick a fork in it, we're done.*/
/*----------------------------------SURFACEDISTANCE subroutine----------*/
surfaceDistance: arg th1,ph1,th2,ph2   /*use haversine formula for dist.*/
  radius = 6372.8                      /*earth's mean radius in km      */
  ph1 = ph1-ph2
  x = cos(ph1) * cos(th1) - cos(th2)
  y = sin(ph1) * cos(th1)
  z = sin(th1) - sin(th2)
  return radius * 2 * aSin(sqrt(x**2+y**2+z**2)/2 )

cos: Return RxCalcCos(arg(1))
sin: Return RxCalcSin(arg(1))
asin: Return RxCalcArcSin(arg(1),,'R')
sqrt: Return RxCalcSqrt(arg(1))
::requires rxMath library


dist(th1, th2, ph)={
  my(v=[cos(ph)*cos(th1)-cos(th2),sin(ph)*cos(th1),sin(th1)-sin(th2)]);
  asin(sqrt(norml2(v))/2)
};
distEarth(th1, ph1, th2, ph2)={
  my(d=12742, deg=Pi/180); \\ Authalic diameter of the Earth
  d*dist(th1*deg, th2*deg, (ph1-ph2)*deg)
};
distEarth(36.12, -86.67, 33.94, -118.4)


html "<INPUT TYPE='HIDDEN' id='winHigh' name='winHigh' VALUE='";winHigh;"'></input>"
html "<INPUT TYPE='HIDDEN' id='winWide' name='winWide' VALUE='";winWide;"'></input>"

html "<script>
<!--

function winSize()
{
var myWide	= 0, myHigh = 0;
if( typeof( window.innerWidth ) == 'number' ) {
//Non-IE
myWide		= window.innerWidth;
myHigh		= window.innerHeight;
} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
//IE 6+ in 'standards compliant mode'
myWide		= document.documentElement.clientWidth;
myHigh		= document.documentElement.clientHeight;
} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
//IE 4 compatible
myWide		= document.body.clientWidth;
myHigh		= document.body.clientHeight;
}
// window.alert( 'Width = ' + myWide + ' Height = ' + myHigh );
document.getElementById('winHigh').value = myHigh;
document.getElementById('winWide').value = myWide;
}

window.onresize  = function()
{
var x = winSize();
}
var x = winSize();
//--></script>
"


import java.awt.{Dimension, Insets, Toolkit}

import javax.swing.JFrame

class MaxWindowDims() extends JFrame {
  val toolkit: Toolkit = Toolkit.getDefaultToolkit
  val (insets0, screenSize) = (toolkit.getScreenInsets(getGraphicsConfiguration),  toolkit.getScreenSize)

  println("Physical screen size: " + screenSize)
  System.out.println("Insets: " + insets0)
  screenSize.width -= (insets0.left + insets0.right)
  screenSize.height -= (insets0.top + insets0.bottom)
  System.out.println("Max available: " + screenSize)
}

object MaxWindowDims {
  def main(args: Array[String]): Unit = {
    new MaxWindowDims
  }
}


require('Tk')

func max_window_size() -> (Number, Number) {
    %s'MainWindow'.new.maxsize;
}

var (width, height) = max_window_size();
say (width, 'x', height);


package require Tk
proc maxSize {} {
    # Need a dummy window; max window can be changed by scripts
    set top .__defaultMaxSize__
    if {![winfo exists $top]} {
        toplevel $top
        wm withdraw $top
    }
    # Default max size of window is value we want
    return [wm maxsize $top]
}


TYPE syswindowstru
  screenheight AS INTEGER
  screenwidth AS INTEGER
  maxheight AS INTEGER
  maxwidth AS INTEGER
END TYPE

DIM syswindow AS syswindowstru

' Determine the height and width of the screen

syswindow.screenwidth = Screen.Width / Screen.TwipsPerPixelX
syswindow.screenheight=Screen.Height / Screen.TwipsPerPixelY

' Make adjustments for window decorations and menubars


bool isHappy(int n) pure nothrow {
    int[int] past;

    while (true) {
        int total = 0;
        while (n > 0) {
            total += (n % 10) ^^ 2;
            n /= 10;
        }
        if (total == 1)
            return true;
        if (total in past)
            return false;
        n = total;
        past[total] = 0;
    }
}

void main() {
    import std.stdio, std.algorithm, std.range;

    int.max.iota.filter!isHappy.take(8).writeln;
}


main() {
  HashMap<int,bool> happy=new HashMap<int,bool>();
  happy[1]=true;

  int count=0;
  int i=0;

  while(count<8) {
    if(happy[i]==null) {
      int j=i;
      Set<int> sequence=new Set<int>();
      while(happy[j]==null && !sequence.contains(j)) {
        sequence.add(j);
        int sum=0;
        int val=j;
        while(val>0) {
          int digit=val%10;
          sum+=digit*digit;
          val=(val/10).toInt();
        }
        j=sum;
      }
      bool sequenceHappy=happy[j];
      Iterator<int> it=sequence.iterator();
      while(it.hasNext()) {
        happy[it.next()]=sequenceHappy;
      }
    }
    if(happy[i]) {
      print(i);
      count++;
    }
    i++;
  }
}


function main()
end function "Hello world!{d}{a}"


Program HaversineDemo(output);

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);
    haversineDist := arcsin(sqrt(dx**2 + dy**2 + dz**2) / 2) * diameter;
  end;

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


use ntheory qw/Pi/;

sub asin { my $x = shift; atan2($x, sqrt(1-$x*$x)); }

sub surfacedist {
  my($lat1, $lon1, $lat2, $lon2) = @_;
  my $radius = 6372.8;
  my $radians = Pi() / 180;;
  my $dlat = ($lat2 - $lat1) * $radians;
  my $dlon = ($lon2 - $lon1) * $radians;
  $lat1 *= $radians;
  $lat2 *= $radians;
  my $a = sin($dlat/2)**2 + cos($lat1) * cos($lat2) * sin($dlon/2)**2;
  my $c = 2 * asin(sqrt($a));
  return $radius * $c;
}
my @BNA = (36.12, -86.67);
my @LAX = (33.94, -118.4);
printf "Distance: %.3f km\n", surfacedist(@BNA, @LAX);


Imports System.Drawing
Imports System.Windows.Forms

Module Program
    Sub Main()
        Dim bounds As Rectangle = Screen.PrimaryScreen.Bounds
        Console.WriteLine($"Primary screen bounds:  {bounds.Width}x{bounds.Height}")

        Dim workingArea As Rectangle = Screen.PrimaryScreen.WorkingArea
        Console.WriteLine($"Primary screen working area:  {workingArea.Width}x{workingArea.Height}")
    End Sub
End Module


import "input" for Keyboard
import "dome" for Window, Process
import "graphics" for Canvas, Color

class Game {
    static init() {
        Canvas.print("Maximize the window and press 'm'", 0, 0, Color.white)
    }

    static update() {
        if (Keyboard.isKeyDown("m") ) {
            System.print("Maximum window dimensions are %(Window.width) x %(Window.height)")
            Process.exit(0)
        }
    }

    static draw(alpha) {}
}


int A;
[A:= GetFB;
Text(0, "Width =  "); IntOut(0, A(0));  CrLf(0);
Text(0, "Height = "); IntOut(0, A(1));  CrLf(0);
]


[lcI~rscd*+lc0<H]sH
[0rsclHxd4<h]sh
[lIp]s_
0sI[lI1+dsIlhx2>_z8>s]dssx


$ happy_1 = 1
$ found = 0
$ i = 1
$ loop1:
$  n = i
$  seen_list = ","
$  loop2:
$   if f$type( happy_'n ) .nes. "" then $ goto happy
$   if f$type( unhappy_'n ) .nes. "" then $ goto unhappy
$   if f$locate( "," + n + ",", seen_list ) .eq. f$length( seen_list )
$   then
$    seen_list = seen_list + f$string( n ) + ","
$   else
$    goto unhappy
$   endif
$   ns = f$string( n )
$   nl = f$length( ns )
$   j = 0
$   sumsq = 0
$   loop3:
$    digit = f$integer( f$extract( j, 1, ns ))
$    sumsq = sumsq + digit * digit
$    j = j + 1
$    if j .lt. nl then $ goto loop3
$    n = sumsq
$   goto loop2
$  unhappy:
$  j = 1
$  loop4:
$   x = f$element( j, ",", seen_list )
$   if x .eqs. "" then $ goto continue
$   unhappy_'x = 1
$   j = j + 1
$   goto loop4
$  happy:
$  found = found + 1
$  found_'found = i
$  if found .eq. 8 then $ goto done
$  j = 1
$  loop5:
$   x = f$element( j, ",", seen_list )
$   if x .eqs. "" then $ goto continue
$   happy_'x = 1
$   j = j + 1
$   goto loop5
$  continue:
$  i = i + 1
$  goto loop1
$ done:
$ show symbol found*


BEGIN
   OUTTEXT("Hello world!");
   OUTIMAGE
END


requires "sio";

public fn singmain(argv [*]string) i32
{
    sio.print("hello world !\r\n");
    return(0);
}


define main

% Sisal doesn't yet have a string built-in.
% Let's define one as an array of characters.

type string = array[character];

function main(returns string)
  "Hello world!"
end function


function haversine(atom lat1, long1, lat2, long2)
    constant MER = 6371, -- mean earth radius(km)
             DEG_TO_RAD = PI/180
    lat1 *= DEG_TO_RAD
    lat2 *= DEG_TO_RAD
    long1 *= DEG_TO_RAD
    long2 *= DEG_TO_RAD
    return MER*arccos(sin(lat1)*sin(lat2)+cos(lat1)*cos(lat2)*cos(long2-long1))
end function

atom d = haversine(36.12,-86.67,33.94,-118.4)
printf(1,"Distance is %f km (%f miles)\n",{d,d/1.609344})


class POI {
    private $latitude;
    private $longitude;

    public function __construct($latitude, $longitude) {
        $this->latitude = deg2rad($latitude);
        $this->longitude = deg2rad($longitude);
    }

    public function getLatitude() {
        return $this->latitude;
    }

    public function getLongitude() {
        return $this->longitude;
    }

    public function getDistanceInMetersTo(POI $other) {
        $radiusOfEarth = 6371; // Earth's radius in kilometers.

        $diffLatitude = $other->getLatitude() - $this->latitude;
        $diffLongitude = $other->getLongitude() - $this->longitude;

        $a = sin($diffLatitude / 2) ** 2 +
             cos($this->latitude) *
             cos($other->getLatitude()) *
             sin($diffLongitude / 2) ** 2;

        $c = 2 * asin(sqrt($a));
        $distance = $radiusOfEarth * $c;

        return $distance;
    }
}


program Happy_numbers;

{$APPTYPE CONSOLE}

uses
  System.SysUtils,
  Boost.Int;

type
  TIntegerDynArray = TArray<Integer>;

  TIntHelper = record helper for Integer
    function IsHappy: Boolean;
    procedure Next;
  end;

{ TIntHelper }

function TIntHelper.IsHappy: Boolean;
var
  cache: TIntegerDynArray;
  sum, n: integer;
begin
  n := self;
  repeat
    sum := 0;
    while n > 0 do
    begin
      sum := sum + (n mod 10) * (n mod 10);
      n := n div 10;
    end;
    if sum = 1 then
      exit(True);

    if cache.Has(sum) then
      exit(False);
    n := sum;
    cache.Add(sum);
  until false;
end;

procedure TIntHelper.Next;
begin
  inc(self);
end;

var
  count, n: integer;

begin
  n := 1;
  count := 0;
  while count < 8 do
  begin
    if n.IsHappy then
    begin
      count.Next;
      write(n, ' ');
    end;
    n.Next;
  end;
  writeln;
  readln;
end.


test: procedure options (main); /* 12 January 2014.  Derived from Fortran version */
   declare d float;

   d = haversine(36.12, -86.67, 33.94, -118.40);  /* BNA to LAX */
   put edit ( 'distance: ', d, ' km') (A, F(10,3)); /* distance: 2887.2600 km */

degrees_to_radians: procedure (degree) returns (float);
   declare degree float nonassignable;
   declare pi float (15) initial ( (4*atan(1.0d0)) );

   return ( degree*pi/180 );
end degrees_to_radians;

haversine: procedure (deglat1, deglon1, deglat2, deglon2) returns (float);
   declare (deglat1, deglon1, deglat2, deglon2) float nonassignable;
   declare (a, c, dlat, dlon, lat1, lat2) float;
   declare radius float value (6372.8);

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

end test;


Add-Type -AssemblyName System.Device

$BNA = New-Object System.Device.Location.GeoCoordinate 36.12, -86.67
$LAX = New-Object System.Device.Location.GeoCoordinate 33.94, -118.40

$BNA.GetDistanceTo( $LAX ) / 1000


proc nonrec dsumsq(byte n) byte:
    byte r, d;
    r := 0;
    while n~=0 do
        d := n % 10;
        n := n / 10;
        r := r + d * d
    od;
    r
corp

proc nonrec happy(byte n) bool:
    [256] bool seen;
    byte i;
    for i from 0 upto 255 do seen[i] := false od;
    while not seen[n] do
        seen[n] := true;
        n := dsumsq(n)
    od;
    seen[1]
corp

proc nonrec main() void:
    byte n, seen;
    n := 1;
    seen := 0;
    while seen < 8 do
        if happy(n) then
            writeln(n:3);
            seen := seen + 1
        fi;
        n := n + 1
    od
corp


function IsHappy(n : Integer) : Boolean;
var
   cache : array of Integer;
   sum : Integer;
begin
   while True do begin
      sum := 0;
      while n>0 do begin
         sum += Sqr(n mod 10);
         n := n div 10;
      end;
      if sum = 1 then
         Exit(True);
      if sum in cache then
         Exit(False);
      n := sum;
      cache.Add(sum);
   end;
end;

var n := 8;
var i : Integer;

while n>0 do begin
   Inc(i);
   if IsHappy(i) then begin
      PrintLn(i);
      Dec(n);
   end;
end;


#DIA=2*6372.8

Procedure.d Haversine(th1.d,ph1.d,th2.d,ph2.d)
  Define dx.d,
         dy.d,
         dz.d

  ph1=Radian(ph1-ph2)
  th1=Radian(th1)
  th2=Radian(th2)

  dz=Sin(th1)-Sin(th2)
  dx=Cos(ph1)*Cos(th1)-Cos(th2)
  dy=Sin(ph1)*Cos(th1)
  ProcedureReturn ASin(Sqr(Pow(dx,2)+Pow(dy,2)+Pow(dz,2))/2)*#DIA
EndProcedure

OpenConsole("Haversine distance")
Print("Haversine distance: ")
Print(StrD(Haversine(36.12,-86.67,33.94,-118.4),7)+" km.")
Input()


func happy(n) {
    var m = []
    while n > 1 {
        m.Add(n)
        var x = n
        n = 0
        while x > 0 {
            var d = x % 10
            n += d * d
            x /= 10
        }
        if m.IndexOf(n) != -1 {
            return false
        }
    }
    return true
}

var (n, found) = (1, 0)
while found < 8 {
    if happy(n) {
        print("\(n) ", terminator: "")
        found += 1
    }
    n += 1
}
print()


next-num:
	0
	while over:
		over
		* dup % swap 10
		+
		swap floor / swap 10 swap
	drop swap

is-happy happies n:
	if has happies n:
		return happies! n
	local :seq set{ n }
	n
	while /= 1 dup:
		next-num
		if has seq dup:
			drop
			set-to happies n false
			return false
		if has happies dup:
			set-to happies n dup happies!
			return
		set-to seq over true
	drop
	set-to happies n true
	true

local :h {}
1 0
while > 8 over:
	if is-happy h dup:
		!print( "A happy number: " over )
		swap ++ swap
	++
drop
drop


extern print

dv Msg Goodbye,World!

mov eax Msg
push
call print
pop


	.section	".text"
	.global		_start
_start:
	mov	4,%g1			! 4 is SYS_write
	mov	1,%o0			! 1 is stdout
	set	.msg,%o1		! pointer to buffer
	mov	(.msgend-.msg),%o2	! length
	ta	8

	mov	1,%g1			! 1 is SYS_exit
	clr	%o0			! return status is 0
	ta	8

.msg:
	.ascii	"Hello world!\n"
.msgend:


from math import radians, sin, cos, sqrt, asin

def haversine(lat1, lon1, lat2, lon2):
    R = 6372.8  # Earth radius in kilometers

    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 * asin(sqrt(a))

    return R * c

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


SCREEN _NEWIMAGE(800, 100, 32)

'*** Units: K=kilometers  M=miles  N=nautical miles
DIM UNIT AS STRING
DIM Distance AS STRING
DIM Result AS DOUBLE
DIM ANSWER AS DOUBLE

'*** Change the To/From Latittude/Logitudes for your run

'*** LAT/LON for Nashville International Airport (BNA)
lat1 = 36.12
Lon1 = -86.67

'*** LAT/LONG for Los Angeles International Airport (LAX)
Lat2 = 33.94
Lon2 = -118.40

'*** Initialize Values
UNIT = "K"
Distance = ""
'Radius = 6378.137
Radius = 6372.8

'*** Calculate distance using Haversine Function
lat1 = (lat1 * _PI / 180)
Lon1 = (Lon1 * _PI / 180)
Lat2 = (Lat2 * _PI / 180)
Lon2 = (Lon2 * _PI / 180)
DLon = Lon1 - Lon2

ANSWER = _ACOS(SIN(lat1) * SIN(Lat2) + COS(lat1) * COS(Lat2) * COS(DLon)) * Radius

'*** Adjust Answer based on Distance Unit (kilometers, miles, nautical miles)
SELECT CASE UNIT
       CASE "M"
            Result = ANSWER * 0.621371192
            Distance = "miles"
       CASE "N"
            Result = ANSWER * 0.539956803
            Distance = "nautical miles"
       CASE ELSE
            Result = ANSWER
            Distance = "kilometers"
END SELECT

'*** Change PRINT statement with your labels for FROM/TO locations
PRINT "The distance from Nashville International to Los Angeles International in "; Distance;
PRINT USING " is: ##,###.##"; Result;
PRINT "."

END


dms_to_rad <- function(d, m, s) (d + m / 60 + s / 3600) * pi / 180

# Volumetric mean radius is 6371 km, see http://nssdc.gsfc.nasa.gov/planetary/factsheet/earthfact.html
# The diameter is thus 12742 km

great_circle_distance <- function(lat1, long1, lat2, long2) {
   a <- sin(0.5 * (lat2 - lat1))
   b <- sin(0.5 * (long2 - long1))
   12742 * asin(sqrt(a * a + cos(lat1) * cos(lat2) * b * b))
}

# Coordinates are found here:
#     http://www.airport-data.com/airport/BNA/
#     http://www.airport-data.com/airport/LAX/

great_circle_distance(
   dms_to_rad(36,  7, 28.10), dms_to_rad( 86, 40, 41.50),   # Nashville International Airport (BNA)
   dms_to_rad(33, 56, 32.98), dms_to_rad(118, 24, 29.05))  # Los Angeles International Airport (LAX)

# Output:  2886.327


def isHappyNumber(var x :int) {
  var seen := [].asSet()
  while (!seen.contains(x)) {
    seen with= x
    var sum := 0
    while (x > 0) {
      sum += (x % 10) ** 2
      x //= 10
    }
    x := sum
    if (x == 1) { return true }
  }
  return false
}

var count := 0
for x ? (isHappyNumber(x)) in (int >= 1) {
  println(x)
  if ((count += 1) >= 8) { break }
}


class
	APPLICATION

create
	make

feature {NONE} -- Initialization

	make
			-- Run application.
		local
			l_val: INTEGER
		do
			from
				l_val := 1
			until
				l_val > 100
			loop
				if is_happy_number (l_val) then
					print (l_val.out)
					print ("%N")
				end
				l_val := l_val + 1
			end
		end

feature -- Happy number

	is_happy_number (a_number: INTEGER): BOOLEAN
			-- Is `a_number' a happy number?
		require
			positive_number: a_number > 0
		local
			l_number: INTEGER
			l_set: ARRAYED_SET [INTEGER]
		do
			from
				l_number := a_number
				create l_set.make (10)
			until
				l_number = 1 or l_set.has (l_number)
			loop
				l_set.put (l_number)
				l_number := square_sum_of_digits (l_number)
			end

			Result := (l_number = 1)
		end

feature{NONE} -- Implementation

	square_sum_of_digits (a_number: INTEGER): INTEGER
			-- Sum of the sqares of digits of `a_number'.
		require
			positive_number: a_number > 0
		local
			l_number, l_digit: INTEGER
		do
			from
				l_number := a_number
			until
				l_number = 0
			loop
				l_digit := l_number \\ 10
				Result := Result + l_digit * l_digit
				l_number := l_number // 10
			end
		end

end


#lang racket
(require math)
(define earth-radius 6371)

(define (distance lat1 long1 lat2 long2)
  (define (h a b) (sqr (sin (/ (- b a) 2))))
  (* 2 earth-radius
     (asin (sqrt (+ (h lat1 lat2)
                    (* (cos lat1) (cos lat2) (h long1 long2)))))))

(define (deg-to-rad d m s)
  (* (/ pi 180) (+ d (/ m 60) (/ s 3600))))

(distance (deg-to-rad 36  7.2 0) (deg-to-rad  86 40.2 0)
          (deg-to-rad 33 56.4 0) (deg-to-rad 118 24.0 0))


class EarthPoint {
        has $.lat; # latitude
        has $.lon; # longitude

        has $earth_radius = 6371; # mean earth radius
        has $radian_ratio = pi / 180;

        # accessors for radians
        method latR { $.lat * $radian_ratio }
        method lonR { $.lon * $radian_ratio }

        method haversine-dist(EarthPoint $p) {

                my EarthPoint $arc .= new(
                        lat => $!lat - $p.lat,
                        lon => $!lon - $p.lon );

                my $a = sin($arc.latR/2) ** 2 + sin($arc.lonR/2) ** 2
                        * cos($.latR) * cos($p.latR);
                my $c = 2 * asin( sqrt($a) );

                return $earth_radius * $c;
        }
}

my EarthPoint $BNA .= new(lat => 36.12, lon => -86.67);
my EarthPoint $LAX .= new(lat => 33.94, lon => -118.4);

say $BNA.haversine-dist($LAX); # 2886.44444099822


import extensions;
import system'collections;
import system'routines;

isHappy(int n)
{
    auto cache := new List<int>(5);
    int sum := 0;
    int num := n;
    while (num != 1)
    {
        if (cache.indexOfElement:num != -1)
        {
            ^ false
        };
        cache.append(num);
        while (num != 0)
        {
            int digit := num.mod:10;
            sum += (digit*digit);
            num /= 10
        };
        num := sum;
        sum := 0
    };

    ^ true
}

public program()
{
    auto happynums  := new List<int>(8);
    int num := 1;
    while (happynums.Length < 8)
    {
        if (isHappy(num))
        {
            happynums.append(num)
        };

        num += 1
    };
    console.printLine("First 8 happy numbers: ", happynums.asEnumerable())
}


defmodule Happy do
  def task(num) do
    Process.put({:happy, 1}, true)
    Stream.iterate(1, &(&1+1))
    |> Stream.filter(fn n -> happy?(n) end)
    |> Enum.take(num)
  end

  defp happy?(n) do
    sum = square_sum(n, 0)
    val = Process.get({:happy, sum})
    if val == nil do
      Process.put({:happy, sum}, false)
      val = happy?(sum)
      Process.put({:happy, sum}, val)
    end
    val
  end

  defp square_sum(0, sum), do: sum
  defp square_sum(n, sum) do
    r = rem(n, 10)
    square_sum(div(n, 10), sum + r*r)
  end
end

IO.inspect Happy.task(8)


SELECT 'Hello world!' AS text FROM sysibm.sysdummy1;


define PI
  -1 acos

define toRadians use $degree
  $degree PI * 180 /

define haversine use $lat1, $lon1, $lat2, $lon2
  6372.8 as $R
  # In kilometers
  $lat2 $lat1 - toRadians   as $dLat
  $lon2 $lon1 - toRadians   as $dLon
  $lat1 toRadians  as $lat1
  $lat2 toRadians  as $lat2

  $dLat 2 /  sin
  $dLat 2 /  sin *
  $dLon 2 /  sin
  $dLon 2 /  sin *
  $lat1 cos *
  $lat2 cos * +        as $a
  $a sqrt  asin  2 *   as $c
  $R $c *
}

-118.40 33.94 -86.67 36.12 haversine "haversine: %.15g\n" print


/*REXX program  calculates  the  distance between  Nashville  and  Los Angles  airports.*/
call pi;    numeric digits length(pi) % 2        /*use half of PI dec. digits for output*/
say "       Nashville:  north 36º  7.2', west  86º 40.2'   =   36.12º,  -86.67º"
say "      Los Angles:  north 33º 56.4', west 118º 24.0'   =   33.94º, -118.40º"
@using_radius= 'using the mean radius of the earth as '            /*a literal for  SAY.*/
radii.=.;    radii.1=6372.8;     radii.2=6371    /*mean radii of the earth in kilometers*/
say;                         m=1/0.621371192237  /*M:   one statute mile  in      "     */
    do radius=1  while radii.radius\==.          /*calc. distance using specific radii. */
    d= surfaceDist( 36.12,    -86.67,    33.94,   -118.4,    radii.radius);         say
    say center(@using_radius     radii.radius         ' kilometers', 75, '─')
    say ' Distance between:  '   format(d/1            ,,2)    " kilometers,"
    say '               or   '   format(d/m            ,,2)    " statute miles,"
    say '               or   '   format(d/m*5280/6076.1,,2)    " nautical (or air miles)."
    end   /*radius*/                             /*show──┘   2 dec. digs past dec. point*/
exit                                             /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
surfaceDist: parse arg th1,ph1,th2,ph2,r         /*use  haversine  formula for distance.*/
      numeric digits digits() * 2                /*double number of decimal digits used.*/
              ph1 = d2r(ph1 - ph2)               /*convert degrees ──► radians & reduce.*/
              th1 = d2r(th1)                     /*   "       "           "    "    "   */
              th2 = d2r(th2)                     /*   "       "           "    "    "   */
      cosTH1= cos(th1)                           /*compute a shortcut (it's used twice).*/
                x = cos(ph1) * cosTH1 - cos(th2) /*   "    X   coordinate.              */
                y = sin(ph1) * cosTH1            /*   "    Y       "                    */
                z = sin(th1)          - sin(th2) /*   "    Z       "                    */
      return Asin(sqrt(x*x + y*y + z*z)*.5) *r*2 /*compute the arcsin and return value. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
Acos: return pi() * .5   -   aSin( arg(1) )      /*calculate the ArcCos of an argument. */
d2d:  return arg(1)               //  360        /*normalize degrees to a  unit circle. */
d2r:  return r2r(  arg(1) * pi()  /   180)       /*normalize and convert deg ──► radians*/
r2d:  return d2d( (arg(1) * 180   /   pi()))     /*normalize and convert rad ──► degrees*/
r2r:  return arg(1)               // (pi() * 2)  /*normalize radians to a  unit circle. */
pi:   pi= 3.141592653589793238462643383279502884197169399375105820975;           return pi
/*──────────────────────────────────────────────────────────────────────────────────────*/
Asin: procedure; parse arg x 1 z 1 o 1 p;     a= abs(x);               aa= a * a
      if a >= sqrt(2) * .5  then return sign(x) * Acos( sqrt(1 - aa) )
        do j=2  by 2  until p=z;    p= z;     o= o * aa * (j-1) / j;   z= z  +  o / (j+1)
        end   /*j*/;                return z      /* [↑]  compute until no more noise.  */
/*──────────────────────────────────────────────────────────────────────────────────────*/
cos:  procedure; parse arg x;       x= r2r(x);       a= abs(x);              Hpi= pi * .5
      numeric fuzz min(6, digits() - 3)  ;     if a=pi    then return -1
      if a=Hpi | a=Hpi*3  then return 0  ;     if a=pi/3  then return .5
      if a=pi* 2/3        then return -.5;     q= x*x;    p= 1;     z= 1;     _= 1
        do k=2  by 2;  _= -_*q / (k*(k-1)); z= z+_; if z=p  then leave; p=z; end; return z
/*──────────────────────────────────────────────────────────────────────────────────────*/
sin:  procedure; parse arg x;  x= r2r(x);                numeric fuzz min(5, digits() - 3)
      if abs(x)=pi  then  return 0;            q= x*x;    p= x;     z= x;      _= x
        do k=2  by 2; _= -_*q / (k*(k+1));  z= z+_; if z=p  then leave; p=z; end; return z
/*──────────────────────────────────────────────────────────────────────────────────────*/
sqrt: procedure; parse arg x; if x=0  then return 0; d=digits(); m.=9; numeric form; h=d+6
      numeric digits;  parse value format(x,2,1,,0) 'E0' with g "E" _ .;  g=g * .5'e'_ % 2
        do j=0  while h>9;      m.j= h;              h= h%2 + 1;    end  /*j*/
        do k=j+5  to 0  by -1;  numeric digits m.k;  g= (g+x/g)*.5; end  /*k*/;   return g


-module(tasks).
-export([main/0]).
-import(lists, [map/2, member/2, sort/1, sum/1]).

is_happy(X, XS) ->
    if
	X == 1 ->
	    true;
	X < 1 ->
	    false;
	true ->
	    case member(X, XS) of
		true -> false;
		false ->
		    is_happy(sum(map(fun(Z) -> Z*Z end,
				     [Y - 48 || Y <- integer_to_list(X)])),
			     [X|XS])
	    end
    end.

main(X, XS) ->
    if
	length(XS) == 8 ->
	    io:format("8 Happy Numbers: ~w~n", [sort(XS)]);
	true ->
	    case is_happy(X, []) of
		true -> main(X + 1, [X|XS]);
		false -> main(X + 1, XS)
	    end
    end.
main() ->
    main(0, []).


include Math

Radius = 6371  # rough radius of the Earth, in kilometers

def spherical_distance(start_coords, end_coords)
  lat1, long1 = deg2rad *start_coords
  lat2, long2 = deg2rad *end_coords
  2 * Radius * asin(sqrt(sin((lat2-lat1)/2)**2 + cos(lat1) * cos(lat2) * sin((long2 - long1)/2)**2))
end

def deg2rad(lat, long)
  [lat * PI / 180, long * PI / 180]
end

bna = [36.12, -86.67]
lax = [33.94, -118.4]

puts "%.1f" % spherical_distance(bna, lax)


    D2R = atn(1)/45
    diam  = 2 * 6372.8
Lg1m2  = ((-86.67)-(-118.4)) * D2R
Lt1    = 36.12 * D2R ' degrees to rad
Lt2    = 33.94 * D2R
    dz    = sin(Lt1) - sin(Lt2)
    dx    = cos(Lg1m2) * cos(Lt1) - cos(Lt2)
    dy    = sin(Lg1m2) * cos(Lt1)
    hDist = asn((dx^2 + dy^2 + dz^2)^0.5 /2) * diam
print "Haversine distance: ";using("####.#############",hDist);" km."

 'Tips: ( 36 deg 7 min 12 sec ) = print 36+(7/60)+(12/3600).  Produces: 36.12 deg.
 '
 '      http://maps.google.com
 '      Search   36.12,-86.67
 '      Earth.
 '      Center the pin, zoom airport.
 '      Directions (destination).
 '      36.12.-86.66999
 '      Distance is 35.37 inches.


function is_happy(integer n)
    sequence seen
    integer k
    seen = {}
    while n > 1 do
        seen &= n
        k = 0
        while n > 0 do
            k += power(remainder(n,10),2)
            n = floor(n/10)
        end while
        n = k
        if find(n,seen) then
            return 0
        end if
    end while
    return 1
end function

integer n,count
n = 1
count = 0
while count < 8 do
    if is_happy(n) then
        ? n
        count += 1
    end if
    n += 1
end while


open System.Collections.Generic
open Microsoft.FSharp.Collections

let answer =
    let sqr x = x*x                                                 // Classic square definition
    let rec AddDigitSquare n =
        match n with
        | 0 -> 0                                                    // Sum of squares for 0 is 0
        | _ -> sqr(n % 10) + (AddDigitSquare (n / 10))              // otherwise add square of bottom digit to recursive call
    let dict = new Dictionary<int, bool>()                          // Dictionary to memoize values
    let IsHappy n =
        if dict.ContainsKey(n) then                                 // If we've already discovered it
            dict.[n]                                                // Return previously discovered value
        else
            let cycle = new HashSet<_>(HashIdentity.Structural)     // Set to keep cycle values in
            let rec isHappyLoop n =
                if cycle.Contains n then n = 1                      // If there's a loop, return true if it's 1
                else
                    cycle.Add n |> ignore                           // else add this value to the cycle
                    isHappyLoop (AddDigitSquare n)                  // and check the next number in the cycle
            let f = isHappyLoop n                                   // Keep track of whether we're happy or not
            cycle |> Seq.iter (fun i -> dict.[i] <- f)              // and apply it to all the values in the cycle
            f                                                       // Return the boolean

    1                                                               // Starting with 1,
    |> Seq.unfold (fun i -> Some (i, i + 1))                        // make an infinite sequence of consecutive integers
    |> Seq.filter IsHappy                                           // Keep only the happy ones
    |> Seq.truncate 8                                               // Stop when we've found 8
    |> Seq.iter (Printf.printf "%d\n")				    // Print results


use std::f64;

static R: f64 = 6372.8;

struct Point {
    lat: f64,
    lon: f64,
}

fn haversine(mut origin: Point, mut destination: Point) -> f64 {
    origin.lon -= destination.lon;
    origin.lon = origin.lon.to_radians();
    origin.lat = origin.lat.to_radians();
    destination.lat = destination.lat.to_radians();
    let dz: f64 = origin.lat.sin() - destination.lat.sin();
    let dx: f64 = origin.lon.cos() * origin.lat.cos() - destination.lat.cos();
    let dy: f64 = origin.lon.sin() * origin.lat.cos();
    ((dx * dx + dy * dy + dz * dz).sqrt() / 2.0).asin() * 2.0 * R
}

fn main() {
    let origin: Point = Point {
        lat: 36.12,
        lon:-86.67
    };
    let destination: Point = Point {
        lat: 33.94,
        lon:-118.4
    };
    let d: f64 = haversine(origin, destination);
    println!("Distance: {} km ({} mi)", d, d / 1.609344);
}


options minoperator;

%macro haver(lat1, long1, lat2, long2, type=D, dist=K);

	%if %upcase(&type) in (D DEG DEGREE DEGREES) %then %do;
		%let convert = constant('PI')/180;
		%end;
	%else %if %upcase(&type) in (R RAD RADIAN RADIANS) %then %do;
		%let convert = 1;
		%end;
	%else %do;
		%put ERROR - Enter RADIANS or DEGREES for type.;
		%goto exit;
		%end;

	%if %upcase(&dist) in (M MILE MILES) %then %do;
		%let distrat = 1.609344;
		%end;
	%else %if %upcase(&dist) in (K KM KILOMETER KILOMETERS) %then %do;
		%let distrat = 1;
		%end;
	%else %do;
		%put ERROR - Enter M on KM for dist;
		%goto exit;
		%end;

		data _null_;
			convert = &convert;
			lat1 = &lat1 * convert;
			lat2 = &lat2 * convert;
			long1 = &long1 * convert;
			long2 = &long2 * convert;

			diff1 = lat2 - lat1;
			diff2 = long2 - long1;

			part1 = sin(diff1/2)**2;
			part2 = cos(lat1)*cos(lat2);
			part3 = sin(diff2/2)**2;

			root = sqrt(part1 + part2*part3);

			dist = 2 * 6372.8 / &distrat * arsin(root);

			put "Distance is " dist "%upcase(&dist)";
		run;

	%exit:
%mend;

%haver(36.12, -86.67, 33.94, -118.40);


import math._

object Haversine {
   val R = 6372.8  //radius in km

   def haversine(lat1:Double, lon1:Double, lat2:Double, lon2:Double)={
      val dLat=(lat2 - lat1).toRadians
      val dLon=(lon2 - lon1).toRadians

      val a = pow(sin(dLat/2),2) + pow(sin(dLon/2),2) * cos(lat1.toRadians) * cos(lat2.toRadians)
      val c = 2 * asin(sqrt(a))
      R * c
   }

   def main(args: Array[String]): Unit = {
      println(haversine(36.12, -86.67, 33.94, -118.40))
  }
}


USING: combinators kernel make math sequences ;

: squares ( n -- s )
    0 [ over 0 > ] [ [ 10 /mod sq ] dip + ] while nip ;

: (happy?) ( n1 n2 -- ? )
    [ squares ] [ squares squares ] bi* {
        { [ dup 1 = ] [ 2drop t ] }
        { [ 2dup = ] [ 2drop f ] }
        [ (happy?) ]
    } cond ;

: happy? ( n -- ? )
    dup (happy?) ;

: happy-numbers ( n -- seq )
    [
        0 [ over 0 > ] [
            dup happy? [ dup , [ 1 - ] dip ] when 1 +
        ] while 2drop
    ] { } make ;


[$10/$10*@\-$*\]m:             {modulo squared and division}
[$m;![$9>][m;[email protected]@+\]#$*+]s:     {sum of squares}
[$0[1ø1>][1ø3+ø3ø=|\1-\]#\%]f: {look for duplicates}

{check happy number}
[
  $1[f;!~2ø1=~&][1+\s;[email protected]]#     {loop over sequence until 1 or duplicate}
  1ø1=                         {return value}
  \[$0=~][@%1-]#%              {drop sequence and counter}
]h:

0 1
"Happy numbers:"
[1ø8=~][h;![" "$.\1+\]?1+]#
%%


C = terralib.includec("stdio.h")

terra hello(argc : int, argv : &rawstring)
  C.printf("Hello world!\n")
  return 0
end


(define earth-radius 6371)
(define pi (acos -1))

(define (distance lat1 long1 lat2 long2)
(define (h a b) (expt (sin (/ (- b a) 2)) 2))
(* 2 earth-radius (asin (sqrt (+ (h lat1 lat2) (* (cos lat1) (cos lat2) (h long1 long2)))))))

(define (deg-to-rad d m s) (* (/ pi 180) (+ d (/ m 60) (/ s 3600))))

(distance (deg-to-rad 36  7.2 0) (deg-to-rad  86 40.2 0)
          (deg-to-rad 33 56.4 0) (deg-to-rad 118 24.0 0))
; 2886.444442837984


$ include "seed7_05.s7i";
  include "float.s7i";
  include "math.s7i";

const func float: greatCircleDistance (in float: latitude1, in float: longitude1,
    in float: latitude2, in float: longitude2) is func
  result
    var float: distance is 0.0;
  local
    const float: EarthRadius is 6372.8;  # Average great-elliptic or great-circle radius in kilometers
  begin
    distance := 2.0 * EarthRadius * asin(sqrt(sin(0.5 * (latitude2 - latitude1)) ** 2 +
                                              cos(latitude1) * cos(latitude2) *
                                              sin(0.5 * (longitude2 - longitude1)) ** 2));
  end func;

const func float: degToRad (in float: degrees) is
  return degrees * 0.017453292519943295769236907684886127;

const proc: main is func
  begin
    writeln("Distance in kilometers between BNA and LAX");
    writeln(greatCircleDistance(degToRad(36.12), degToRad(-86.67),  # Nashville International Airport (BNA)
                                degToRad(33.94), degToRad(-118.4))  # Los Angeles International Airport (LAX)
            digits 2);
  end func;


class Main
{
  static Bool isHappy (Int n)
  {
    Int[] record := [,]
    while (n != 1 && !record.contains(n))
    {
      record.add (n)
      // find sum of squares of digits
      newn := 0
      while (n > 0)
      {
        newn += (n.mod(10) * n.mod(10))
        n = n.div(10)
      }
      n = newn
    }
    return (n == 1)
  }

  public static Void main ()
  {
    i := 1
    count := 0
    while (count < 8)
    {
      if (isHappy (i))
      {
        echo (i)
        count += 1
      }
      i += 1
    }
  }
}


: next ( n -- n )
  0 swap begin 10 /mod >r  dup * +  r> ?dup 0= until ;

: cycle? ( n -- ? )
  here dup @ cells +
  begin dup here >
  while 2dup @ = if 2drop true exit then
        1 cells -
  repeat
  1 over +!  dup @ cells + !  false ;

: happy? ( n -- ? )
  0 here !  begin next dup cycle? until  1 = ;

: happy-numbers ( n -- )
  0 swap 0 do
    begin 1+ dup happy? until dup .
  loop drop ;

8 happy-numbers  \ 1 7 10 13 19 23 28 31


output "result" {
  value = "Hello world!"
}


class EarthPoint(lat, lon) {

    const earth_radius = 6371       # mean earth radius
    const radian_ratio = Num.pi/180

    # accessors for radians
    method latR { self.lat * radian_ratio }
    method lonR { self.lon * radian_ratio }

    method haversine_dist(EarthPoint p) {
        var arc = EarthPoint(
              self.lat - p.lat,
              self.lon - p.lon,
        )

        var a = Math.sum(
                  (arc.latR / 2).sin**2,
                  (arc.lonR / 2).sin**2 *
                    self.latR.cos * p.latR.cos
                )

        earth_radius * a.sqrt.asin * 2
    }
}

var BNA = EarthPoint.new(lat: 36.12, lon: -86.67)
var LAX = EarthPoint.new(lat: 33.94, lon: -118.4)

say BNA.haversine_dist(LAX)   #=> 2886.444442837983299747157823945746716...


'*** LAT/LONG for Nashville International Airport (BNA)
lat1=36.12
Lon1=-86.67

'*** LAT/LONG for Los Angeles International Airport (LAX)
Lat2=33.94
Lon2=-118.40

'*** Units: K=kilometers  M=miles  N=nautical miles
Unit$ = "K"

Result=HAVERSINE(Lat1,Lon1,Lat2,Lon2,Unit$)
R$=STR$(Result,"#,###.##")

PRINT "The distance between Nashville International Airport and Los Angeles International Airport in kilometers is: "&R$

STOP

DEF HAVERSINE(Lat1,Lon1,Lat2,Lon2,Unit$)
'---------------------------------------------------------------
'*** Haversine Formula - Calculate distances by LAT/LONG
'

'*** Pass to it the LAT/LONG of the two locations, and then unit of measure
'*** Usage: X=HAVERSINE(Lat1,Lon1,Lat2,Lon2,Unit$)

    PI=3.14159265358979323846
    Radius=6372.8
    Lat1=(Lat1*PI/180)
    Lon1=(Lon1*PI/180)
    Lat2=(Lat2*PI/180)
    Lon2=(Lon2*PI/180)
    DLon=Lon1-Lon2
    Answer=ACOS(SIN(Lat1)*SIN(Lat2)+COS(Lat1)*COS(Lat2)*COS(DLon))*Radius

    IF UNIT$="M" THEN Answer=Answer*0.621371192
    IF UNIT$="N" THEN Answer=Answer*0.539956803

  RETURN Answer

ENDDEF


program spheredist
	version 15.0
	syntax varlist(min=4 max=4 numeric), GENerate(namelist max=1) ///
		[Radius(real 6371) ALTitude(real 0) LABel(string)]
	confirm new variable `generate'
	local lat1 : word 1 of `varlist'
	local lon1 : word 2 of `varlist'
	local lat2 : word 3 of `varlist'
	local lon2 : word 4 of `varlist'
	local r=2*(`radius'+`altitude'/1000)
	local k=_pi/180
	gen `generate'=`r'*asin(sqrt(sin((`lat2'-`lat1')*`k'/2)^2+ ///
		cos(`lat1'*`k')*cos(`lat2'*`k')*sin((`lon2'-`lon1')*`k'/2)^2))
	if `"`label'"' != "" {
		label variable `generate' `"`label'"'
	}
end


program happy

  implicit none
  integer, parameter :: find = 8
  integer :: found
  integer :: number

  found = 0
  number = 1
  do
    if (found == find) then
      exit
    end if
    if (is_happy (number)) then
      found = found + 1
      write (*, '(i0)') number
    end if
    number = number + 1
  end do

contains

  function sum_digits_squared (number) result (result)

    implicit none
    integer, intent (in) :: number
    integer :: result
    integer :: digit
    integer :: rest
    integer :: work

    result = 0
    work = number
    do
      if (work == 0) then
        exit
      end if
      rest = work / 10
      digit = work - 10 * rest
      result = result + digit * digit
      work = rest
    end do

  end function sum_digits_squared

  function is_happy (number) result (result)

    implicit none
    integer, intent (in) :: number
    logical :: result
    integer :: turtoise
    integer :: hare

    turtoise = number
    hare = number
    do
      turtoise = sum_digits_squared (turtoise)
      hare = sum_digits_squared (sum_digits_squared (hare))
      if (turtoise == hare) then
        exit
      end if
    end do
    result = turtoise == 1

  end function is_happy

end program happy


begin: parse(( = { <Hello, World!> * } ));


import Foundation

func haversine(lat1:Double, lon1:Double, lat2:Double, lon2:Double) -> Double {
    let lat1rad = lat1 * Double.pi/180
    let lon1rad = lon1 * Double.pi/180
    let lat2rad = lat2 * Double.pi/180
    let lon2rad = lon2 * Double.pi/180

    let dLat = lat2rad - lat1rad
    let dLon = lon2rad - lon1rad
    let a = sin(dLat/2) * sin(dLat/2) + sin(dLon/2) * sin(dLon/2) * cos(lat1rad) * cos(lat2rad)
    let c = 2 * asin(sqrt(a))
    let R = 6372.8

    return R * c
}

print(haversine(lat1:36.12, lon1:-86.67, lat2:33.94, lon2:-118.40))


lat1 : 36.12
lon1 : -86.67
lat2 : 33.94
lon2 : -118.4

dx : 0.
dy : 0.
dz : 0.
kms : 0.

 {degtorad(lon2 - lon1)} lon1
 {degtorad lat1} lat1
 {degtorad lat2} lat2

 {sin lat1 - sin lat2} dz
 {cos lon1 * cos lat1 - cos lat2} dx
 {sin lon1 * cos lat1} dy

 {arcsin(sqrt(dx^2 + dy^2 + dz^2)/2) * 12745.6} kms

 "'Haversine distance: ' kms ' kms'" []


OPTION angle radians ' the default
SUB haversine(lat1, lon1, lat2, lon2)
	DIM EarthRadiusKm = 6372.8        ' Earth radius in kilometers
	DIM latRad1 = RAD(lat1)
	DIM latRad2 = RAD(lat2)
	DIM lonRad1 = RAD(lon1)
	DIM lonRad2 = RAD(lon2)
	DIM _diffLa = latRad2 - latRad1
	DIM _doffLo = lonRad2 - lonRad1
	DIM sinLaSqrd = SIN(_diffLa / 2) ^ 2
	DIM sinLoSqrd = SIN(_doffLo / 2) ^ 2
	DIM computation = asin(sqrt(sinLaSqrd + COS(latRad1) * COS(latRad2) * sinLoSqrd))
	RETURN 2 * EarthRadiusKm * computation
END SUB

PRINT USING "Nashville International Airport to Los Angeles International Airport ####.########### km", haversine(36.12, -86.67, 33.94, -118.40)
PRINT USING "Perth, WA Australia to Baja California, Mexico #####.########### km", haversine(-31.95, 115.86, 31.95, -115.86)


' FB 1.05.0 Win64

Function isHappy(n As Integer) As Boolean
  If n < 0 Then Return False
  ' Declare a dynamic array to store previous sums.
  ' If a previous sum is duplicated before a sum of 1 is reached
  ' then the number can't be "happy" as the cycle will just repeat
  Dim prevSums() As Integer
  Dim As Integer digit, ub, sum = 0
  Do
    While n > 0
      digit = n Mod 10
      sum += digit * digit
      n \= 10
    Wend
    If sum = 1 Then Return True
    ub = UBound(prevSums)
    If ub > -1 Then
      For i As Integer = 0 To ub
         If sum = prevSums(i) Then Return False
      Next
    End If
    ub += 1
    Redim Preserve prevSums(0 To ub)
    prevSums(ub) = sum
    n = sum
    sum  = 0
  Loop
End Function

Dim As Integer n = 1, count = 0

Print "The first 8 happy numbers are : "
Print
While count < 8
  If isHappy(n) Then
    count += 1
    Print count;" =>"; n
  End If
  n += 1
Wend
Print
Print "Press any key to quit"
Sleep


module Happy where

import Prelude.Math
-- ugh, since Frege doesn't have Set, use Map instead
import Data.Map (member, insertMin, empty emptyMap)

digitToInteger :: Char -> Integer
digitToInteger c = fromInt $ (ord c) - (ord '0')

isHappy :: Integer -> Bool
isHappy = p emptyMap
  where p _ 1n = true
        p s n | n `member` s = false
              | otherwise  = p (insertMin n () s) (f n)
        f = sum . map (sqr . digitToInteger) . unpacked . show

main _ = putStrLn $ unwords $ map show $ take 8 $ filter isHappy $ iterate (+ 1n) 1n


package require Tcl 8.5
proc haversineFormula {lat1 lon1 lat2 lon2} {
    set rads [expr atan2(0,-1)/180]
    set R 6372.8    ;# In kilometers

    set dLat [expr {($lat2-$lat1) * $rads}]
    set dLon [expr {($lon2-$lon1) * $rads}]
    set lat1 [expr {$lat1 * $rads}]
    set lat2 [expr {$lat2 * $rads}]

    set a [expr {sin($dLat/2)**2 + sin($dLon/2)**2*cos($lat1)*cos($lat2)}]
    set c [expr {2*asin(sqrt($a))}]
    return [expr {$R * $c}]
}

# Don't bother with too much inappropriate accuracy!
puts [format "distance=%.1f km" [haversineFormula 36.12 -86.67 33.94 -118.40]]


{{trans|BASIC}}
FUNCTION HAVERSINE
!---------------------------------------------------------------
!*** Haversine Formula - Calculate distances by LAT/LONG
!

!*** LAT/LON of the two locations and Unit of measure are GLOBAL
!*** as they are defined in the main logic of the program, so they
!*** available for use in the Function.
!*** Usage: X=HAVERSINE

    Radius=6378.137
    Lat1=(Lat1*MATH.PI/180)
    Lon1=(Lon1*MATH.PI/180)
    Lat2=(Lat2*MATH.PI/180)
    Lon2=(Lon2*MATH.PI/180)
    DLon=Lon1-Lon2
    ANSWER=ACOS(SIN(Lat1)*SIN(Lat2)+COS(Lat1)*COS(Lat2)*COS(DLon))*Radius

    DISTANCE="kilometers"
    SELECT CASE UNIT
           CASE "M"
                HAVERSINE=ANSWER*0.621371192
                Distance="miles"
           CASE "N"
                HAVERSINE=ANSWER*0.539956803
                Distance="nautical miles"
    END SELECT

END FUNCTION


# syntax: CALL SP_HAVERSINE(36.12,33.94,-86.67,-118.40,x);

CREATE PROCEDURE SP_HAVERSINE
(
IN lat1 FLOAT,
IN lat2 FLOAT,
IN lon1 FLOAT,
IN lon2 FLOAT,
OUT distance FLOAT)

BEGIN
    DECLARE dLat FLOAT;
    DECLARE dLon FLOAT;
    DECLARE c FLOAT;
    DECLARE a FLOAT;
    DECLARE km FLOAT;

    SET dLat = RADIANS(lat2-lat1);
    SET dLon = RADIANS(lon2-lon1);

    SET a = SIN(dLat / 2) * SIN(dLat / 2) + SIN(dLon / 2) * SIN(dLon / 2) * COS(RADIANS(lat1)) * COS(RADIANS(lat2));
    SET c = 2 * ASIN(SQRT(a));
    SET km = 6372.8 * c;

    SELECT km INTO distance;
END;


package main

import "fmt"

func happy(n int) bool {
	m := make(map[int]bool)
	for n > 1 {
		m[n] = true
		var x int
		for x, n = n, 0; x > 0; x /= 10 {
			d := x % 10
			n += d * d
		}
		if m[n] {
			return false
		}
	}
	return true
}

func main() {
	for found, n := 0, 1; found < 8; n++ {
		if happy(n) {
			fmt.Print(n, " ")
			found++
		}
	}
	fmt.Println()
}


! In True BASIC all programs run in their own window. So this is almost a graphical version.
PRINT "Hello world!"
END


CREATE FUNCTION [dbo].[Haversine](@Lat1 AS DECIMAL(9,7), @Lon1 AS DECIMAL(10,7), @Lat2 AS DECIMAL(9,7), @Lon2 AS DECIMAL(10,7))
RETURNS DECIMAL(12,7)
AS
BEGIN
	DECLARE @R	DECIMAL(11,7);
	DECLARE @dLat	DECIMAL(9,7);
	DECLARE @dLon	DECIMAL(10,7);
	DECLARE @a	DECIMAL(10,7);
	DECLARE @c	DECIMAL(10,7);

	SET @R		= 6372.8;
	SET @dLat	= RADIANS(@Lat2 - @Lat1);
	SET @dLon	= RADIANS(@Lon2 - @Lon1);
	SET @Lat1	= RADIANS(@Lat1);
	SET @Lat2	= RADIANS(@Lat2);
	SET @a		= SIN(@dLat / 2) * SIN(@dLat / 2) + SIN(@dLon / 2) * SIN(@dLon / 2) * COS(@Lat1) * COS(@Lat2);
	SET @c		= 2 * ASIN(SQRT(@a));

	RETURN @R * @c;
END
GO

SELECT dbo.Haversine(36.12,-86.67,33.94,-118.4)


DEF Haversine (lat1, long1, lat2, long2)
    OPTION ANGLE RADIANS
    LET R = 6372.8                !radio terrestre en km.
    LET dLat = RAD(lat2-lat1)
    LET dLong = RAD(long2-long1)
    LET lat1 = RAD(lat1)
    LET lat2 = RAD(lat2)
    LET Haversine = R *2 * ASIN(SQR(SIN(dLat/2)^2 + SIN(dLong/2)^2 *COS(lat1) * COS(lat2)))
END DEF
PRINT

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


Number.metaClass.isHappy = {
    def number = delegate as Long
    def cycle = new HashSet<Long>()
    while (number != 1 && !cycle.contains(number)) {
        cycle << number
        number = (number as String).collect { d = (it as Long); d * d }.sum()
    }
    number == 1
}

def matches = []
for (int i = 0; matches.size() < 8; i++) {
    if (i.happy) { matches << i }
}
println matches


PROCEDURE Main()
   LOCAL i := 8, nH := 0

   ? hb_StrFormat( "The first %d happy numbers are:", i )
   ?

   WHILE i > 0
      IF IsHappy( ++nH )
	?? hb_NtoS( nH ) + " "
	--i
      ENDIF
   END

   RETURN

STATIC FUNCTION IsHappy( nNumber )
   STATIC aUnhappy := {}
   LOCAL nDigit, nSum := 0, cNumber := hb_NtoS( nNumber )

   FOR EACH nDigit IN cNumber
      nSum += Val( nDigit ) ^ 2
   NEXT

   IF nSum == 1
      aUnhappy := {}
      RETURN .T.
   ELSEIF AScan( aUnhappy, nSum ) > 0
     RETURN .F.
   ENDIF

   AAdd( aUnhappy, nSum )

   RETURN IsHappy( nSum )


let radians = function (degree: number) {

    // degrees to radians
    let rad: number = degree * Math.PI / 180;

    return rad;
}

export const haversine = (lat1: number, lon1: number, lat2: number, lon2: number) => {

    // var dlat: number, dlon: number, a: number, c: number, R: number;
    let dlat, dlon, a, c, R: number;

    R = 6372.8; // km
    dlat = radians(lat2 - lat1);
    dlon = radians(lon2 - lon1);
    lat1 = radians(lat1);
    lat2 = radians(lat2);
    a = Math.sin(dlat / 2) * Math.sin(dlat / 2) + Math.sin(dlon / 2) * Math.sin(dlon / 2) * Math.cos(lat1) * Math.cos(lat2)
    c = 2 * Math.asin(Math.sqrt(a));
    return R * c;
}

console.log("Distance:" + haversine(36.12, -86.67, 33.94, -118.40));


import Data.Char (digitToInt)
import Data.Set (member, insert, empty)

isHappy :: Integer -> Bool
isHappy = p empty
  where
    p _ 1 = True
    p s n
      | n `member` s = False
      | otherwise = p (insert n s) (f n)
    f = sum . fmap ((^ 2) . toInteger . digitToInt) . show

main :: IO ()
main = mapM_ print $ take 8 $ filter isHappy [1 ..]


procedure main(arglist)
local n
n := arglist[1] | 8    # limiting number of happy numbers to generate, default=8
writes("The first ",n," happy numbers are:")
every writes(" ", happy(seq()) \ n )
write()
end

procedure happy(i)    #: returns i if i is happy
local n

    if  4 ~= (0 <= i) then { # unhappy if negative, 0, or 4
        if i = 1 then return i
        every (n := 0) +:= !i ^ 2
        if happy(n) then return i
        }
end


Const MER = 6371         '-- mean earth radius(km)
Public DEG_TO_RAD As Double

Function haversine(lat1 As Double, long1 As Double, lat2 As Double, long2 As Double) As Double
    lat1 = lat1 * DEG_TO_RAD
    lat2 = lat2 * DEG_TO_RAD
    long1 = long1 * DEG_TO_RAD
    long2 = long2 * DEG_TO_RAD
    haversine = MER * WorksheetFunction.Acos(Sin(lat1) * Sin(lat2) + Cos(lat1) * Cos(lat2) * Cos(long2 - long1))
End Function

Public Sub main()
    DEG_TO_RAD = WorksheetFunction.Pi / 180
    d = haversine(36.12, -86.67, 33.94, -118.4)
    Debug.Print "Distance is "; Format(d, "#.######"); " km ("; Format(d / 1.609344, "#.######"); " miles)."
End Sub


Imports System.Math

Module Module1

  Const deg2rad As Double = PI / 180

  Structure AP_Loc
    Public IATA_Code As String, Lat As Double, Lon As Double

    Public Sub New(ByVal iata_code As String, ByVal lat As Double, ByVal lon As Double)
      Me.IATA_Code = iata_code : Me.Lat = lat * deg2rad : Me.Lon = lon * deg2rad
    End Sub

    Public Overrides Function ToString() As String
      Return String.Format("{0}: ({1}, {2})", IATA_Code, Lat / deg2rad, Lon / deg2rad)
    End Function
  End Structure

  Function Sin2(ByVal x As Double) As Double
    Return Pow(Sin(x / 2), 2)
  End Function

  Function calculate(ByVal one As AP_Loc, ByVal two As AP_Loc) As Double
    Dim R As Double = 6371, ' In kilometers, (as recommended by the International Union of Geodesy and Geophysics)
        a As Double = Sin2(two.Lat - one.Lat) + Sin2(two.Lon - one.Lon) * Cos(one.Lat) * Cos(two.Lat)
    Return R * 2 * Asin(Sqrt(a))
  End Function

  Sub ShowOne(pntA As AP_Loc, pntB as AP_Loc)
    Dim adst As Double = calculate(pntA, pntB), sfx As String = "km"
    If adst < 1000 Then adst *= 1000 : sfx = "m"
    Console.WriteLine("The approximate distance between airports {0} and {1} is {2:n2} {3}.", pntA, pntB, adst, sfx)
    Console.WriteLine("The uncertainty is under 0.5%, or {0:n1} {1}." & vbLf, adst / 200, sfx)
  End Sub

' Airport coordinate data excerpted from the data base at http://www.partow.net/miscellaneous/airportdatabase/

' The four additional airports are the furthest and closest pairs, according to the "Fun Facts..." section.

' KBNA, BNA, NASHVILLE INTERNATIONAL, NASHVILLE, USA, 036, 007, 028, N, 086, 040, 041, W, 00183, 36.124, -86.678
' KLAX, LAX, LOS ANGELES INTERNATIONAL, LOS ANGELES, USA, 033, 056, 033, N, 118, 024, 029, W, 00039, 33.942, -118.408
' SKNV, NVA, BENITO SALAS, NEIVA, COLOMBIA, 002, 057, 000, N, 075, 017, 038, W, 00439, 2.950, -75.294
' WIPP, PLM, SULTAN MAHMUD BADARUDDIN II, PALEMBANG, INDONESIA, 002, 053, 052, S, 104, 042, 004, E, 00012, -2.898, 104.701
' LOWL, LNZ, HORSCHING INTERNATIONAL AIRPORT (AUS - AFB), LINZ, AUSTRIA, 048, 014, 000, N, 014, 011, 000, E, 00096, 48.233, 14.183
' LOXL, N/A, LINZ, LINZ, AUSTRIA, 048, 013, 059, N, 014, 011, 015, E, 00299, 48.233, 14.188

  Sub Main()
    ShowOne(New AP_Loc("BNA", 36.124, -86.678),  New AP_Loc("LAX", 33.942, -118.408))
    ShowOne(New AP_Loc("NVA",  2.95,  -75.294),  New AP_Loc("PLM", -2.898,  104.701))
    ShowOne(New AP_Loc("LNZ", 48.233,  14.183),  New AP_Loc("N/A", 48.233,   14.188))
  End Sub
End Module


import java.util.HashSet;
public class Happy{
   public static boolean happy(long number){
       long m = 0;
       int digit = 0;
       HashSet<Long> cycle = new HashSet<Long>();
       while(number != 1 && cycle.add(number)){
           m = 0;
           while(number > 0){
               digit = (int)(number % 10);
               m += digit*digit;
               number /= 10;
           }
           number = m;
       }
       return number == 1;
   }

   public static void main(String[] args){
       for(long num = 1,count = 0;count<8;num++){
           if(happy(num)){
               System.out.println(num);
               count++;
           }
       }
   }
}


முதன்மை என்பதின் வகை எண் பணி {{
         ("உலகத்தோருக்கு வணக்கம்") என்பதை திரை.இடு;

         முதன்மை = 0;
}};


import math

fn haversine(h f64) f64 {
    return .5 * (1 - math.cos(h))
}

struct Pos {
    lat f64 // latitude, radians
    long f64 // longitude, radians
}

fn deg_pos(lat f64, lon f64) Pos {
    return Pos{lat * math.pi / 180, lon * math.pi / 180}
}

const r_earth = 6372.8 // km

fn hs_dist(p1 Pos, p2 Pos) f64 {
    return 2 * r_earth * math.asin(math.sqrt(haversine(p2.lat-p1.lat)+
        math.cos(p1.lat)*math.cos(p2.lat)*haversine(p2.long-p1.long)))
}

fn main() {
    println(hs_dist(deg_pos(36.12, -86.67), deg_pos(33.94, -118.40)))
}


var R = 6372.8  // Earth's approximate radius in kilometers.

/*  Class containing trig methods which work with degrees rather than radians. */
class D {
    static deg2Rad(deg) { (deg*Num.pi/180 + 2*Num.pi) % (2*Num.pi) }
    static sin(d) { deg2Rad(d).sin }
    static cos(d) { deg2Rad(d).cos }
}

var haversine = Fn.new { |lat1, lon1, lat2, lon2|
    var dlat = lat2 - lat1
    var dlon = lon2 - lon1
    return 2 * R * (D.sin(dlat/2).pow(2) + D.cos(lat1) * D.cos(lat2) * D.sin(dlon/2).pow(2)).sqrt.asin
}

System.print(haversine.call(36.12, -86.67, 33.94, -118.4))