import Foundation

func isPalin2(n: Int) -> Bool {
  var x = 0
  var n = n

  guard n & 1 != 0 else {
    return n == 0
  }

  while x < n {
    x = x << 1 | n & 1
    n >>= 1
  }

  return n == x || n == x >> 1
}

func reverse3(n: Int) -> Int {
  var x = 0
  var n = n

  while n > 0 {
    x = x * 3 + (n % 3)
    n /= 3
  }

  return x
}

func printN(_ n: Int, base: Int) {
  var n = n

  print(" ", terminator: "")

  repeat {
    print("\(n % base)", terminator: "")

    n /= base
  } while n > 0

  print("(\(base))", terminator: "")
}

func show(n: Int) {
  print(n, terminator: "")
  printN(n, base: 2)
  printN(n, base: 3)
  print()
}

private var count = 0
private var lo = 0
private var (hi, pow2, pow3) = (1, 1, 1)

show(n: 0)

while true {
  var n: Int

  for i in lo..<hi {
    n = (i * 3 + 1) * pow3 + reverse3(n: i)

    guard isPalin2(n: n) else {
      continue
    }

    show(n: n)
    count += 1

    guard count < 7 else {
      exit(0)
    }
  }

  if hi == pow3 {
    pow3 *= 3
  } else {
    pow2 *= 4
  }

  while true {
    while pow2 <= pow3 {
      pow2 *= 4
    }

    let lo2 = (pow2 / pow3 - 1) / 3
    let hi2 = (pow2 * 2 / pow3 - 1) / 3 + 1
    let lo3 = pow3 / 3
    let hi3 = pow3

    if lo2 >= hi3 {
      pow3 *= 3
    } else if lo3 >= hi2 {
      pow2 *= 4
    } else {
      lo = max(lo2, lo3)
      hi = min(hi2, hi3)
      break
    }
  }
}


proc format_%t {n} {
    while {$n} {
        append r [expr {$n % 3}]
        set n [expr {$n / 3}]
    }
    if {![info exists r]} {set r 0}
    string reverse $r
}


(for-each (lambda (x)
      (print (cond
         ((and (zero? (mod x 3)) (zero? (mod x 5)))
            "FizzBuzz")
         ((zero? (mod x 3))
            "Fizz")
         ((zero? (mod x 5))
            "Buzz")
         (else
            x))))
   (iota 100))


Public Declare Function GetTickCount Lib "kernel32.dll" () As Long
'palindromes both in base3 and base2
'using Decimal data type to find number 6 and 7, although slowly
Private Function DecimalToBinary(DecimalNum As Long) As String
    Dim tmp As String
    Dim n As Long

    n = DecimalNum

    tmp = Trim(CStr(n Mod 2))
    n = n \ 2

    Do While n <> 0
    tmp = Trim(CStr(n Mod 2)) & tmp
    n = n \ 2
    Loop

    DecimalToBinary = tmp
End Function
Function Dec2Bin(ByVal DecimalIn As Variant, _
              Optional NumberOfBits As Variant) As String
    Dec2Bin = ""
    DecimalIn = Int(CDec(DecimalIn))
    Do While DecimalIn <> 0
        Dec2Bin = Format$(DecimalIn - 2 * Int(DecimalIn / 2)) & Dec2Bin
        DecimalIn = Int(DecimalIn / 2)
    Loop
    If Not IsMissing(NumberOfBits) Then
       If Len(Dec2Bin) > NumberOfBits Then
          Dec2Bin = "Error - Number exceeds specified bit size"
       Else
          Dec2Bin = Right$(String$(NumberOfBits, _
                    "0") & Dec2Bin, NumberOfBits)
       End If
    End If
End Function
Public Sub base()
    'count integer n from 0 upwards
    'display representation in base 3

    Time1 = GetTickCount
    Dim n As Long
    Dim three(19) As Integer
    Dim pow3(19) As Variant
    Dim full3 As Variant
    Dim trail As Variant
    Dim check As Long
    Dim len3 As Integer
    Dim carry As Boolean
    Dim i As Integer, j As Integer
    Dim s As String
    Dim t As String
    pow3(0) = CDec(1)
    For i = 1 To 19
        pow3(i) = 3 * pow3(i - 1)
    Next i
    Debug.Print String$(5, " "); "iter"; String$(7, " "); "decimal"; String$(18, " "); "binary";
    Debug.Print String$(30, " "); "ternary"
    n = 0: full3 = 0: t = "0": s = "0"
    Debug.Print String$(8 - Len(CStr(n)), " "); n; String$(12 - Len(CStr(full3)), " ");
    Debug.Print full3; String$((41 - Len(t)) / 2, " "); t; String$((41 - Len(t)) / 2, " ");
    Debug.Print String$((31 - Len(s)) / 2, " "); s
    n = 0: full3 = 1: t = "1": s = "1"
    Debug.Print String$(8 - Len(CStr(n)), " "); n; String$(12 - Len(CStr(full3)), " ");
    Debug.Print full3; String$((41 - Len(t)) / 2, " "); t; String$((41 - Len(t)) / 2, " ");
    Debug.Print String$((31 - Len(s)) / 2, " "); s
    number = 0
    n = 1
    len3 = 0
    full3 = 3
    Do 'For n = 1 To 200000 '20000000 takes 1000 seconds and number 7 not found yet
        three(0) = three(0) + 1
        carry = False
        If three(0) = 3 Then
            three(0) = 0
            carry = True
            j = 1
            Do While carry
                three(j) = three(j) + 1
                If three(j) = 3 Then
                    three(j) = 0
                    j = j + 1
                Else
                    carry = False
                End If
            Loop
            If len3 < j Then
                trail = full3 - (n - 1) * pow3(len3 + 2) - pow3(len3 + 1)
                len3 = j
                full3 = n * pow3(len3 + 2) + pow3(len3 + 1) + 3 * trail
                For i = 0 To j - 1
                    full3 = full3 - 2 * pow3(len3 - i)
                Next i
                full3 = full3 + 1 'as j=len3 now and 1=pow3(len3 - j)
            Else
                full3 = full3 + pow3(len3 + 2)
                For i = 0 To j - 1
                    full3 = full3 - 2 * pow3(len3 - i)
                Next i
                full3 = full3 + pow3(len3 - j)
            End If
        Else
            full3 = full3 + pow3(len3 + 2) + pow3(len3)
        End If
        s = ""
        For i = 0 To len3
            s = s & CStr(three(i))
        Next i
        'do we have a hit?
        t = Dec2Bin(full3) 'CStr(DecimalToBinary(full3))
        If t = StrReverse(t) Then
            'we have a hit
            number = number + 1
            s = StrReverse(s) & "1" & s
            If n < 200000 Then
                Debug.Print String$(8 - Len(CStr(n)), " "); n; String$(12 - Len(CStr(full3)), " ");
                Debug.Print full3; String$((41 - Len(t)) / 2, " "); t; String$((41 - Len(t)) / 2, " ");
                Debug.Print String$((31 - Len(s)) / 2, " "); s
                If number = 4 Then
                    Debug.Print "Completed in"; (GetTickCount - Time1) / 1000; "seconds"
                    Time2 = GetTickCount
                    Application.ScreenUpdating = False
                End If
            Else
                Debug.Print n, full3, Len(t), t, Len(s), s
                Debug.Print "Completed in"; (Time2 - Time1) / 1000; "seconds";
                Time3 = GetTickCount
            End If
        End If
        n = n + 1
    Loop Until number = 5 'Next n
    Debug.Print "Completed in"; (Time3 - Time1) / 1000; "seconds"
    Application.ScreenUpdating = True
End Sub


fizz: func (n: Int) -> Bool {
  if(n % 3 == 0) {
    printf("Fizz")
    return true
  }
  return false
}

buzz: func (n: Int) -> Bool {
  if(n % 5 == 0) {
    printf("Buzz")
    return true
  }
  return false
}

main: func {
  for(n in 1..100) {
    fizz:= fizz(n)
    buzz:= buzz(n)
    fizz || buzz || printf("%d", n)
    println()
  }
}


import "/fmt" for Fmt

var isPalindrome2 = Fn.new { |n|
    var x = 0
    if (n % 2 == 0) return n == 0
    while (x < n) {
        x = x*2 + (n%2)
        n = (n/2).floor
    }
    return n == x || n == (x/2).floor
}

var reverse3 = Fn.new { |n|
    var x = 0
    while (n != 0) {
        x = x*3 + (n%3)
        n = (n/3).floor
    }
    return x
}

var start

var show = Fn.new { |n|
    Fmt.print("Decimal : $d", n)
    Fmt.print("Binary  : $b", n)
    Fmt.print("Ternary : $t", n)
    Fmt.print("Time    : $0.3f ms\n", (System.clock - start)*1000)
}

var min = Fn.new { |a, b| (a < b) ? a : b }
var max = Fn.new { |a, b| (a > b) ? a : b }

start = System.clock
System.print("The first 6 numbers which are palindromic in both binary and ternary are :\n")
show.call(0)
var cnt = 1
var lo = 0
var hi = 1
var pow2 = 1
var pow3 = 1
while (true) {
    var i = lo
    while (i < hi) {
        var n = (i*3+1)*pow3 + reverse3.call(i)
        if (isPalindrome2.call(n)) {
            show.call(n)
            cnt = cnt + 1
            if (cnt >= 6) return
        }
        i = i + 1
    }
    if (i == pow3) {
        pow3 = pow3 * 3
    } else {
        pow2 = pow2 * 4
    }
    while (true) {
        while (pow2 <= pow3) pow2 = pow2 * 4
        var lo2 = (((pow2/pow3).floor - 1)/3).floor
        var hi2 = (((pow2*2/pow3).floor-1)/3).floor + 1
        var lo3 = (pow3/3).floor
        var hi3 = pow3
        if (lo2 >= hi3) {
            pow3 = pow3 * 3
        } else if (lo3 >= hi2) {
            pow2 = pow2 * 4
        } else {
            lo = max.call(lo2, lo3)
            hi = min.call(hi2, hi3)
            break
        }
    }
}


#include <order/interpreter.h>

// Get FB for one number
#define ORDER_PP_DEF_8fizzbuzz ORDER_PP_FN(            \
8fn(8N,                                                \
    8let((8F, 8fn(8N, 8G,                              \
                  8is_0(8remainder(8N, 8G)))),         \
         8cond((8ap(8F, 8N, 15), 8quote(fizzbuzz))     \
               (8ap(8F, 8N, 3), 8quote(fizz))          \
               (8ap(8F, 8N, 5), 8quote(buzz))          \
               (8else, 8N)))) )

// Print E followed by a comma (composable, 8print is not a function)
#define ORDER_PP_DEF_8print_el ORDER_PP_FN( \
8fn(8E, 8print(8E 8comma)) )

ORDER_PP(  // foreach instead of map, to print but return nothing
  8seq_for_each(8compose(8print_el, 8fizzbuzz), 8seq_iota(1, 100))
)


F line_intersect(Ax1, Ay1, Ax2, Ay2, Bx1, By1, Bx2, By2)
   V d = (By2 - By1) * (Ax2 - Ax1) - (Bx2 - Bx1) * (Ay2 - Ay1)
   I d == 0
      R (Float.infinity, Float.infinity)

   V uA = ((Bx2 - Bx1) * (Ay1 - By1) - (By2 - By1) * (Ax1 - Bx1)) / d
   V uB = ((Ax2 - Ax1) * (Ay1 - By1) - (Ay2 - Ay1) * (Ax1 - Bx1)) / d

   I !(uA C 0.0..1.0 & uB C 0.0..1.0)
      R (Float.infinity, Float.infinity)
   V x = Ax1 + uA * (Ax2 - Ax1)
   V y = Ay1 + uA * (Ay2 - Ay1)

   R (x, y)

V (a, b, c, d) = (4.0, 0.0, 6.0, 10.0)
V (e, f, g, h) = (0.0, 3.0, 10.0, 7.0)
V pt = line_intersect(a, b, c, d, e, f, g, h)
print(pt)


fcn pal23W{  //--> iterator returning (index,palindromic number)
   Walker.tweak(fcn(ri,r){  // references to loop start and count of palindromes
      foreach i in ([ri.value..*]){
	 n3:=i.toString(3);
	 n:=String(n3,"1",n3.reverse()).toInt(3);  // create base 3 palindrome
	 n2:= n.toString(2);
	 if(n2.len().isOdd and n2==n2.reverse()){  // stop here, return answer
	    ri.set(i+1);    // continue loop from this value at next iteration
	    return(r.inc(),n);
	 }
      }
   }.fp(Ref(3),Ref(3))).push(T(1,0),T(2,1))  // seed with first two results
}


declare
  fun {FizzBuzz X}
     if     X mod 15 == 0 then 'FizzBuzz'
     elseif X mod  3 == 0 then 'Fizz'
     elseif X mod  5 == 0 then 'Buzz'
     else                      X
     end
  end
in
  for I in 1..100 do
     {Show {FizzBuzz I}}
  end


*        Intersection of two lines   01/03/2019
INTERSEC CSECT
         USING  INTERSEC,R13       base register
         B      72(R15)            skip savearea
         DC     17F'0'             savearea
         SAVE   (14,12)            save previous context
         ST     R13,4(R15)         link backward
         ST     R15,8(R13)         link forward
         LR     R13,R15            set addressability
         LE     F0,XA              xa
       IF    CE,F0,EQ,XB THEN      if xa=xb then
         STE    F0,X1                x1=xa
         LE     F0,YA
       IF    CE,F0,EQ,YB THEN        if ya=yb then
         MVI    MSG,C'='               msg='='
       ENDIF    ,                    endif
       ELSE     ,                  else
         MVI    FK1,X'01'            fk1=true
         LE     F0,YB
         SE     F0,YA                yb-ya
         LE     F2,XB
         SE     F2,XA                xb-xa
         DER    F0,F2                /
         STE    F0,K1                k1=(yb-ya)/(xb-xa)
         ME     F0,XA                k1*xa
         LE     F2,YA                ya
         SER    F2,F0                -
         STE    F2,D1                d1=ya-k1*xa
       ENDIF    ,                  endif
         LE     F0,XC
       IF    CE,F0,EQ,XD THEN      if xc=xd then
         STE    F0,X2                x2=xc
         LE     F4,YC                yc
       IF    CE,F4,EQ,YD THEN        if yc=yd then
         MVI    MSG,C'='               msg='='
       ENDIF    ,                    endif
       ELSE     ,                  else
         MVI    FK2,X'01'            fk2=true
         LE     F0,YD
         SE     F0,YC                yd-yc
         LE     F2,XD
         SE     F2,XC                xd-xc
         DER    F0,F2                /
         STE    F0,K2                k2=(yd-yc)/(xd-xc)
         ME     F0,XC                k2*xc
         LE     F2,YC                yc
         SER    F2,F0                -
         STE    F2,D2                d2=yc-k2*xc
       ENDIF    ,                  endif
       IF   CLI,MSG,EQ,C' ' THEN   if msg=' ' then
       IF   CLI,FK1,EQ,X'00' THEN    if not fk1 then
       IF   CLI,FK2,EQ,X'00' THEN      if not fk2 then
         LE     F4,X1
       IF    CE,F4,EQ,X2                 if x1=x2 then
         MVI    MSG,C'='                   msg='='
       ELSE     ,                        else
         MVI    MSG,C'/'                   msg='/'
       ENDIF    ,                        endif
       ELSE     ,                      else
         LE     F0,X1
         STE    F0,X                     x=x1
         LE     F0,K2                    k2
         ME     F0,X                     *x
         AE     F0,D2                    +d2
         STE    F0,Y                     y=k2*x+d2
       ENDIF    ,                      endif
       ELSE     ,                    else
       IF    CLI,FK2,EQ,X'00' THEN     if not fk2 then
         LE     F0,X2
         STE    F0,X                     x=x2
         LE     F0,K1                    k1
         ME     F0,X                     *x
         AE     F0,D1                    +d1
         STE    F0,Y                     y=k1*x+d1
       ELSE     ,                      else
         LE     F4,K1
       IF    CE,F4,EQ,K2 THEN            if k1=k2 then
         LE     F4,D1
       IF    CE,F4,EQ,D2 THEN              if d1=d2 then
         MVI    MSG,C'='                     msg='=';
       ELSE     ,                          else
         MVI    MSG,C'/'                     msg='/';
       ENDIF    ,                          endif
       ELSE     ,                        else
         LE     F0,D2                      d2
         SE     F0,D1                      -d1
         LE     F2,K1                      k1
         SE     F2,K2                      -k2
         DER    F0,F2                      /
         STE    F0,X                       x=(d2-d1)/(k1-k2)
         LE     F0,K1                      k1
         ME     F0,X                       *x
         AE     F0,D1                      +d1
         STE    F0,Y                       y=k1*x+d1
       ENDIF    ,                        endif
       ENDIF    ,                      endif
       ENDIF    ,                    endif
       ENDIF    ,                  endif
       IF   CLI,MSG,EQ,C' ' THEN   if msg=' ' then
         LE     F0,X                 x
         LA     R0,3                 decimal=3
         BAL    R14,FORMATF          format x
         MVC    PG+0(13),0(R1)       output x
         LE     F0,Y                 y
         LA     R0,3                 decimal=3
         BAL    R14,FORMATF          format y
         MVC    PG+13(13),0(R1)      output y
       ENDIF    ,                  endif
         MVC    PG+28(1),MSG       output msg
         XPRNT  PG,L'PG            print buffer
         L      R13,4(0,R13)       restore previous savearea pointer
         RETURN (14,12),RC=0       restore registers from calling sav
         COPY   plig\$_FORMATF.MLC
XA       DC     E'4.0'             point A
YA       DC     E'0.0'
XB       DC     E'6.0'             point B
YB       DC     E'10.0'
XC       DC     E'0.0'             point C
YC       DC     E'3.0'
XD       DC     E'10.0'            point D
YD       DC     E'7.0'
X        DS     E
Y        DS     E
X1       DS     E
X2       DS     E
K1       DS     E
K2       DS     E
D1       DS     E
D2       DS     E
FK1      DC     X'00'
FK2      DC     X'00'
MSG      DC     C' '
PG       DC     CL80' '
         REGEQU
         END    INTERSEC


INCLUDE "D2:REAL.ACT" ;from the Action! Tool Kit

DEFINE REALPTR="CARD"
TYPE PointR=[REALPTR x,y]

PROC Det(REAL POINTER x1,y1,x2,y2,res)
  REAL tmp1,tmp2

  RealMult(x1,y2,tmp1)
  RealMult(y1,x2,tmp2)
  RealSub(tmp1,tmp2,res)
RETURN

BYTE FUNC IsZero(REAL POINTER a)
  CHAR ARRAY s(10)

  StrR(a,s)
  IF s(0)=1 AND s(1)='0 THEN
    RETURN (1)
  FI
RETURN (0)

BYTE FUNC Intersection(PointR POINTER p1,p2,p3,p4,res)
  REAL det1,det2,dx1,dx2,dy1,dy2,nom,denom

  Det(p1.x,p1.y,p2.x,p2.y,det1)
  Det(p3.x,p3.y,p4.x,p4.y,det2)
  RealSub(p1.x,p2.x,dx1)
  RealSub(p1.y,p2.y,dy1)
  RealSub(p3.x,p4.x,dx2)
  RealSub(p3.y,p4.y,dy2)
  Det(dx1,dy1,dx2,dy2,denom)

  IF IsZero(denom) THEN
    RETURN (0)
  FI

  Det(det1,dx1,det2,dx2,nom)
  RealDiv(nom,denom,res.x)
  Det(det1,dy1,det2,dy2,nom)
  RealDiv(nom,denom,res.y)
RETURN (1)

PROC PrintPoint(PointR POINTER p)
  Print("(") PrintR(p.x)
  Print(",") PrintR(p.y)
  Print(")")
RETURN

PROC PrintLine(PointR POINTER p1,p2)
  PrintPoint(p1)
  Print(" and ")
  PrintPoint(p2)
RETURN

PROC Test(PointR POINTER p1,p2,p3,p4)
  BYTE res
  REAL px,py
  PointR p

  p.x=px p.y=py
  Print("Line 1 points: ")
  PrintLine(p1,p2) PutE()
  Print("Line 2 points: ")
  PrintLine(p3,p4) PutE()

  res=Intersection(p1,p2,p3,p4,p)
  IF res THEN
    Print("Intersection point: ")
    PrintPoint(p) PutE()
  ELSE
    PrintE("There is no intersection")
  FI
  PutE()
RETURN

PROC Main()
  REAL x1,y1,x2,y2,x3,y3,x4,y4,px,py
  PointR p1,p2,p3,p4

  Put(125) PutE() ;clear screen

  p1.x=x1 p1.y=y1
  p2.x=x2 p2.y=y2
  p3.x=x3 p3.y=y3
  p4.x=x4 p4.y=y4

  IntToReal(4,x1) IntToReal(0,y1)
  IntToReal(6,x2) IntToReal(10,y2)
  IntToReal(0,x3) IntToReal(3,y3)
  IntToReal(10,x4) IntToReal(7,y4)
  Test(p1,p2,p3,p4)

  IntToReal(0,x1) IntToReal(0,y1)
  IntToReal(1,x2) IntToReal(1,y2)
  IntToReal(1,x3) IntToReal(2,y3)
  IntToReal(4,x4) IntToReal(5,y4)
  Test(p1,p2,p3,p4)
RETURN


with Ada.Text_IO;

procedure Intersection_Of_Two_Lines
is
   Do_Not_Intersect : exception;

   type Line is record
      a : Float;
      b : Float;
   end record;

   type Point is record
      x : Float;
      y : Float;
   end record;

   function To_Line(p1, p2 : in Point) return Line
   is
      a : constant Float := (p1.y - p2.y) / (p1.x - p2.x);
      b : constant Float := p1.y - (a * p1.x);
   begin
      return (a,b);
   end To_Line;

   function Intersection(Left, Right : in Line) return Point is
   begin
      if Left.a = Right.a then
         raise Do_Not_Intersect with "The two lines do not intersect.";
      end if;

      declare
         b : constant Float := (Right.b - Left.b) / (Left.a - Right.a);
      begin
         return (b, Left.a * b + Left.b);
      end;
   end Intersection;

   A1 : constant Line := To_Line((4.0, 0.0), (6.0, 10.0));
   A2 : constant Line := To_Line((0.0, 3.0), (10.0, 7.0));
   p : constant Point := Intersection(A1, A2);
begin
   Ada.Text_IO.Put(p.x'Img);
   Ada.Text_IO.Put_Line(p.y'Img);
end Intersection_Of_Two_Lines;


BEGIN
    # mode to hold a point #
    MODE POINT = STRUCT( REAL x, y );
    # mode to hold a line expressed as y = mx + c #
    MODE LINE  = STRUCT( REAL m, c );
    # returns the line that passes through p1 and p2 #
    PROC find line = ( POINT p1, p2 )LINE:
         IF x OF p1 = x OF p2 THEN
             # the line is vertical                 #
             LINE( 0, x OF p1 )
         ELSE
             # the line is not vertical             #
             REAL m = ( y OF p1 - y OF p2 ) / ( x OF p1 - x OF p2 );
             LINE( m, y OF p1 - ( m * x OF p1 ) )
         FI # find line # ;

    # returns the intersection of two lines - the lines must be distinct and not parallel #
    PRIO INTERSECTION = 5;
    OP   INTERSECTION = ( LINE l1, l2 )POINT:
         BEGIN
             REAL x = ( c OF l2 - c OF l1 ) / ( m OF l1 - m OF l2 );
             POINT( x, ( m OF l1 * x ) + c OF l1 )
         END # INTERSECTION # ;

    # find the intersection of the lines as per the task #
    POINT i = find line( POINT( 4.0, 0.0 ), POINT( 6.0, 10.0 ) )
              INTERSECTION find line( ( 0.0, 3.0 ), ( 10.0, 7.0 ) );
    print( ( fixed( x OF i, -8, 4 ), fixed( y OF i, -8, 4 ), newline ) )

END


⍝ APL has a powerful operator the « dyadic domino » to solve a system of N linear equations with N unknowns
⍝ We use it first to solve the a and b, defining the 2 lines as y = ax + b, with the x and y of the given points
⍝ The system of equations for first line will be:
⍝  0 = 4a + b
⍝ 10 = 6a + b
⍝ The two arguments to be passed to the dyadic domino are:
⍝ The (0, 10) vector as the left argument
⍝ The ( 4  1 ) matrix as the right argument.
⍝     ( 6  1 )
⍝ We will define a solver that will take the matrix of coordinates, one point per row, then massage the argument to extract x,y
⍝ and inject 1, where needed, and return a pair (a, b) of resolved unknowns.
⍝ Applied twice, we will have a, b and a', b' defining the two lines, we need to resolve it in x and y, in order to determine
⍝ their intersection
⍝ y =  ax + b
⍝ y = a'x + b'
⍝ In order to reuse the same solver, we need to format a little bit the arguments, and change the sign of a and a', therefore
⍝ multiply (a,b) and (a', b') by (-1, 1):
⍝ b  =  -ax + y
⍝ b' = -a'x + y
  A ← 4 0
  B ← 6 10
  C ← 0 3
  D ← 10 7
  solver ← {(,2 ¯1↑⍵)⌹(2 1↑⍵),1}
  I ← solver 2 2⍴((¯1 1)×solver 2 2⍴A,B),(¯1 1)×solver 2 2⍴C,D


program fizzbuzz(output);
var
  i: integer;
begin
  for i := 1 to 100 do
    if i mod 15 = 0 then
      writeln('FizzBuzz')
    else if i mod 3 = 0 then
      writeln('Fizz')
    else if i mod 5 = 0 then
      writeln('Buzz')
    else
      writeln(i)
end.


define :point [x,y][]
define :line [a, b][
    init: [
        this\slope: div this\b\y-this\a\y this\b\x-this\a\x
        this\yInt: this\a\y - this\slope*this\a\x
    ]
]

evalX: function [line, x][
    line\yInt + line\slope * x
]

intersect: function [line1, line2][
    x: div line2\yInt-line1\yInt line1\slope-line2\slope
    y: evalX line1 x

    to :point @[x y]
]

l1: to :line @[to :point [4.0 0.0] to :point [6.0 10.0]]
l2: to :line @[to :point [0.0 3.0] to :point [10.0 7.0]]

print intersect l1 l2


/--------------------------------------------------------
/THIS PROGRAM PRINTS THE INTEGERS FROM 1 TO 100 (INCL).
/WITH THE FOLLOWING RESTRICTIONS:
/  FOR MULTIPLES OF THREE, PRINT 'FIZZ'
/  FOR MULTIPLES OF FIVE,  PRINT 'BUZZ'
/  FOR MULTIPLES OF BOTH THREE AND FIVE, PRINT 'FIZZBUZZ'
/--------------------------------------------------------

/--------------------------------------------------------
/DEFINES
/--------------------------------------------------------
SWBA=7447               /EAE MODE A INSTRUCTION
DVI=7407                /EAE DIVIDE INSTRUCTION
AIX0=0010               /AUTO INDEX REGISTER 0
CR=0215                 /CARRIAGE RETURN
LF=0212                 /LINEFEED
EOT=0000                /END OF TEXT NUL
FIZMOD=0003             /CONSTANT DECIMAL 3 (FIZZ)
BUZMOD=0005             /CONSTANT DECIMAL 5 (BUZZ)
K10=0012                /CONSTANT DECIMAL 10

LAST=0144               /FIZZBUZZ THE NUMBERS 1..LAST
                        /0144 OCTAL == 100 DECIMAL
                        /CAN BE ANY FROM [0001...7777]

/--------------------------------------------------------
/FIZZBUZZ START=0200
/--------------------------------------------------------
        *200            /START IN MEMORY AT 0200 OCTAL
FZZBZZ, CLA             /CLEAR AC
        TAD (-LAST-1    /LOAD CONSTANT -(LAST+1)
        DCA CNTR        /SET UP MAIN COUNTER
        TAD (-FIZMOD    /SET UP FIZZ COUNTER
        DCA FIZCTR      /TO -3
        TAD (-BUZMOD    /SET UP BUZZ COUNTER
        DCA BUZCTR      /TO -5
LOOP,   ISZ CNTR        /READY?
        SKP             /NO: CONTINUE
        JMP I [7600     /YES: RETURN TO OS/8, REPLACE BY
                        /'HLT' IF NOT ON OS/8
CHKFIZ, ISZ FIZCTR      /MULTIPLE OF 3?
        JMP CHKBUZ      /NO: CONTINUE
        TAD FIZSTR      /YES: LOAD ADDRESS OF 'FIZZ'
        JMS STROUT      /PRINT IT TO TTY
        TAD (-FIZMOD    /RELOAD THE
        DCA FIZCTR      /MOD 3 COUNTER
CHKBUZ, ISZ BUZCTR      /MULTIPLE OF 5?
        JMP CHKNUM      /NO: CONTINUE
        TAD BUZSTR      /YES: LOAD ADDRESS OF 'BUZZ'
        JMS STROUT      /PRINT IT TO TTY
        TAD (-BUZMOD    /RELOAD THE
        DCA BUZCTR      /MOD 5 COUNTER
        JMP NXTLIN      /PRINT NEWLINE AND CONTINUE
CHKNUM, TAD FIZCTR      /CHECK WHETHER MOD 3 COUNTER
        TAD (FIZMOD     /IS RELOADED
        SNA             /DID WE JUST PRINT 'FIZZ'?
        JMP NXTLIN      /YES: PRINT NEWLINE AND CONTINUE
        CLA             /ZERO THE AC
NUM,    TAD CNTR        /LOAD THE MAIN NUMBER COUNTER
        TAD (LAST+1     /OFFSET IT TO A POSITIVE VALUE
        JMS NUMOUT      /PRINT IT TO THE TTY
NXTLIN, TAD LINSTR      /LOAD THE ADDRESS OF THE NEWLINE
        JMS STROUT      /PRINT IT TO TTY
        JMP LOOP        /CONTINUE WITH THE NEXT NUMBER
CNTR,   0               /MAIN COUNTER
FIZCTR, 0               /FIZZ COUNTER
BUZCTR, 0               /BUZZ COUNTER

/--------------------------------------------------------
/WRITE ASCII CHARACTER IN AC TO TTY
/PRE : AC=ASCII CHARACTER
/POST: AC=0
/--------------------------------------------------------
CHROUT, .-.
        TLS             /SEND CHARACTER TO TTY
        TSF             /IS TTY READY FOR NEXT CHARACTER?
        JMP .-1         /NO TRY AGAIN
        CLA             /AC=0
        JMP I CHROUT    /RETURN

/--------------------------------------------------------
/WRITE NUL TERMINATED ASCII STRING TO TTY
/PRE : AC=ADDRESS OF STRING MINUS 1
/POST: AC=0
/--------------------------------------------------------
STROUT, .-.
        DCA AIX0        /STORE POINTER IN AUTO INDEX 0
STRLOP, TAD I AIX0      /GET NEXT CHARACTER FROM STRING
        SNA             /SKIP IF NOT EOT
        JMP I STROUT    /RETURN
        JMS CHROUT      /PRINT CHARACTER
        JMP STRLOP      /GO GET NEXT CHARACTER

/--------------------------------------------------------
/WRITE NUMBER IN AC TO TTY AS DECIMAL
/PRE : AC=UNSIGNED NUMBER BETWEEN 0000 AND 7777
/POST: AC=0
/--------------------------------------------------------
NUMOUT, .-.
        SWBA            /SET EAE IN MODE A
        MQL             /MQ=NUM; AC=0
        TAD BUFFER      /LOAD END OF BUFFER
        DCA BUFPTR      /IN BUFPTR
        SKP             /NUM IS ALREADY IN MQ
NUMLOP, MQL             /MQ=NUM; AC=0
        DVI             /MQ=NUM/10; AC=NUM-(NUM/10)*10
        K10             /DECIMAL 10
        TAD ("0         /ADD ASCII ZERO
        DCA I BUFPTR    /STORE CHAR BUFFER, BACK TO FRONT
        CMA             /AC=-1
        TAD BUFPTR      /DECREMENT
        DCA BUFPTR      /BUFFER POINTER
        MQA             /MQ -> AC
        SZA             /READY IF ZERO
        JMP NUMLOP      /GET NEXT DIGIT
        TAD BUFPTR      /LOAD START OF CONVERTED NUMBER
        JMS STROUT      /SEND IT TO TTY
        JMP I NUMOUT    /RETURN
BUFFER, .+4             /ADDRESS OF BUFFER
        *.+4            /RESERVE 4 LOCATIONS (MAX=4095)
        EOT             /END OF BUFFER
BUFPTR, 0               /POINTER IN BUFFER

/--------------------------------------------------------
/STRINGS
/--------------------------------------------------------
FIZSTR, .               /FIZZ STRING
        "F; "I; "Z; "Z; EOT
BUZSTR, .               /BUZZ STRING
        "B; "U; "Z; "Z; EOT
LINSTR, .               /NEWLINE STIRNG
        CR; LF; EOT
        $


# syntax: GAWK -f FIND_THE_INTERSECTION_OF_TWO_LINES.AWK
# converted from Ring
BEGIN {
    intersect(4,0,6,10,0,3,10,7)
    exit(0)
}
function intersect(xa,ya,xb,yb,xc,yc,xd,yd,  errors,x,y) {
    printf("the 1st line passes through (%g,%g) and (%g,%g)\n",xa,ya,xb,yb)
    printf("the 2nd line passes through (%g,%g) and (%g,%g)\n",xc,yc,xd,yd)
    if (xb-xa == 0) { print("error: xb-xa=0") ; errors++ }
    if (xd-xc == 0) { print("error: xd-xc=0") ; errors++ }
    if (errors > 0) {
      print("")
      return(0)
    }
    printf("the two lines are:\n")
    printf("yab=%g+x*%g\n",ya-xa*((yb-ya)/(xb-xa)),(yb-ya)/(xb-xa))
    printf("ycd=%g+x*%g\n",yc-xc*((yd-yc)/(xd-xc)),(yd-yc)/(xd-xc))
    x = ((yc-xc*((yd-yc)/(xd-xc)))-(ya-xa*((yb-ya)/(xb-xa))))/(((yb-ya)/(xb-xa))-((yd-yc)/(xd-xc)))
    printf("x=%g\n",x)
    y = ya-xa*((yb-ya)/(xb-xa))+x*((yb-ya)/(xb-xa))
    printf("yab=%g\n",y)
    printf("ycd=%g\n",yc-xc*((yd-yc)/(xd-xc))+x*((yd-yc)/(xd-xc)))
    printf("intersection: %g,%g\n\n",x,y)
    return(1)
}


<# DEFINE USERDEFINEDROUTINE LITERAL>__FizzBuzz|<# SUPPRESSAUTOMATICWHITESPACE>
<# TEST ISITMODULUSZERO PARAMETER LITERAL>1|3</#>
<# TEST ISITMODULUSZERO PARAMETER LITERAL>1|5</#>
<# ONLYFIRSTOFLASTTWO><# SAY LITERAL>Fizz</#></#>
<# ONLYSECONDOFLASTTWO><# SAY LITERAL>Buzz</#></#>
<# BOTH><# SAY LITERAL>FizzBuzz</#></#>
<# NEITHER><# SAY PARAMETER>1</#></#>
</#></#>
<# ITERATE FORITERATION LITERAL LITERAL>100|<# ACT USERDEFINEDROUTINE POSITION FORITERATION>__FizzBuzz|...</#> </#>


 0 A = 1:B = 2: HOME : VTAB 21: HGR : HCOLOR= 3: FOR L = A TO B: READ X1(L),Y1(L),X2(L),Y2(L): HPLOT X1(L),Y1(L) TO X2(L),Y2(L): NEXT : DATA4,0,6,10,0,3,10,7
 1  GOSUB 5: IF NAN THEN  PRINT "THE LINES DO NOT INTERSECT, THEY ARE EITHER PARALLEL OR CO-INCIDENT."
 2  IF  NOT NAN THEN  PRINT "POINT OF INTERSECTION : "X" "Y
 3  PRINT  CHR$ (13)"HIT ANY KEY TO END PROGRAM": IF  NOT NAN THEN  FOR K = 0 TO 1 STEP 0:C = C = 0: HCOLOR= 3 * C: HPLOT X,Y: FOR I = 1 TO 30:K =  PEEK (49152) > 127: NEXT I,K
 4  GET K$: TEXT : END
 5  FOR L = A TO B:S$(L) = "NAN": IF X1(L) <  > X2(L) THEN S(L) = (Y1(L) - Y2(L)) / (X1(L) - X2(L)):S$(L) =  STR$ (S(L))
 6  NEXT L:NAN = S$(A) = S$(B): IF NAN THEN  RETURN
 7  IF S$(A) = "NAN" AND S$(B) <  > "NAN" THEN X = X1(A):Y = (X1(A) - X1(B)) * S(B) + Y1(B): RETURN
 8  IF S$(B) = "NAN" AND S$(A) <  > "NAN" THEN X = X1(B):Y = (X1(B) - X1(A)) * S(A) + Y1(A): RETURN
 9 X = (S(A) * X1(A) - S(B) * X1(B) + Y1(B) - Y1(A)) / (S(A) - S(B)):Y = S(B) * (X - X1(B)) + Y1(B): RETURN


use strict;
use warnings;
use feature qw(say);

for my $i (1..100) {
    say $i % 15 == 0 ? "FizzBuzz"
      : $i %  3 == 0 ? "Fizz"
      : $i %  5 == 0 ? "Buzz"
      : $i;
}


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

typedef struct{
	double x,y;
}point;

double lineSlope(point a,point b){

	if(a.x-b.x == 0.0)
		return NAN;
	else
		return (a.y-b.y)/(a.x-b.x);
}

point extractPoint(char* str){
	int i,j,start,end,length;
	char* holder;
	point c;

	for(i=0;str[i]!=00;i++){
		if(str[i]=='(')
			start = i;
		if(str[i]==','||str[i]==')')
		{
			end = i;

			length = end - start;

			holder = (char*)malloc(length*sizeof(char));

			for(j=0;j<length-1;j++)
				holder[j] = str[start + j + 1];
			holder[j] = 00;

			if(str[i]==','){
				start = i;
				c.x = atof(holder);
			}
			else
				c.y = atof(holder);
		}
	}

	return c;
}

point intersectionPoint(point a1,point a2,point b1,point b2){
	point c;

	double slopeA = lineSlope(a1,a2), slopeB = lineSlope(b1,b2);

	if(slopeA==slopeB){
		c.x = NAN;
		c.y = NAN;
	}
	else if(isnan(slopeA) && !isnan(slopeB)){
		c.x = a1.x;
		c.y = (a1.x-b1.x)*slopeB + b1.y;
	}
	else if(isnan(slopeB) && !isnan(slopeA)){
		c.x = b1.x;
		c.y = (b1.x-a1.x)*slopeA + a1.y;
	}
	else{
		c.x = (slopeA*a1.x - slopeB*b1.x + b1.y - a1.y)/(slopeA - slopeB);
		c.y = slopeB*(c.x - b1.x) + b1.y;
	}

	return c;
}

int main(int argC,char* argV[])
{
	point c;

	if(argC < 5)
		printf("Usage : %s <four points specified as (x,y) separated by a space>",argV[0]);
	else{
		c = intersectionPoint(extractPoint(argV[1]),extractPoint(argV[2]),extractPoint(argV[3]),extractPoint(argV[4]));

		if(isnan(c.x))
			printf("The lines do not intersect, they are either parallel or co-incident.");
		else
			printf("Point of intersection : (%lf,%lf)",c.x,c.y);
	}

	return 0;
}


constant x = {"%d\n","Fizz\n","Buzz\n","FizzBuzz\n"}
for i=1 to 100 do
    printf(1,x[1+(remainder(i,3)=0)+2*(remainder(i,5)=0)],i)
end for


using System;
using System.Drawing;
public class Program
{
    static PointF FindIntersection(PointF s1, PointF e1, PointF s2, PointF e2) {
        float a1 = e1.Y - s1.Y;
        float b1 = s1.X - e1.X;
        float c1 = a1 * s1.X + b1 * s1.Y;

        float a2 = e2.Y - s2.Y;
        float b2 = s2.X - e2.X;
        float c2 = a2 * s2.X + b2 * s2.Y;

        float delta = a1 * b2 - a2 * b1;
        //If lines are parallel, the result will be (NaN, NaN).
        return delta == 0 ? new PointF(float.NaN, float.NaN)
            : new PointF((b2 * c1 - b1 * c2) / delta, (a1 * c2 - a2 * c1) / delta);
    }

    static void Main() {
        Func<float, float, PointF> p = (x, y) => new PointF(x, y);
        Console.WriteLine(FindIntersection(p(4f, 0f), p(6f, 10f), p(0f, 3f), p(10f, 7f)));
        Console.WriteLine(FindIntersection(p(0f, 0f), p(1f, 1f), p(1f, 2f), p(4f, 5f)));
    }
}


#include <iostream>
#include <cmath>
#include <cassert>
using namespace std;

/** Calculate determinant of matrix:
	[a b]
	[c d]
*/
inline double Det(double a, double b, double c, double d)
{
	return a*d - b*c;
}

/// Calculate intersection of two lines.
///\return true if found, false if not found or error
bool LineLineIntersect(double x1, double y1, // Line 1 start
	double x2, double y2, // Line 1 end
	double x3, double y3, // Line 2 start
	double x4, double y4, // Line 2 end
	double &ixOut, double &iyOut) // Output
{
	double detL1 = Det(x1, y1, x2, y2);
	double detL2 = Det(x3, y3, x4, y4);
	double x1mx2 = x1 - x2;
	double x3mx4 = x3 - x4;
	double y1my2 = y1 - y2;
	double y3my4 = y3 - y4;

	double denom = Det(x1mx2, y1my2, x3mx4, y3my4);
	if(denom == 0.0) // Lines don't seem to cross
	{
		ixOut = NAN;
		iyOut = NAN;
		return false;
	}

	double xnom = Det(detL1, x1mx2, detL2, x3mx4);
	double ynom = Det(detL1, y1my2, detL2, y3my4);
	ixOut = xnom / denom;
	iyOut = ynom / denom;
	if(!isfinite(ixOut) || !isfinite(iyOut)) // Probably a numerical issue
		return false;

	return true; //All OK
}

int main()
{
	// **Simple crossing diagonal lines**

	// Line 1
	double x1=4.0, y1=0.0;
	double x2=6.0, y2=10.0;

	// Line 2
	double x3=0.0, y3=3.0;
	double x4=10.0, y4=7.0;

	double ix = -1.0, iy = -1.0;
	bool result = LineLineIntersect(x1, y1, x2, y2, x3, y3, x4, y4, ix, iy);
	cout << "result " <<  result << "," << ix << "," << iy << endl;

	double eps = 1e-6;
	assert(result == true);
	assert(fabs(ix - 5.0) < eps);
	assert(fabs(iy - 5.0) < eps);
        return 0;
}


module fizzbuzz;

extern printf;

@Integer main [
	var i = 1;
	while (i <= 100) {
		if (i % 15 == 0)
		    printf("FizzBuzz");
		else if (i % 3 == 0)
		    printf("Fizz");
		else if (i % 5 == 0)
		    printf("Buzz");
		else
		    printf("%d", i);

		printf("\n");
		i = i::inc;
	}

	return 0;
]


;; Point is [x y] tuple
(defn compute-line [pt1 pt2]
  (let [[x1 y1] pt1
        [x2 y2] pt2
        m (/ (- y2 y1) (- x2 x1))]
    {:slope  m
     :offset (- y1 (* m x1))}))

(defn intercept [line1 line2]
  (let [x (/ (- (:offset line1) (:offset line2))
             (- (:slope  line2) (:slope  line1)))]
    {:x x
     :y (+ (* (:slope line1) x)
           (:offset line1))}))


;; Point is [x y] tuple
(defun point-of-intersection (x1 y1 x2 y2 x3 y3 x4 y4)
"Find the point of intersection of the lines defined by the points (x1 y1) (x2 y2) and (x3 y3) (x4 y4)"
  (let* ((dx1 (- x2 x1))
         (dx2 (- x4 x3))
         (dy1 (- y2 y1))
         (dy2 (- y4 y3))
         (den (- (* dy1 dx2) (* dy2 dx1))) )
    (unless (zerop den)
  	(list (/ (+ (* (- y3 y1) dx1 dx2) (* x1 dy1 dx2) (* -1 x3 dy2 dx1)) den)
       	      (/ (+ (* (+ x3 x1) dy1 dy2) (* -1 y1 dx1 dy2) (* y3 dx2 dy1)) den) ))))


<?php
for ($i = 1; $i <= 100; $i++)
{
    if (!($i % 15))
        echo "FizzBuzz\n";
    else if (!($i % 3))
        echo "Fizz\n";
    else if (!($i % 5))
        echo "Buzz\n";
    else
        echo "$i\n";
}
?>


import std.stdio;

struct Point {
    real x, y;

    void toString(scope void delegate(const(char)[]) sink) const {
        import std.format;
        sink("{");
        sink.formattedWrite!"%f"(x);
        sink(", ");
        sink.formattedWrite!"%f"(y);
        sink("}");
    }
}

struct Line {
    Point s, e;
}

Point findIntersection(Line l1, Line l2) {
    auto a1 = l1.e.y - l1.s.y;
    auto b1 = l1.s.x - l1.e.x;
    auto c1 = a1 * l1.s.x + b1 * l1.s.y;

    auto a2 = l2.e.y - l2.s.y;
    auto b2 = l2.s.x - l2.e.x;
    auto c2 = a2 * l2.s.x + b2 * l2.s.y;

    auto delta = a1 * b2 - a2 * b1;
    // If lines are parallel, intersection point will contain infinite values
    return Point((b2 * c1 - b1 * c2) / delta, (a1 * c2 - a2 * c1) / delta);
}

void main() {
    auto l1 = Line(Point(4.0, 0.0), Point(6.0, 10.0));
    auto l2 = Line(Point(0f, 3f), Point(10f, 7f));
    writeln(findIntersection(l1, l2));
    l1 = Line(Point(0.0, 0.0), Point(1.0, 1.0));
    l2 = Line(Point(1.0, 2.0), Point(4.0, 5.0));
    writeln(findIntersection(l1, l2));
}


fizzbuzz_map =>
    println(fizzbuzz_map),
    FB = [I : I in 1..100],
    Map = [(3="Fizz"),(5="Buzz"),(15="FizzBuzz")],
    foreach(I in FB, K=V in Map)
       if I mod K == 0 then
          FB[I] := V
       end
    end,
    println(FB).


(*
Find the point of intersection of 2 lines.
Nigel Galloway May 20th., 2017
*)
type Line={a:float;b:float;c:float} member N.toS=sprintf "%.2fx + %.2fy = %.2f" N.a N.b N.c
let intersect (n:Line) g = match (n.a*g.b-g.a*n.b) with
                           |0.0 ->printfn "%s does not intersect %s" n.toS g.toS
                           |ng  ->printfn "%s intersects %s at x=%.2f y=%.2f" n.toS g.toS ((g.b*n.c-n.b*g.c)/ng) ((n.a*g.c-g.a*n.c)/ng)
let fn (i,g) (e,l) = {a=g-l;b=e-i;c=(e-i)*g+(g-l)*i}
intersect (fn (4.0,0.0) (6.0,10.0)) (fn (0.0,3.0) (10.0,7.0))
intersect {a=3.18;b=4.23;c=7.13} {a=6.36;b=8.46;c=9.75}


USING: arrays combinators.extras kernel math
math.matrices.laplace math.vectors prettyprint sequences ;

: det ( pt pt -- x ) 2array determinant ;

: numerator ( x y pt pt quot -- z )
    [email protected] swapd [ 2array ] [email protected] det ; inline

: intersection ( pt pt pt pt -- pt )
    [ [ det ] [email protected] ]
    [ [ v- ] [email protected] ] 4bi
    [ [ first ] numerator ]
    [ [ second ] numerator ]
    [ det 2nip ] 4tri
    dup zero? [ 3drop { 0/0. 0/0. } ]
    [ tuck [ / ] [email protected] 2array ] if ;

{ 4 0 } { 6 10 } { 0 3 } { 10 7 } intersection .
{ 4 0 } { 6 10 } { 0 3 } { 10 7+1/10 } intersection .
{ 0 0 } { 1 1 } { 1 2 } { 4 5 } intersection .


(for N 100
   (prinl
      (or (pack (at (0 . 3) "Fizz") (at (0 . 5) "Buzz")) N) ) )

# Above, we simply count till 100 'prin'-ting number 'at' 3rd ('Fizz'), 5th ('Buzz') and 'pack'-ing 15th number ('FizzBuzz').
# Rest of the times 'N' is printed as it loops in 'for'.


program intersect_two_lines
  implicit none

  type point
    real::x,y
  end type point

  integer, parameter :: n = 4
  type(point)        :: p(n)

  p(1)%x = 4; p(1)%y = 0; p(2)%x = 6;  p(2)%y = 10 ! fist line
  p(3)%x = 0; p(3)%y = 3; p(4)%x = 10; p(4)%y = 7  ! second line

  call intersect(p, n)

  contains

  subroutine intersect(p,m)
  integer, intent(in)       :: m
  type(point), intent(in)   :: p(m)
  integer   :: i
  real      :: a(2), b(2) ! y = a*x + b, for each line
  real      :: x, y       ! intersect point
  real      :: dx,dy      ! working variables

  do i = 1, 2
    dx = p(2*i-1)%x - p(2*i)%x
    dy = p(2*i-1)%y - p(2*i)%y
    if( dx == 0.) then    ! in case this line is of the form y = b
        a(i) = 0.
        b(i) = p(2*i-1)%y
    else
        a(i)= dy / dx
        b(i) = p(2*i-1)%y - a(i)*p(2*i-1)%x
    endif
  enddo

  if( a(1) - a(2) == 0. ) then
    write(*,*)"lines are not intersecting"
    return
  endif

  x = ( b(2) - b(1) ) / ( a(1) - a(2) )
  y = a(1) * x + b(1)
  write(*,*)x,y
  end subroutine intersect
end program intersect_two_lines


int main(){
   for(int i = 1; i <= 100; i++) {
      if(i % 15 == 0) {
         write("FizzBuzz\n");
      } else if(i % 3 == 0) {
         write("Fizz\n");
      } else if(i % 5 == 0) {
         write("Buzz\n");
      } else {
         write(i + "\n");
      }
   }
}


' version 16-08-2017
' compile with: fbc -s console
#Define NaN 0 / 0   ' FreeBASIC returns -1.#IND

Type _point_
    As Double x, y
End Type

Function l_l_intersect(s1 As _point_, e1 As _point_, s2 As _point_, e2 As _point_) As _point_

    Dim As Double a1 = e1.y - s1.y
    Dim As Double b1 = s1.x - e1.x
    Dim As Double c1 = a1 * s1.x + b1 * s1.y
    Dim As Double a2 = e2.y - s2.y
    Dim As Double b2 = s2.x - e2.x
    Dim As Double c2 = a2 * s2.x + b2 * s2.y
    Dim As Double det = a1 * b2 - a2 * b1

    If det = 0 Then
        Return Type(NaN, NaN)
    Else
        Return Type((b2 * c1 - b1 * c2) / det, (a1 * c2 - a2 * c1) / det)
    End If

End Function

' ------=< MAIN >=------

Dim As _point_ s1, e1, s2, e2, answer

s1.x = 4.0 : s1.y = 0.0 : e1.x =  6.0 : e1.y = 10.0  ' start and end of first line
s2.x = 0.0 : s2.y = 3.0 : e2.x = 10.0 : e2.y =  7.0  ' start and end of second line
answer = l_l_intersect(s1, e1, s2, e2)
Print answer.x, answer.y

s1.x = 0.0 : s1.y = 0.0 : e1.x =  0.0 : e1.y =  0.0  ' start and end of first line
s2.x = 0.0 : s2.y = 3.0 : e2.x = 10.0 : e2.y =  7.0  ' start and end of second line
answer = l_l_intersect(s1, e1, s2, e2)
Print answer.x, answer.y

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


C  :i = 0
*loop
C  :i = i + 1
J ( i > 100 )    : *finished
C  :modulo = i % 15
J ( modulo = 0 ) : *fizzbuzz
C  :modulo = i % 3
J ( modulo = 0 ) : *fizz
C  :modulo = i % 5
J ( modulo = 0 ) : *buzz
T  :#i
J  : *loop
*fizzbuzz
T  :FizzBuzz
J  : *loop
*fizz
T  :Fizz
J  : *loop
*buzz
T  :Buzz
J  : *loop
*finished
END:


package main

import (
	"fmt"
	"errors"
)

type Point struct {
	x float64
	y float64
}

type Line struct {
	slope float64
	yint float64
}

func CreateLine (a, b Point) Line {
	slope := (b.y-a.y) / (b.x-a.x)
	yint := a.y - slope*a.x
	return Line{slope, yint}
}

func EvalX (l Line, x float64) float64 {
	return l.slope*x + l.yint
}

func Intersection (l1, l2 Line) (Point, error) {
	if l1.slope == l2.slope {
		return Point{}, errors.New("The lines do not intersect")
	}
	x := (l2.yint-l1.yint) / (l1.slope-l2.slope)
	y := EvalX(l1, x)
	return Point{x, y}, nil
}

func main() {
	l1 := CreateLine(Point{4, 0}, Point{6, 10})
	l2 := CreateLine(Point{0, 3}, Point{10, 7})
	if result, err := Intersection(l1, l2); err == nil {
		fmt.Println(result)
	} else {
		fmt.Println("The lines do not intersect")
	}
}


class Intersection {
    private static class Point {
        double x, y

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

        @Override
        String toString() {
            return "($x, $y)"
        }
    }

    private static class Line {
        Point s, e

        Line(Point s, Point e) {
            this.s = s
            this.e = e
        }
    }

    private static Point findIntersection(Line l1, Line l2) {
        double a1 = l1.e.y - l1.s.y
        double b1 = l1.s.x - l1.e.x
        double c1 = a1 * l1.s.x + b1 * l1.s.y

        double a2 = l2.e.y - l2.s.y
        double b2 = l2.s.x - l2.e.x
        double c2 = a2 * l2.s.x + b2 * l2.s.y

        double delta = a1 * b2 - a2 * b1
        return new Point((b2 * c1 - b1 * c2) / delta, (a1 * c2 - a2 * c1) / delta)
    }

    static void main(String[] args) {
        Line l1 = new Line(new Point(4, 0), new Point(6, 10))
        Line l2 = new Line(new Point(0, 3), new Point(10, 7))
        println(findIntersection(l1, l2))

        l1 = new Line(new Point(0, 0), new Point(1, 1))
        l2 = new Line(new Point(1, 2), new Point(4, 5))
        println(findIntersection(l1, l2))
    }
}


.sub main :main
  .local int f
  .local int mf
  .local int skipnum
  f = 1
LOOP:
  if f > 100 goto DONE
  skipnum = 0
  mf = f % 3
  if mf == 0 goto FIZZ
FIZZRET:
  mf = f % 5
  if mf == 0 goto BUZZ
BUZZRET:
  if skipnum > 0 goto SKIPNUM
  print f
SKIPNUM:
  print "\n"
  inc f
  goto LOOP
  end
FIZZ:
  print "Fizz"
  inc skipnum
  goto FIZZRET
  end
BUZZ:
  print "Buzz"
  inc skipnum
  goto BUZZRET
  end
DONE:
  end
.end


type Line = (Point, Point)

type Point = (Float, Float)

intersection :: Line -> Line -> Either String Point
intersection ab pq =
  case determinant of
    0 -> Left "(Parallel lines – no intersection)"
    _ ->
      let [abD, pqD] = (\(a, b) -> diff ([fst, snd] <*> [a, b])) <$> [ab, pq]
          [ix, iy] =
            [\(ab, pq) -> diff [abD, ab, pqD, pq] / determinant] <*>
            [(abDX, pqDX), (abDY, pqDY)]
      in Right (ix, iy)
  where
    delta f x = f (fst x) - f (snd x)
    diff [a, b, c, d] = a * d - b * c
    [abDX, pqDX, abDY, pqDY] = [delta fst, delta snd] <*> [ab, pq]
    determinant = diff [abDX, abDY, pqDX, pqDY]

-- TEST ----------------------------------------------------------------
ab :: Line
ab = ((4.0, 0.0), (6.0, 10.0))

pq :: Line
pq = ((0.0, 3.0), (10.0, 7.0))

interSection :: Either String Point
interSection = intersection ab pq

main :: IO ()
main =
  putStrLn $
  case interSection of
    Left x -> x
    Right x -> show x


det=: -/ .*   NB. calculate determinant
findIntersection=: (det ,."1 [: |: -/"2) %&det -/"2


do i = 1 to 100;
   select;
      when (mod(i,15) = 0) put skip list ('FizzBuzz');
      when (mod(i,3)  = 0) put skip list ('Fizz');
      when (mod(i,5)  = 0) put skip list ('Buzz');
      otherwise put skip list (i);
   end;
end;


public class Intersection {
    private static class Point {
        double x, y;

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

        @Override
        public String toString() {
            return String.format("{%f, %f}", x, y);
        }
    }

    private static class Line {
        Point s, e;

        Line(Point s, Point e) {
            this.s = s;
            this.e = e;
        }
    }

    private static Point findIntersection(Line l1, Line l2) {
        double a1 = l1.e.y - l1.s.y;
        double b1 = l1.s.x - l1.e.x;
        double c1 = a1 * l1.s.x + b1 * l1.s.y;

        double a2 = l2.e.y - l2.s.y;
        double b2 = l2.s.x - l2.e.x;
        double c2 = a2 * l2.s.x + b2 * l2.s.y;

        double delta = a1 * b2 - a2 * b1;
        return new Point((b2 * c1 - b1 * c2) / delta, (a1 * c2 - a2 * c1) / delta);
    }

    public static void main(String[] args) {
        Line l1 = new Line(new Point(4, 0), new Point(6, 10));
        Line l2 = new Line(new Point(0, 3), new Point(10, 7));
        System.out.println(findIntersection(l1, l2));

        l1 = new Line(new Point(0, 0), new Point(1, 1));
        l2 = new Line(new Point(1, 2), new Point(4, 5));
        System.out.println(findIntersection(l1, l2));
    }
}


100H:

/* DECLARE OUTPUT IN TERMS OF CP/M -
   PL/M DOES NOT COME WITH ANY STANDARD LIBRARY */
BDOS: PROCEDURE(FUNC, ARG);
    DECLARE FUNC BYTE, ARG ADDRESS;
    GO TO 5;
END BDOS;

PUT$STRING: PROCEDURE(STR);
    DECLARE STR ADDRESS;
    CALL BDOS(9, STR);
    CALL BDOS(9, .(13,10,'$'));
END PUT$STRING;

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

/* FIZZBUZZ */
DECLARE N BYTE;
DO N = 1 TO 100;
    IF N MOD 15 = 0 THEN
        CALL PUT$STRING(.'FIZZBUZZ$');
    ELSE IF N MOD 5 = 0 THEN
        CALL PUT$STRING(.'BUZZ$');
    ELSE IF N MOD 3 = 0 THEN
        CALL PUT$STRING(.'FIZZ$');
    ELSE
        CALL PUT$NUMBER(N);
END;

/* EXIT TO CP/M */
CALL BDOS(0,0);
EOF


(() => {
    'use strict';
    // INTERSECTION OF TWO LINES ----------------------------------------------

    // intersection :: Line -> Line -> Either String (Float, Float)
    const intersection = (ab, pq) => {
        const
            delta = f => x => f(fst(x)) - f(snd(x)),
            [abDX, pqDX, abDY, pqDY] = apList(
                [delta(fst), delta(snd)], [ab, pq]
            ),
            determinant = abDX * pqDY - abDY * pqDX;

        return determinant !== 0 ? Right((() => {
            const [abD, pqD] = map(
                ([a, b]) => fst(a) * snd(b) - fst(b) * snd(a),
                [ab, pq]
            );
            return apList(
                [([pq, ab]) =>
                    (abD * pq - ab * pqD) / determinant
                ], [
                    [pqDX, abDX],
                    [pqDY, abDY]
                ]
            );
        })()) : Left('(Parallel lines – no intersection)');
    };

    // GENERIC FUNCTIONS ------------------------------------------------------

    // Left :: a -> Either a b
    const Left = x => ({
        type: 'Either',
        Left: x
    });

    // Right :: b -> Either a b
    const Right = x => ({
        type: 'Either',
        Right: x
    });

    // A list of functions applied to a list of arguments
    // <*> :: [(a -> b)] -> [a] -> [b]
    const apList = (fs, xs) => //
        [].concat.apply([], fs.map(f => //
            [].concat.apply([], xs.map(x => [f(x)]))));

    // fst :: (a, b) -> a
    const fst = tpl => tpl[0];

    // map :: (a -> b) -> [a] -> [b]
    const map = (f, xs) => xs.map(f);

    // snd :: (a, b) -> b
    const snd = tpl => tpl[1];

    // show :: a -> String
    const show = x => JSON.stringify(x); //, null, 2);

    // TEST --------------------------------------------------

    // lrIntersection ::Either String Point
    const lrIntersection = intersection([
        [4.0, 0.0],
        [6.0, 10.0]
    ], [
        [0.0, 3.0],
        [10.0, 7.0]
    ]);
    return show(lrIntersection.Left || lrIntersection.Right);
})();


BEGIN
  FOR i IN 1 .. 100
  LOOP
    CASE
    WHEN MOD(i, 15) = 0 THEN
      DBMS_OUTPUT.put_line('FizzBuzz');
    WHEN MOD(i, 5) = 0 THEN
      DBMS_OUTPUT.put_line('Buzz');
    WHEN MOD(i, 3) = 0 THEN
      DBMS_OUTPUT.put_line('Fizz');
    ELSE
      DBMS_OUTPUT.put_line(i);
    END CASE;
  END LOOP;
END;


# determinant of 2x2 matrix
def det(a;b;c;d): a*d - b*c ;

# Input: an array representing a line (L1)
# Output: the intersection of L1 and L2 unless the lines are judged to be parallel
# This implementation uses "destructuring" to assign local variables
def lineIntersection(L2):
  .    as [[$ax,$ay], [$bx,$by]]
  | L2 as [[$cx,$cy], [$dx,$dy]]
  | {detAB: det($ax;$ay; $bx;$by),
     detCD: det($cx;$cy; $dx;$dy),
     abDx: ($ax - $bx),
     cdDx: ($cx - $dx),
     abDy: ($ay - $by),
     cdDy: ($cy - $dy)}
  | . + {xnom:  det(.detAB;.abDx;.detCD;.cdDx),
         ynom:  det(.detAB;.abDy;.detCD;.cdDy),
         denom: det(.abDx; .abDy;.cdDx; .cdDy) }
  | if (.denom|length < 10e-6)  # length/0 emits the absolute value
    then error("lineIntersect: parallel lines")
    else [.xnom/.denom, .ynom/.denom]
    end ;


struct Point{T}
    x::T
    y::T
end

struct Line{T}
    s::Point{T}
    e::Point{T}
end

function intersection(l1::Line{T}, l2::Line{T}) where T<:Real
    a1 = l1.e.y - l1.s.y
    b1 = l1.s.x - l1.e.x
    c1 = a1 * l1.s.x + b1 * l1.s.y

    a2 = l2.e.y - l2.s.y
    b2 = l2.s.x - l2.e.x
    c2 = a2 * l2.s.x + b2 * l2.s.y

    Δ = a1 * b2 - a2 * b1
    # If lines are parallel, intersection point will contain infinite values
    return Point((b2 * c1 - b1 * c2) / Δ, (a1 * c2 - a2 * c1) / Δ)
end

l1 = Line(Point{Float64}(4, 0), Point{Float64}(6, 10))
l2 = Line(Point{Float64}(0, 3), Point{Float64}(10, 7))
println(intersection(l1, l2))

l1 = Line(Point{Float64}(0, 0), Point{Float64}(1, 1))
l2 = Line(Point{Float64}(1, 2), Point{Float64}(4, 5))
println(intersection(l1, l2))


// version 1.1.2

class PointF(val x: Float, val y: Float) {
    override fun toString() = "{$x, $y}"
}

class LineF(val s: PointF, val e: PointF)

fun findIntersection(l1: LineF, l2: LineF): PointF {
    val a1 = l1.e.y - l1.s.y
    val b1 = l1.s.x - l1.e.x
    val c1 = a1 * l1.s.x + b1 * l1.s.y

    val a2 = l2.e.y - l2.s.y
    val b2 = l2.s.x - l2.e.x
    val c2 = a2 * l2.s.x + b2 * l2.s.y

    val delta = a1 * b2 - a2 * b1
    // If lines are parallel, intersection point will contain infinite values
    return PointF((b2 * c1 - b1 * c2) / delta, (a1 * c2 - a2 * c1) / delta)
}

fun main(args: Array<String>) {
    var l1 = LineF(PointF(4f, 0f), PointF(6f, 10f))
    var l2 = LineF(PointF(0f, 3f), PointF(10f, 7f))
    println(findIntersection(l1, l2))
    l1 = LineF(PointF(0f, 0f), PointF(1f, 1f))
    l2 = LineF(PointF(1f, 2f), PointF(4f, 5f))
    println(findIntersection(l1, l2))
}


use "collections"

actor Main
  new create(env: Env) =>
    for i in Range[I32](1, 100) do
      env.out.print(fizzbuzz(i))
    end

  fun fizzbuzz(n: I32): String =>
    if (n % 15) == 0 then
      "FizzBuzz"
    elseif (n % 5) == 0 then
      "Buzz"
    elseif (n % 3) == 0 then
      "Fizz"
    else
      n.string()
    end


function intersection (s1, e1, s2, e2)
  local d = (s1.x - e1.x) * (s2.y - e2.y) - (s1.y - e1.y) * (s2.x - e2.x)
  local a = s1.x * e1.y - s1.y * e1.x
  local b = s2.x * e2.y - s2.y * e2.x
  local x = (a * (s2.x - e2.x) - (s1.x - e1.x) * b) / d
  local y = (a * (s2.y - e2.y) - (s1.y - e1.y) * b) / d
  return x, y
end

local line1start, line1end = {x = 4, y = 0}, {x = 6, y = 10}
local line2start, line2end = {x = 0, y = 3}, {x = 10, y = 7}
print(intersection(line1start, line1end, line2start, line2end))


Module Lineintersection (lineAtuple, lineBtuple) {
	class line {
	private:
		slop, k
	public:
		function f(x) {
			=x*.slop-.k
		}
		function intersection(b as line) {
			if b.slop==.slop then
				=(,)
			else
				x1=(.k-b.k)/(.slop-b.slop)
				=(x1, .f(x1))
			end if
		}
	Class:
		module line {
			read  x1, y1, x2, y2
			if x1==x2 then error "wrong input"
			if x1>x2 then swap x1,x2 : swap y1, y2
			.slop<=(y1-y2)/(x1-x2)
			.k<=x1*.slop-y1
		}
	}
	M=line(!lineAtuple)
	N=line(!lineBtuple)
	Print M.intersection(N)
}
Lineintersection (4,0,6,10), (0,3,10,7)  ' print   5  5


lvars str;
for i from 1 to 100 do
  if i rem 15 = 0 then
    'FizzBuzz' -> str;
  elseif i rem 3 = 0 then
    'Fizz' -> str;
  elseif i rem 5 = 0 then
    'Buzz' -> str;
  else
    '' >< i -> str;
  endif;
  printf(str, '%s\n');
endfor;


with(geometry):
line(L1, [point(A,[4,0]), point(B,[6,10])]):
line(L2, [point(C,[0,3]), point(E,[10,7])]):
coordinates(intersection(x,L1,L2));


RegionIntersection[
    InfiniteLine[{{4, 0}, {6, 10}}],
    InfiniteLine[{{0, 3}, {10, 7}}]
]


function cross=intersection(line1,line2)
    a=polyfit(line1(:,1),line1(:,2),1);
    b=polyfit(line2(:,1),line2(:,2),1);
    cross=[a(1) -1; b(1) -1]\[-a(2);-b(2)];
end


MODULE LineIntersection;
FROM RealStr IMPORT RealToStr;
FROM Terminal IMPORT WriteString,WriteLn,ReadChar;

TYPE
    Point = RECORD
        x,y : REAL;
    END;

PROCEDURE PrintPoint(p : Point);
VAR buf : ARRAY[0..31] OF CHAR;
BEGIN
    WriteString("{");
    RealToStr(p.x, buf);
    WriteString(buf);
    WriteString(", ");
    RealToStr(p.y, buf);
    WriteString(buf);
    WriteString("}");
END PrintPoint;

TYPE
    Line = RECORD
        s,e : Point;
    END;

PROCEDURE FindIntersection(l1,l2 : Line) : Point;
VAR a1,b1,c1,a2,b2,c2,delta : REAL;
BEGIN
    a1 := l1.e.y - l1.s.y;
    b1 := l1.s.x - l1.e.x;
    c1 := a1 * l1.s.x + b1 * l1.s.y;

    a2 := l2.e.y - l2.s.y;
    b2 := l2.s.x - l2.e.x;
    c2 := a2 * l2.s.x + b2 * l2.s.y;

    delta := a1 * b2 - a2 * b1;
    RETURN Point{(b2 * c1 - b1 * c2) / delta, (a1 * c2 - a2 * c1) / delta};
END FindIntersection;

VAR
    l1,l2 : Line;
    result : Point;
BEGIN
    l1 := Line{{4.0,0.0}, {6.0,10.0}};
    l2 := Line{{0.0,3.0}, {10.0,7.0}};
    PrintPoint(FindIntersection(l1,l2));
    WriteLn;

    l1 := Line{{0.0,0.0}, {1.0,1.0}};
    l2 := Line{{1.0,2.0}, {4.0,5.0}};
    PrintPoint(FindIntersection(l1,l2));
    WriteLn;

    ReadChar;
END LineIntersection.


1 1 100 {
	/c false def
	dup 3 mod 0 eq { (Fizz) print /c true def } if
	dup 5 mod 0 eq { (Buzz) print /c true def } if
    c {pop}{(   ) cvs print} ifelse
    (\n) print
} for


type
  Line = tuple
    slope: float
    yInt: float
  Point = tuple
    x: float
    y: float

func createLine(a, b: Point): Line =
  result.slope = (b.y - a.y) / (b.x - a.x)
  result.yInt = a.y - result.slope * a.x

func evalX(line: Line, x: float): float =
  line.slope * x + line.yInt

func intersection(line1, line2: Line): Point =
  let x = (line2.yInt - line1.yInt) / (line1.slope - line2.slope)
  let y = evalX(line1, x)
  (x, y)

var line1 = createLine((4.0, 0.0), (6.0, 10.0))
var line2 = createLine((0.0, 3.0), (10.0, 7.0))
echo intersection(line1, line2)
line1 = createLine((0.0, 0.0), (1.0, 1.0))
line2 = createLine((1.0, 2.0), (4.0, 5.0))
echo intersection(line1, line2)


1 to 100 (a):
  if (a % 15 == 0):
    'FizzBuzz'.
  elsif (a % 3 == 0):
    'Fizz'.
  elsif (a % 5 == 0):
    'Buzz'.
  else: a. string print
  "\n" print.


with javascript_semantics
enum X, Y

function abc(sequence s,e)
-- yeilds {a,b,c}, corresponding to ax+by=c
    atom a = e[Y]-s[Y], b = s[X]-e[X], c = a*s[X]+b*s[Y]
    return {a,b,c}
end function

procedure intersect(sequence s1, e1, s2, e2)
    atom {a1,b1,c1} = abc(s1,e1),
         {a2,b2,c2} = abc(s2,e2),
         delta = a1*b2 - a2*b1,
         x = b2*c1 - b1*c2,
         y = a1*c2 - a2*c1
    ?iff(delta=0?"parallel lines/do not intersect"
                :{x/delta, y/delta})
end procedure

intersect({4,0},{6,10},{0,3},{10,7})        -- {5,5}
intersect({4,0},{6,10},{0,3},{10,7.1})      -- {5.010893246,5.054466231}
intersect({0,0},{0,0},{0,3},{10,7})         -- "parallel lines/do not intersect"
intersect({0,0},{1,1},{1,2},{4,5})          -- "parallel lines/do not intersect"
intersect({1,-1},{4,4},{2,5},{3,-2})        -- {2.5,1.5}


void setup() {
  // test lineIntersect() with visual and textual output
  float lineA[] = {4, 0, 6, 10};  // try 4, 0, 6, 4
  float lineB[] = {0, 3, 10, 7};  // for non intersecting test
  PVector pt = lineInstersect(lineA[0], lineA[1], lineA[2], lineA[3],
                              lineB[0], lineB[1], lineB[2], lineB[3]);
  scale(9);
  line(lineA[0], lineA[1], lineA[2], lineA[3]);
  line(lineB[0], lineB[1], lineB[2], lineB[3]);
  if (pt != null) {
    stroke(255);
    point(pt.x, pt.y);
    println(pt.x, pt.y);
  } else {
    println("No point");
  }
}

PVector lineInstersect(float Ax1, float Ay1, float Ax2, float Ay2,
  float  Bx1, float By1, float Bx2, float By2) {
  // returns null if there is no intersection
  float uA, uB;
  float d = ((By2 - By1) * (Ax2 - Ax1) - (Bx2 - Bx1) * (Ay2 - Ay1));
  if (d != 0) {
    uA = ((Bx2 - Bx1) * (Ay1 - By1) - (By2 - By1) * (Ax1 - Bx1)) / d;
    uB = ((Ax2 - Ax1) * (Ay1 - By1) - (Ay2 - Ay1) * (Ax1 - Bx1)) / d;
  } else {
    return null;
  }
  if (0 > uA || uA > 1 || 0 > uB || uB > 1) {
    return null;
  }
  float x = Ax1 + uA * (Ax2 - Ax1);
  float y = Ay1 + uA * (Ay2 - Ay1);
  return new PVector(x, y);
}


for (int i = 0; i < width; i++) {
  if (i % 3 == 0 && i % 5 == 0) {
    stroke(255, 255, 0);
    println("FizzBuzz!");
  }
  else if (i % 5 == 0) {
    stroke(0, 255, 0);
    println("Buzz");
  }
  else if (i % 3 == 0) {
    stroke(255, 0, 0);
    println("Fizz");
  }
  else {
    stroke(0, 0, 255);
    println(i);
  }
  line(i, 0, i, height);
}


def line_intersect(Ax1, Ay1, Ax2, Ay2, Bx1, By1, Bx2, By2):
    """ returns a (x, y) tuple or None if there is no intersection """
    d = (By2 - By1) * (Ax2 - Ax1) - (Bx2 - Bx1) * (Ay2 - Ay1)
    if d:
        uA = ((Bx2 - Bx1) * (Ay1 - By1) - (By2 - By1) * (Ax1 - Bx1)) / d
        uB = ((Ax2 - Ax1) * (Ay1 - By1) - (Ay2 - Ay1) * (Ax1 - Bx1)) / d
    else:
        return
    if not(0 <= uA <= 1 and 0 <= uB <= 1):
        return
    x = Ax1 + uA * (Ax2 - Ax1)
    y = Ay1 + uA * (Ay2 - Ay1)

    return x, y

if __name__ == '__main__':
    (a, b), (c, d) = (4, 0), (6, 10)  # try (4, 0), (6, 4)
    (e, f), (g, h) = (0, 3), (10, 7)  # for non intersecting test
    pt = line_intersect(a, b, c, d, e, f, g, h)
    print(pt)


#lang racket/base
(define (det a b c d) (- (* a d) (* b c))) ; determinant

(define (line-intersect ax ay bx by cx cy dx dy) ; --> (values x y)
  (let* ((det.ab (det ax ay bx by))
         (det.cd (det cx cy dx dy))
         (abΔx (- ax bx))
         (cdΔx (- cx dx))
         (abΔy (- ay by))
         (cdΔy (- cy dy))
         (xnom (det det.ab abΔx det.cd cdΔx))
         (ynom (det det.ab abΔy det.cd cdΔy))
         (denom (det abΔx abΔy cdΔx cdΔy)))
    (when (zero? denom)
      (error 'line-intersect "parallel lines"))
    (values (/ xnom denom) (/ ynom denom))))

(module+ test (line-intersect 4 0 6 10
                              0 3 10 7))


fizzbuzz :-
        foreach(between(1, 100, X), print_item(X)).

print_item(X) :-
        (  0 is X mod 15
        -> print('FizzBuzz')
        ;  0 is X mod 3
        -> print('Fizz')
        ;  0 is X mod 5
        -> print('Buzz')
        ;  print(X)
        ),
        nl.


;beginning of your program
lda #$BE
sta $0100
lda #$EF
sta $0101

ldx #$ff
txs      ;stack pointer is set to $FF

;later...

lda $0100 ;if this no longer equals $BE the stack has overflowed
cmp #$BE
bne StackHasOverflowed


sub intersection (Real $ax, Real $ay, Real $bx, Real $by,
                  Real $cx, Real $cy, Real $dx, Real $dy ) {

    sub term:<|AB|> { determinate($ax, $ay, $bx, $by) }
    sub term:<|CD|> { determinate($cx, $cy, $dx, $dy) }

    my $ΔxAB = $ax - $bx;
    my $ΔyAB = $ay - $by;
    my $ΔxCD = $cx - $dx;
    my $ΔyCD = $cy - $dy;

    my $x-numerator = determinate( |AB|, $ΔxAB, |CD|, $ΔxCD );
    my $y-numerator = determinate( |AB|, $ΔyAB, |CD|, $ΔyCD );
    my $denominator = determinate( $ΔxAB, $ΔyAB, $ΔxCD, $ΔyCD );

    return 'Lines are parallel' if $denominator == 0;

    ($x-numerator/$denominator, $y-numerator/$denominator);
}

sub determinate ( Real $a, Real $b, Real $c, Real $d ) { $a * $d - $b * $c }

# TESTING
say 'Intersection point: ', intersection( 4,0, 6,10, 0,3, 10,7 );
say 'Intersection point: ', intersection( 4,0, 6,10, 0,3, 10,7.1 );
say 'Intersection point: ', intersection( 0,0, 1,1, 1,2, 4,5 );


fun fizzbuzz(n :: NumPositive) -> String:
  doc: ```For positive input which is multiples of three return 'Fizz', for the multiples of five return 'Buzz'.
  For numbers which are multiples of both three and five return 'FizzBuzz'. Otherwise, return the number itself.```
  ask:
    | num-modulo(n, 15) == 0 then: "FizzBuzz"
    | num-modulo(n, 3) == 0 then: "Fizz"
    | num-modulo(n, 5) == 0 then: "Buzz"
    | otherwise: num-to-string(n)
  end
where:
  fizzbuzz(1) is "1"
  fizzbuzz(101) is "101"
  fizzbuzz(45) is "FizzBuzz"
  fizzbuzz(33) is "Fizz"
  fizzbuzz(25) is "Buzz"
end

range(1, 101).map(fizzbuzz).each(print)


	org	100h
	lxi	b,0		; BC holds the amount of calls
	call	recur		; Call the recursive routine
	;;;	BC now holds the maximum amount of recursive calls one
	;;;	can make, and the stack is back to the beginning.
	;;;	Print the value in BC to the console. The stack is freed by ret
	;;;	so push and pop can be used.
	;;;	Make number into ASCII string
	lxi	h,num
	push	h
	mov	h,b
	mov	l,c
	lxi	b,-10
dgt:	lxi	d,-1
clcdgt:	inx	d
	dad	b
	jc	clcdgt
	mov	a,l
	adi	10+'0'
	xthl
	dcx	h
	mov	m,a
	xthl
	xchg
	mov	a,h
	ora	l
	jnz	dgt
	;;;	Use CP/M routine to print the string
	pop	d
	mvi	c,9
	call 	5
	rst	0
	;;;	Recursive routine
recur:	inx	b		; Count the call
	lxi	d,-GUARD	; See if the guard is intact (stack not full)
	lhld	guard		; (subtract the original value from the
	dad	d		; current one)
	mov	a,h		; If so, the answer should be zero
	ora	l
	cz	recur		; If it is, do another recursive call
	ret			; Return
	;;;	Placeholder for numeric output
	db	'00000'
num:	db	'$'
	;;;	The program doesn't need any memory after this location,
	;;;	so all memory beyond here is free for use by the stack.
	;;;	If the guard is overwritten, the stack has overflowed.
GUARD:	equ	$+2		; Make sure it is not a valid return address
guard:	dw	GUARD


(defun recursion-limit (x)
   (if (zp x)
       0
       (prog2$ (cw "~x0~%" x)
               (1+ (recursion-limit (1+ x))))))


with Ada.Text_IO;  use Ada.Text_IO;

procedure Test_Recursion_Depth is
   function Recursion (Depth : Positive) return Positive is
   begin
      return Recursion (Depth + 1);
   exception
      when Storage_Error =>
         return Depth;
   end Recursion;
begin
   Put_Line ("Recursion depth on this system is" & Integer'Image (Recursion (1)));
end Test_Recursion_Depth;


# Project : Find the intersection of two lines

xa=4
ya=0
xb=6
yb=10
xc=0
yc=3
xd=10
yd=7
see "the two lines are:" + nl
see "yab=" + (ya-xa*((yb-ya)/(xb-xa))) + "+x*" + ((yb-ya)/(xb-xa)) + nl
see "ycd=" + (yc-xc*((yd-yc)/(xd-xc))) + "+x*" + ((yd-yc)/(xd-xc)) + nl
x=((yc-xc*((yd-yc)/(xd-xc)))-(ya-xa*((yb-ya)/(xb-xa))))/(((yb-ya)/(xb-xa))-((yd-yc)/(xd-xc)))
see "x=" + x + nl
y=ya-xa*((yb-ya)/(xb-xa))+x*((yb-ya)/(xb-xa))
see "yab=" + y + nl
see "ycd=" + (yc-xc*((yd-yc)/(xd-xc))+x*((yd-yc)/(xd-xc))) + nl
see "intersection: " + x + "," + y + nl


Point = Struct.new(:x, :y)

class Line
  attr_reader :a, :b

  def initialize(point1, point2)
    @a = (point1.y - point2.y).fdiv(point1.x - point2.x)
    @b = point1.y - @a*point1.x
  end

  def intersect(other)
    return nil if @a == other.a
    x = (other.b - @b).fdiv(@a - other.a)
    y = @a*x + @b
    Point.new(x,y)
  end

  def to_s
    "y = #{@a}x + #{@b}"
  end

end

l1 = Line.new(Point.new(4, 0), Point.new(6, 10))
l2 = Line.new(Point.new(0, 3), Point.new(10, 7))

puts "Line #{l1} intersects line #{l2} at #{l1.intersect(l2)}."


#[derive(Copy, Clone, Debug)]
struct Point {
    x: f64,
    y: f64,
}

impl Point {
    pub fn new(x: f64, y: f64) -> Self {
        Point { x, y }
    }
}

#[derive(Copy, Clone, Debug)]
struct Line(Point, Point);

impl Line {
    pub fn intersect(self, other: Self) -> Option<Point> {
        let a1 = self.1.y - self.0.y;
        let b1 = self.0.x - self.1.x;
        let c1 = a1 * self.0.x + b1 * self.0.y;

        let a2 = other.1.y - other.0.y;
        let b2 = other.0.x - other.1.x;
        let c2 = a2 * other.0.x + b2 * other.0.y;

        let delta = a1 * b2 - a2 * b1;

        if delta == 0.0 {
            return None;
        }

        Some(Point {
            x: (b2 * c1 - b1 * c2) / delta,
            y: (a1 * c2 - a2 * c1) / delta,
        })
    }
}

fn main() {
    let l1 = Line(Point::new(4.0, 0.0), Point::new(6.0, 10.0));
    let l2 = Line(Point::new(0.0, 3.0), Point::new(10.0, 7.0));
    println!("{:?}", l1.intersect(l2));

    let l1 = Line(Point::new(0.0, 0.0), Point::new(1.0, 1.0));
    let l2 = Line(Point::new(1.0, 2.0), Point::new(4.0, 5.0));
    println!("{:?}", l1.intersect(l2));
}


      HIMEM = PAGE + 3000000
      INSTALL @lib$+"HIMELIB"
      PROC_himeinit("HIMEkey")

      DIM old$(20000), new$(20000)
      h1% = 1 : h2% = 2 : h3% = 3 : h4% = 4

      FOR base% = 3 TO 17
        PRINT "Base "; base% " : " FN_largest_left_truncated_prime(base%)
      NEXT
      END

      DEF FN_largest_left_truncated_prime(base%)
      LOCAL digit%, i%, new%, old%, prime%, fast%, slow%
      fast% = 1 : slow% = 50
      old$() = ""
      PROC_hiputdec(1, STR$(base%))
      PROC_hiputdec(2, "1")
      REPEAT
        new% = 0 : new$() = ""
        PROC_hiputdec(3, "0")
        FOR digit% = 1 TO base%-1
          SYS `hi_Add`, ^h2%, ^h3%, ^h3%
          FOR i% = 0 TO old%-1
            PROC_hiputdec(4, old$(i%))
            SYS `hi_Add`, ^h3%, ^h4%, ^h4%
            IF old% OR digit% > 1 THEN
              IF old% > 100 THEN
                SYS `hi_IsPrime_RB`, ^fast%, ^h4% TO prime%
              ELSE
                SYS `hi_IsPrime_RB`, ^slow%, ^h4% TO prime%
              ENDIF
              IF prime% THEN new$(new%) = FN_higetdec(4) : new% += 1
            ENDIF
          NEXT
        NEXT
        SYS `hi_Mul`, ^h1%, ^h2%, ^h2%
        SWAP old$(), new$()
        SWAP old%, new%
      UNTIL old% = 0
      = new$(new%-1)


-- recursionDepth :: () -> IO String
on recursionDepth()
    script go
        on |λ|(i)
            try
                |λ|(1 + i)
            on error
                "Recursion limit encountered at " & i
            end try
        end |λ|
    end script

    go's |λ|(0)
end recursionDepth

on run

    recursionDepth()

end run


recurse: function [x][
    print x
    recurse x+1
]

recurse 0


Recurse(0)

Recurse(x)
{
  TrayTip, Number, %x%
  Recurse(x+1)
}


;AutoIt Version: 3.2.10.0
$depth=0
recurse($depth)
Func recurse($depth)
   ConsoleWrite($depth&@CRLF)
   Return recurse($depth+1)
EndFunc


object Intersection extends App {
  val (l1, l2) = (LineF(PointF(4, 0), PointF(6, 10)), LineF(PointF(0, 3), PointF(10, 7)))

  def findIntersection(l1: LineF, l2: LineF): PointF = {
    val a1 = l1.e.y - l1.s.y
    val b1 = l1.s.x - l1.e.x
    val c1 = a1 * l1.s.x + b1 * l1.s.y

    val a2 = l2.e.y - l2.s.y
    val b2 = l2.s.x - l2.e.x
    val c2 = a2 * l2.s.x + b2 * l2.s.y

    val delta = a1 * b2 - a2 * b1
    // If lines are parallel, intersection point will contain infinite values
    PointF((b2 * c1 - b1 * c2) / delta, (a1 * c2 - a2 * c1) / delta)
  }

  def l01 = LineF(PointF(0f, 0f), PointF(1f, 1f))
  def l02 = LineF(PointF(1f, 2f), PointF(4f, 5f))

  case class PointF(x: Float, y: Float) {
    override def toString = s"{$x, $y}"
  }

  case class LineF(s: PointF, e: PointF)

  println(findIntersection(l1, l2))
  println(findIntersection(l01, l02))

}


func det(a, b, c, d) { a*d - b*c }

func intersection(ax, ay, bx, by,
                  cx, cy, dx, dy) {

    var detAB = det(ax,ay, bx,by)
    var detCD = det(cx,cy, dx,dy)

    var ΔxAB = (ax - bx)
    var ΔyAB = (ay - by)
    var ΔxCD = (cx - dx)
    var ΔyCD = (cy - dy)

    var x_numerator = det(detAB, ΔxAB, detCD, ΔxCD)
    var y_numerator = det(detAB, ΔyAB, detCD, ΔyCD)
    var denominator = det( ΔxAB, ΔyAB,  ΔxCD, ΔyCD)

    denominator == 0 && return 'lines are parallel'
    [x_numerator / denominator, y_numerator / denominator]
}

say ('Intersection point: ', intersection(4,0, 6,10, 0,3, 10,7))
say ('Intersection point: ', intersection(4,0, 6,10, 0,3, 10,7.1))
say ('Intersection point: ', intersection(0,0, 1,1, 1,2, 4,5))


for i in xrange(1, 101):
    if i % 15 == 0:
        print "FizzBuzz"
    elif i % 3 == 0:
        print "Fizz"
    elif i % 5 == 0:
        print "Buzz"
    else:
        print i


#include <stdio.h>
#include <gmp.h>

typedef unsigned long ulong;

ulong small_primes[] = {2,3,5,7,11,13,17,19,23,29,31,37,41,
			43,47,53,59,61,67,71,73,79,83,89,97};

#define MAX_STACK 128
mpz_t tens[MAX_STACK], value[MAX_STACK], answer;

ulong base, seen_depth;

void add_digit(ulong i)
{
	ulong d;
	for (d = 1; d < base; d++) {
		mpz_set(value[i], value[i-1]);
		mpz_addmul_ui(value[i], tens[i], d);
		if (!mpz_probab_prime_p(value[i], 1)) continue;

		if (i > seen_depth ||
			(i == seen_depth && mpz_cmp(value[i], answer) == 1))
		{
			if (!mpz_probab_prime_p(value[i], 50)) continue;

			mpz_set(answer, value[i]);
			seen_depth = i;
			gmp_fprintf(stderr, "\tb=%lu d=%2lu | %Zd\n", base, i, answer);
		}

		add_digit(i+1);
	}
}

void do_base()
{
	ulong i;
	mpz_set_ui(answer, 0);
	mpz_set_ui(tens[0], 1);
	for (i = 1; i < MAX_STACK; i++)
		mpz_mul_ui(tens[i], tens[i-1], base);

	for (seen_depth = i = 0; small_primes[i] < base; i++) {
		fprintf(stderr, "\tb=%lu digit %lu\n", base, small_primes[i]);
		mpz_set_ui(value[0], small_primes[i]);
		add_digit(1);
	}
	gmp_printf("%d: %Zd\n", base, answer);
}

int main(void)
{
	ulong i;
	for (i = 0; i < MAX_STACK; i++) {
		mpz_init_set_ui(tens[i], 0);
		mpz_init_set_ui(value[i], 0);
	}
	mpz_init_set_ui(answer, 0);

	for (base = 22; base < 30; base++) do_base();

	return 0;
}


# syntax: GAWK -f FIND_LIMIT_OF_RECURSION.AWK
#
# version             depth  messages
# ------------------  -----  --------
# GAWK 3.1.4           2892  none
# XML GAWK 3.1.4       3026  none
# GAWK 4.0          >999999
# MAWK 1.3.3           4976  A stack overflow was encountered at
#                            address 0x7c91224e.
# TAWK-DOS AWK 5.0c     357  stack overflow
# TAWK-WIN AWKW 5.0c   2477  awk stack overflow
# NAWK 20100523        4351  Segmentation fault (core dumped)
#
BEGIN {
    x()
    print("done")
}
function x() {
    print(++n)
    if (n > 999999) { return }
    x()
}


RECURSE(1)
Lbl RECURSE
.Optionally, limit the number of times the argument is printed
Disp r₁▶Dec,i
RECURSE(r₁+1)


 100  PRINT "RECURSION DEPTH"
 110  PRINT D" ";
 120  LET D = D + 1
 130  GOSUB 110"RECURSION


@echo off
set /a c=c+1
echo [Depth %c%] Mung until no good
cmd /c mung.cmd
echo [Depth %c%] No good
set /a c=c-1


struct Point {
  var x: Double
  var y: Double
}

struct Line {
  var p1: Point
  var p2: Point

  var slope: Double {
    guard p1.x - p2.x != 0.0 else { return .nan }

    return (p1.y-p2.y) / (p1.x-p2.x)
  }

  func intersection(of other: Line) -> Point? {
    let ourSlope = slope
    let theirSlope = other.slope

    guard ourSlope != theirSlope else { return nil }

    if ourSlope.isNaN && !theirSlope.isNaN {
      return Point(x: p1.x, y: (p1.x - other.p1.x) * theirSlope + other.p1.y)
    } else if theirSlope.isNaN && !ourSlope.isNaN {
      return Point(x: other.p1.x, y: (other.p1.x - p1.x) * ourSlope + p1.y)
    } else {
      let x = (ourSlope*p1.x - theirSlope*other.p1.x + other.p1.y - p1.y) / (ourSlope - theirSlope)
      return Point(x: x, y: theirSlope*(x - other.p1.x) + other.p1.y)
    }
  }
}

let l1 = Line(p1: Point(x: 4.0, y: 0.0), p2: Point(x: 6.0, y: 10.0))
let l2 = Line(p1: Point(x: 0.0, y: 3.0), p2: Point(x: 10.0, y: 7.0))

print("Intersection at : \(l1.intersection(of: l2)!)")


Option Explicit

Public Type Point
  x As Double
  y As Double
  invalid As Boolean
End Type

Public Type Line
  s As Point
  e As Point
End Type

Public Function GetIntersectionPoint(L1 As Line, L2 As Line) As Point
Dim a1 As Double
Dim b1 As Double
Dim c1 As Double
Dim a2 As Double
Dim b2 As Double
Dim c2 As Double
Dim det As Double

  a1 = L1.e.y - L1.s.y
  b1 = L1.s.x - L1.e.x
  c1 = a1 * L1.s.x + b1 * L1.s.y
  a2 = L2.e.y - L2.s.y
  b2 = L2.s.x - L2.e.x
  c2 = a2 * L2.s.x + b2 * L2.s.y
  det = a1 * b2 - a2 * b1

  If det Then
    With GetIntersectionPoint
      .x = (b2 * c1 - b1 * c2) / det
      .y = (a1 * c2 - a2 * c1) / det
    End With
  Else
    GetIntersectionPoint.invalid = True
  End If
End Function

Sub Main()
Dim ln1 As Line
Dim ln2 As Line
Dim ip As Point

  ln1.s.x = 4
  ln1.s.y = 0
  ln1.e.x = 6
  ln1.e.y = 10
  ln2.s.x = 0
  ln2.s.y = 3
  ln2.e.x = 10
  ln2.e.y = 7
  ip = GetIntersectionPoint(ln1, ln2)
  Debug.Assert Not ip.invalid
  Debug.Assert ip.x = 5 And ip.y = 5

  LSet ln2.s = ln2.e
  ip = GetIntersectionPoint(ln1, ln2)
  Debug.Assert ip.invalid

  LSet ln2 = ln1
  ip = GetIntersectionPoint(ln1, ln2)
  Debug.Assert ip.invalid

End Sub


Imports System.Drawing

Module Module1

    Function FindIntersection(s1 As PointF, e1 As PointF, s2 As PointF, e2 As PointF) As PointF
        Dim a1 = e1.Y - s1.Y
        Dim b1 = s1.X - e1.X
        Dim c1 = a1 * s1.X + b1 * s1.Y

        Dim a2 = e2.Y - s2.Y
        Dim b2 = s2.X - e2.X
        Dim c2 = a2 * s2.X + b2 * s2.Y

        Dim delta = a1 * b2 - a2 * b1

        'If lines are parallel, the result will be (NaN, NaN).
        Return If(delta = 0, New PointF(Single.NaN, Single.NaN), New PointF((b2 * c1 - b1 * c2) / delta, (a1 * c2 - a2 * c1) / delta))
    End Function

    Sub Main()
        Dim p = Function(x As Single, y As Single) New PointF(x, y)
        Console.WriteLine(FindIntersection(p(4.0F, 0F), p(6.0F, 10.0F), p(0F, 3.0F), p(10.0F, 7.0F)))
        Console.WriteLine(FindIntersection(p(0F, 0F), p(1.0F, 1.0F), p(1.0F, 2.0F), p(4.0F, 5.0F)))
    End Sub

End Module


q){(sum 1 2*0=x mod/:3 5)'[`$string x;`fizz;`buzz;`fizzbuzz]}1+til 20
`1`2`fizz`4`buzz`fizz`7`8`fizz`buzz`11`fizz`13`14`fizzbuzz`16`17`fizz`19`buzz


using Mpir.NET;  // 0.4.0
using System;   // [email protected]
using System.Collections.Generic;
class MaxLftTrP_B
{
    static void Main()
    {
        mpz_t p; var sw = System.Diagnostics.Stopwatch.StartNew(); L(3);
        for (uint b = 3; b < 13; b++)
        {
            sw.Restart(); p = L(b);
            Console.WriteLine("{0} {1,2} {2}", sw.Elapsed, b, p);
        }
        Console.Read();
    }

    static mpz_t L(uint b)
    {
        var p = new List<mpz_t>(); mpz_t np = 0;
        while ((np = nxtP(np)) < b) p.Add(np);
        int i0 = 0, i = 0, i1 = p.Count - 1; mpz_t n0 = b, n, n1 = b * (b - 1);
        for (; i < p.Count; n0 *= b, n1 *= b, i0 = i1 + 1, i1 = p.Count - 1)
            for (n = n0; n <= n1; n += n0)
                for (i = i0; i <= i1; i++)
                    if (mpir.mpz_probab_prime_p(np = n + p[i], 15) > 0) p.Add(np);
        return p[p.Count - 1];
    }

    static mpz_t nxtP(mpz_t n) { mpz_t p = 0; mpir.mpz_nextprime(p, n); return p; }
}


#include <gmpxx.h>

#include <algorithm>
#include <cassert>
#include <functional>
#include <iostream>
#include <vector>

using big_int = mpz_class;

const unsigned int small_primes[] = {2,  3,  5,  7,  11, 13, 17, 19, 23,
                                     29, 31, 37, 41, 43, 47, 53, 59, 61,
                                     67, 71, 73, 79, 83, 89, 97};

bool is_probably_prime(const big_int& n, int reps) {
    return mpz_probab_prime_p(n.get_mpz_t(), reps) != 0;
}

big_int largest_left_truncatable_prime(unsigned int base) {
    std::vector<big_int> powers = {1};
    std::vector<big_int> value = {0};
    big_int result = 0;

    std::function<void(unsigned int)> add_digit = [&](unsigned int i) {
        if (i == value.size()) {
            value.resize(i + 1);
            powers.push_back(base * powers.back());
        }
        for (unsigned int d = 1; d < base; ++d) {
            value[i] = value[i - 1] + powers[i] * d;
            if (!is_probably_prime(value[i], 1))
                continue;
            if (value[i] > result) {
                if (!is_probably_prime(value[i], 50))
                    continue;
                result = value[i];
            }
            add_digit(i + 1);
        }
    };

    for (unsigned int i = 0; small_primes[i] < base; ++i) {
        value[0] = small_primes[i];
        add_digit(1);
    }
    return result;
}

int main() {
    for (unsigned int base = 3; base < 18; ++base) {
        std::cout << base << ": " << largest_left_truncatable_prime(base)
                  << '\n';
    }
    for (unsigned int base = 19; base < 32; base += 2) {
        std::cout << base << ": " << largest_left_truncatable_prime(base)
                  << '\n';
    }
}


      PROCrecurse(1)
      END

      DEF PROCrecurse(depth%)
      IF depth% MOD 100 = 0 PRINT TAB(0,0) depth%;
      PROCrecurse(depth% + 1)
      ENDPROC


   {𝕊1+•Show 𝕩}0
0
1
.
.
.
4094
Error: Stack overflow
at {𝕊1+•Show 𝕩}0


#include <stdio.h>

void recurse(unsigned int i)
{
  printf("%d\n", i);
  recurse(i+1); // 523756
}

int main()
{
  recurse(0);
  return 0;
}


class Point {
    construct new(x, y) {
        _x = x
        _y = y
    }

    x { _x }
    y { _y }

    toString { "(%(_x), %(_y))" }
}

class Line {
    construct new(s, e) {
        _s = s
        _e = e
    }

    s { _s }
    e { _e }
}

var findIntersection = Fn.new { |l1, l2|
    var a1 = l1.e.y - l1.s.y
    var b1 = l1.s.x - l1.e.x
    var c1 = a1*l1.s.x + b1*l1.s.y

    var a2 = l2.e.y - l2.s.y
    var b2 = l2.s.x - l2.e.x
    var c2 = a2*l2.s.x + b2*l2.s.y

    var delta = a1*b2 - a2*b1
    // if lines are parallel, intersection point will contain infinite values
    return Point.new((b2*c1 - b1*c2)/delta, (a1*c2 - a2*c1)/delta)
}

var l1 = Line.new(Point.new(4, 0), Point.new(6, 10))
var l2 = Line.new(Point.new(0, 3), Point.new(10, 7))
System.print(findIntersection.call(l1, l2))
l1 = Line.new(Point.new(0, 0), Point.new(1, 1))
l2 = Line.new(Point.new(1, 2), Point.new(4, 5))
System.print(findIntersection.call(l1, l2))


For n = 1 To 100
    If n Mod 15 = 0 Then
        Print "FizzBuzz"
    ElseIf n Mod 5 = 0 Then
        Print "Buzz"
    ElseIf n Mod 3 = 0 Then
        Print "Fizz"
    Else
        Print n
    End If
Next


class
	LARGEST_LEFT_TRUNCABLE_PRIME

create
	make

feature

	make
			-- Tests find_prime for different bases.
		local
			i: INTEGER
			decimal: INTEGER_64
		do
			from
				i := 3
			until
				i = 10
			loop
				largest := 0
				find_prime ("", i)
				decimal := convert_to_decimal (largest, i)
				io.put_string (i.out + ":%T" + decimal.out)
				io.new_line
				i := i + 1
			end
		end

	find_prime (right_part: STRING; base: INTEGER)
			-- Largest left truncable prime for a given 'base'.
		local
			i, larger, larger_dec: INTEGER_64
			right: STRING
			prime: BOOLEAN
		do
			from
				i := 1
			until
				i = base
			loop
				create right.make_empty
				right.deep_copy (right_part)
				right.prepend (i.out)
				larger := right.to_integer_64
				if base /= 10 then
					larger_dec := convert_to_decimal (larger, base)
					if larger_dec < 0 then
						io.put_string ("overflow")
						prime := False
					else
						prime := is_prime (larger_dec)
					end
				else
					prime := is_prime (larger)
				end
				if prime = TRUE then
					find_prime (larger.out, base)
				else
					if right_part.count > 0 and right_part.to_integer_64 > largest then
						largest := right_part.to_integer_64
					end
				end
				i := i + 1
			end
		end

	largest: INTEGER_64

	convert_to_decimal (given, base: INTEGER_64): INTEGER_64
			-- 'given' converted to base ten.
		require
		local
			n, i: INTEGER
			st_digits: STRING
			dec: REAL_64
		do
			n := given.out.count
			dec := 0
			st_digits := given.out
			from
				i := 1
			until
				n < 0 or i > given.out.count
			loop
				n := n - 1
				dec := dec + st_digits.at (i).out.to_integer * base ^ n
				i := i + 1
			end
			Result := dec.truncated_to_integer_64
		end

	is_prime (n: INTEGER_64): BOOLEAN
			--Is 'n' a prime number?
		require
			positiv_input: n > 0
		local
			i: INTEGER
			max: REAL_64
			math: DOUBLE_MATH
		do
			create math
			if n = 2 then
				Result := True
			elseif n <= 1 or n \\ 2 = 0 then
				Result := False
			else
				Result := True
				max := math.sqrt (n)
				from
					i := 3
				until
					i > max
				loop
					if n \\ i = 0 then
						Result := False
					end
					i := i + 2
				end
			end
		end

end


using System;
class RecursionLimit
{
  static void Main(string[] args)
  {
    Recur(0);
  }

  private static void Recur(int i)
  {
    Console.WriteLine(i);
    Recur(i + 1);
  }
}


#include <iostream>

void recurse(unsigned int i)
{
  std::cout<<i<<"\n";
  recurse(i+1);
}

int main()
{
  recurse(0);
}


=> (def *stack* 0)
=> ((fn overflow [] ((def *stack* (inc *stack*))(overflow))))
java.lang.StackOverflowError (NO_SOURCE_FILE:0)
=> *stack*
10498


fcn lineIntersect(ax,ay, bx,by,   cx,cy, dx,dy){	// --> (x,y)
   detAB,detCD := det(ax,ay, bx,by), det(cx,cy, dx,dy);
   abDx,cdDx := ax - bx, cx - dx;	// delta x
   abDy,cdDy := ay - by, cy - dy;	// delta y

   xnom,ynom := det(detAB,abDx, detCD,cdDx), det(detAB,abDy, detCD,cdDy);
   denom     := det(abDx,abDy, cdDx,cdDy);
   if(denom.closeTo(0.0, 0.0001))
      throw(Exception.MathError("lineIntersect: Parallel lines"));

   return(xnom/denom, ynom/denom);
}
fcn det(a,b,c,d){ a*d - b*c }	// determinant


  [ times
      [ i^ 1+
        ' echo
        over 3 mod 0 = if
          [ say "Fizz"
            drop ' drop ]
        over 5 mod 0 = if
          [ say "Buzz"
            drop ' drop ]
        do
        sp ]
    cr ]                  is fizzbuzz ( n --> )

  say 'First 100 turns in the game of fizzbuzz:' cr cr
  100 fizzbuzz cr


(* Find some probable candidates for The Largest Left Trucatable Prime in a given base
   Nigel Galloway: April 25th., 2017 *)
let snF Fbase pZ =
  let rec fn i g (e:bigint) l =
    match e with
    | _ when e.IsZero  -> i=1I
    | _ when e.IsEven  -> fn i ((g*g)%l) (e/2I) l
    | _                -> fn ((i*g)%l) ((g*g)%l) (e/2I) l
  let rec fi n i =
    let g = n|>Array.Parallel.collect(fun n->[|for g in 1I..(Fbase-1I) do yield g*i+n|])|>Array.filter(fun n->fn 1I 2I (n-1I) n)
    if (Array.isEmpty g) then n else (fi g (i*Fbase))
  pZ |> Array.Parallel.map (fun n -> fi [|n|] Fbase)|>Seq.concat|>Seq.max


      USE PRIMEBAG	!Gain access to NEXTPRIME and ISPRIME.
Calculates the largest "left-truncatable" digit sequence that is a prime number, in various bases.
      INTEGER LBASE,MANY,ENUFF	!Some sizes.
      PARAMETER (LBASE = 13, MANY = 66666, ENUFF = 66)
      INTEGER NS,START(LBASE)	!A list of single-digit prime numbers for starters.
      INTEGER NH,LH		!Counters for the horde.
      INTEGER N,HORDEN(MANY)		!Numerical value of a digit sequence.
      INTEGER*1 HORDED(ENUFF,MANY)	!Single-digit values only.
      INTEGER B,D,DB	!The base, a digit, some power of the base.
      INTEGER L		!The length of the digit sequence: DB = B**L.
      INTEGER P		!Possibly a prime number.
      INTEGER I		!A stepper.

      MSG = 6	!I/O unit number for "standard output".
      IF (.NOT.GRASPPRIMEBAG(66)) STOP "Gan't grab my file!"	!Attempt in hope.
      NS = 0	!No starters.
      P = 1	!Start looking for some primes.
    1 P = NEXTPRIME(P)	!Thus skipping non-primes.
      IF (P.LE.LBASE) THEN	!Beyond the limit?
        NS = NS + 1		!No. Count another starter.
        START(NS) = P		!Save its value.
        GO TO 1			!And seek further.
      END IF		!One could insted prepare some values, the primes being well-known.
      WRITE (MSG,2) LBASE,NS,START(1:NS)	!But, parameterisation is easy enough.
    2 FORMAT ("Working in bases 3 to ",I0," there are ",I0,	!Announce the known.
     * " single-digit primes: ",666(I0:", "))	!The : sez stop if the list is exhausted.
      WRITE (MSG,3)		!Produce a heading for the tabular output.
    3 FORMAT (/"Base Digits Count Max. Value = (in base)")

   10 DO B = 3,LBASE	!Work through the bases.
        NH = 0			!The horde is empty.
        DO I = 1,NS		!Prepare the starters for base B.
          IF (START(I).GE.B) EXIT	!Like, they're single-digits in base B.
          NH = NH + 1			!So, count another in.
          HORDEN(NH) = START(I)		!Its numerical value.
          HORDED(1,NH) = START(I)	!Its digits. Just one.
        END DO			!On to the next single-digit prime number.
        L = 0	!Syncopation. The length of the digit sequences.
        DB = 1	!The power for the incoming digit.

   20   L = L + 1	!We're about to add another digit.
        IF (L.GE.ENUFF) STOP "Too many digits!"	!Hopefully, there's room.
        DB = DB*B	!The new power of B.
        IF (DB.LE.0) GO TO 29	!Integer overflow?
        LH = NH		!The live ones, awaiting extension.
        DO I = 1,LH	!Step through each starter.
          N = HORDEN(I)	!Grab its numerical value.
          DO D = 1,B - 1	!Consider all possible lead digits.
            P = D*DB + N		!Place it at the start of the number.
            IF (P.LE.0) GO TO 29	!Oh for IF OVERFLOW ...
            IF (ISPRIME(P)) THEN	!And if it is a prime,
              IF (NH.GE.MANY) STOP "Too many sequences!"	!Add a sequence.
              NH = NH + 1			!Count in a survivor.
              HORDEN(NH) = P			!The numerical value.
              HORDED(1:L,NH) = HORDED(1:L,I)	!The digits.
              HORDED(L + 1,NH) = D		!Plus the added high-order digit.
            END IF			!So much for persistent primality.
          END DO		!On to the next lead digit.
        END DO	!On to the next starter.

        N = NH - LH		!The number of entries added to the horde.
        IF (N.GT.0) THEN	!Were there any?
          DO I = 1,MIN(LH,N)		!Yes. Overwrite the starters.
            HORDEN(I) = HORDEN(NH)		!From the tail end of the horde.
            HORDED(1:L + 1,I) = HORDED(1:L + 1,NH)	!Digit sequences as well.
            NH = NH - 1				!One snipped off.
          END DO			!Thus fill the gap at the start.
          NH = N			!The new horde count.
          LH = NH			!All are starters for the next level.
          GO TO 20			!See how it goes.
        END IF			!So much for further progress.
        GO TO 30		!But if none, done.
   29   WRITE (MSG,28) B,L,NH,DB,P	!Curses. Offer some details.
   28   FORMAT (I4,I7,I6,28X,"Integer overflow!",2I12)
        CYCLE			!Or, GO TO the end of the loop.

   30   I = MAXLOC(HORDEN(1:NH),DIM = 1)	!Finger the mostest number.
        WRITE (MSG,31) B,L,NH,HORDEN(I),HORDED(L:1:-1,I)	!Results!
   31   FORMAT (I4,I7,I6,I11," = "666(I0:"."))	!See Format 3.

      END DO		!On to the next base.
      END	!Simple enough.


identification division.
program-id. recurse.
data division.
working-storage section.
01 depth-counter	pic 9(3).
01  install-address   	usage is procedure-pointer.
01  install-flag      	pic x comp-x value 0.
01  status-code       	pic x(2) comp-5.
01  ind               	pic s9(9) comp-5.

linkage section.
01  err-msg           	pic x(325).

procedure division.
100-main.

	set install-address to entry "300-err".

	call "CBL_ERROR_PROC" using install-flag
		install-address
		returning status-code.

	if status-code not = 0
		display "ERROR INSTALLING ERROR PROC"
		stop run
        end-if

 	move 0 to depth-counter.
	display 'Mung until no good.'.
	perform 200-mung.
	display 'No good.'.
	stop run.

200-mung.
	add 1 to depth-counter.
	display depth-counter.
	perform 200-mung.
300-err.
	entry "300-err" using err-msg.
	perform varying ind from 1 by 1
		until (err-msg(ind:1) = x"00") or (ind = length of err-msg)
			continue
	end-perform

	display err-msg(1:ind).

*> room for a better-than-abrupt death here.

	exit program.


recurse = ( depth = 0 ) ->
    try
        recurse depth + 1
    catch exception
        depth

console.log "Recursion depth on this system is #{ do recurse }"


(defun recurse () (recurse))
(trace recurse)
(recurse)


#include<iostream>
#include<string>
#include<boost/filesystem.hpp>
#include<boost/format.hpp>
#include<boost/iostreams/device/mapped_file.hpp>
#include<optional>
#include<algorithm>
#include<iterator>
#include<execution>
#include"dependencies/xxhash.hpp" // https://github.com/RedSpah/xxhash_cpp

/**
* Find ranges (neighbouring elements) of the same value within [begin, end[ and
* call callback for each such range
* @param begin start of container
* @param end end of container (1 beyond last element)
* @param function returns value for each iterator V(*T&)
* @param callback void(start, end, value)
* @return number of range
*/
template<typename  T, typename V, typename F>
size_t for_each_adjacent_range(T begin, T end, V getvalue, F callback) {
    size_t partitions = 0;
    while (begin != end) {
        auto const& value = getvalue(*begin);
        auto current = begin;
        while (++current != end && getvalue(*current) == value);
        callback(begin, current, value);
        ++partitions;
        begin = current;
    }
    return partitions;
}

namespace bi = boost::iostreams;
namespace fs = boost::filesystem;

struct file_entry {
public:
    explicit file_entry(fs::directory_entry const & entry)
        : path_{entry.path()}, size_{fs::file_size(entry)}
    {}
    auto size() const { return size_; }
    auto const& path() const { return path_; }
    auto get_hash() {
        if (!hash_)
            hash_ = compute_hash();
        return *hash_;
    }
private:
    xxh::hash64_t compute_hash() {
        bi::mapped_file_source source;
        source.open<fs::wpath>(this->path());
        if (!source.is_open()) {
            std::cerr << "Cannot open " << path() << std::endl;
            throw std::runtime_error("Cannot open file");
        }
        xxh::hash_state64_t hash_stream;
        hash_stream.update(source.data(), size_);
        return hash_stream.digest();
    }
private:
    fs::wpath path_;
    uintmax_t size_;
    std::optional<xxh::hash64_t> hash_;
};

using vector_type = std::vector<file_entry>;
using iterator_type = vector_type::iterator;

auto find_files_in_dir(fs::wpath const& path, vector_type& file_vector, uintmax_t min_size = 1) {
    size_t found = 0, ignored = 0;
    if (!fs::is_directory(path)) {
        std::cerr << path << " is not a directory!" << std::endl;
    }
    else {
        std::cerr << "Searching " << path << std::endl;

        for (auto& e : fs::recursive_directory_iterator(path)) {
            ++found;
            if (fs::is_regular_file(e) && fs::file_size(e) >= min_size)
                file_vector.emplace_back(e);
            else ++ignored;
        }
    }
    return std::make_tuple(found, ignored);
}

int main(int argn, char* argv[])
{
    vector_type files;
    for (auto i = 1; i < argn; ++i) {
        fs::wpath path(argv[i]);
        auto [found, ignored] = find_files_in_dir(path, files);
        std::cerr << boost::format{
            "  %1$6d files found\n"
            "  %2$6d files ignored\n"
            "  %3$6d files added\n" } % found % ignored % (found - ignored)
            << std::endl;
    }

    std::cerr << "Found " << files.size() << " regular files" << std::endl;
    // sort files in descending order by file size
    std::sort(std::execution::par_unseq, files.begin(), files.end()
        , [](auto const& a, auto const& b) { return a.size() > b.size(); }
    );
    for_each_adjacent_range(
        std::begin(files)
        , std::end(files)
        , [](vector_type::value_type const& f) { return f.size(); }
        , [](auto start, auto end, auto file_size) {
            // Files with same size
            size_t nr_of_files = std::distance(start, end);
            if (nr_of_files > 1) {
                // sort range start-end by hash
                std::sort(start, end, [](auto& a, auto& b) {
                    auto const& ha = a.get_hash();
                    auto const& hb = b.get_hash();
                    auto const& pa = a.path();
                    auto const& pb = b.path();
                    return std::tie(ha, pa) < std::tie(hb, pb);
                    });
                for_each_adjacent_range(
                    start
                    , end
                    , [](vector_type::value_type& f) { return f.get_hash(); }
                    , [file_size](auto hstart, auto hend, auto hash) {
                        // Files with same size and same hash are assumed to be identical
                        // could resort to compare files byte-by-byte now
                        size_t hnr_of_files = std::distance(hstart, hend);
                        if (hnr_of_files > 1) {
                            std::cout << boost::format{ "%1$3d files with hash %3$016x and size %2$d\n" }
                                % hnr_of_files % file_size % hash;
                            std::for_each(hstart, hend, [hash, file_size](auto& e) {
                                std::cout << '\t' << e.path() << '\n';
                                }
                            );
                        }
                    }
                );
            }
        }
    );

    return 0;
}


#lang racket

(for ([n (in-range 1 101)])
  (displayln
   (match (gcd n 15)
     [15 "fizzbuzz"]
     [3 "fizz"]
     [5 "buzz"]
     [_ n])))


for 1 .. 100 {
    when $_ %% (3 & 5) { say 'FizzBuzz'; }
    when $_ %% 3       { say 'Fizz'; }
    when $_ %% 5       { say 'Buzz'; }
    default            { .say; }
}


F last_sundays(year)
   [String] sundays
   L(month) 1..12
      V last_day_of_month = I month < 12 {Time(year, month + 1)} E Time(year + 1)
      L
         last_day_of_month -= TimeDelta(days' 1)
         I last_day_of_month.strftime(‘%w’) == ‘0’
            sundays [+]= year‘-’(‘#02’.format(month))‘-’last_day_of_month.strftime(‘%d’)
            L.break
   R sundays

print(last_sundays(2013).join("\n"))


package main

import (
    "fmt"
    "math/big"
)

var smallPrimes = [...]int{2, 3, 5, 7, 11, 13, 17, 19, 23, 29}

const maxStack = 128

var (
    tens, values    [maxStack]big.Int
    bigTemp, answer = new(big.Int), new(big.Int)
    base, seenDepth int
)

func addDigit(i int) {
    for d := 1; d < base; d++ {
        values[i].Set(&values[i-1])
        bigTemp.SetUint64(uint64(d))
        bigTemp.Mul(bigTemp, &tens[i])
        values[i].Add(&values[i], bigTemp)
        if !values[i].ProbablyPrime(0) {
            continue
        }
        if i > seenDepth || (i == seenDepth && values[i].Cmp(answer) == 1) {
            if !values[i].ProbablyPrime(0) {
                continue
            }
            answer.Set(&values[i])
            seenDepth = i
        }
        addDigit(i + 1)
    }
}

func doBase() {
    answer.SetUint64(0)
    tens[0].SetUint64(1)
    bigTemp.SetUint64(uint64(base))
    seenDepth = 0
    for i := 1; i < maxStack; i++ {
        tens[i].Mul(&tens[i-1], bigTemp)
    }
    for i := 0; smallPrimes[i] < base; i++ {
        values[0].SetUint64(uint64(smallPrimes[i]))
        addDigit(1)
    }
    fmt.Printf("%2d: %s\n", base, answer.String())
}

func main() {
    for base = 3; base <= 17; base++ {
        doBase()
    }
}


primesTo100 = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97]

-- (eq. to) find2km (2^k * n) = (k,n)
find2km :: Integral a => a -> (Int,a)
find2km n = f 0 n
	where f k m
            | r == 1 = (k,m)
            | otherwise = f (k+1) q
            where (q,r) = quotRem m 2

-- n is the number to test; a is the (presumably randomly chosen) witness
millerRabinPrimality :: Integer -> Integer -> Bool
millerRabinPrimality n a
    | a >= n_ = True
    | b0 == 1 || b0 == n_ = True
    | otherwise = iter (tail b)
    where
        n_ = n-1
        (k,m) = find2km n_
        b0 = powMod n a m
        b = take k $ iterate (squareMod n) b0
        iter [] = False
        iter (x:xs)
            | x == 1 = False
            | x == n_ = True
            | otherwise = iter xs

-- (eq. to) pow_ (*) (^2) n k = n^k
pow_ :: (Num a, Integral b) => (a->a->a) -> (a->a) -> a -> b -> a
pow_ _ _ _ 0 = 1
pow_ mul sq x_ n_ = f x_ n_ 1
    where
        f x n y
            | n == 1 = x `mul` y
            | r == 0 = f x2 q y
            | otherwise = f x2 q (x `mul` y)
            where
                (q,r) = quotRem n 2
                x2 = sq x

mulMod :: Integral a => a -> a -> a -> a
mulMod a b c = (b * c) `mod` a
squareMod :: Integral a => a -> a -> a
squareMod a b = (b * b) `rem` a

-- (eq. to) powMod m n k = n^k `mod` m
powMod :: Integral a => a -> a -> a -> a
powMod m = pow_ (mulMod m) (squareMod m)

-- Caller supplies a witness list w, which may be used for MR test.
-- Use faster trial division against a small primes list first, to
-- weed out more obvious composites.
is_prime w n
	| n < 100 = n `elem` primesTo100
	| any ((==0).(n`mod`)) primesTo100 = False
	| otherwise = all (millerRabinPrimality n) w

-- final result gets a more thorough Miller-Rabin
left_trunc base = head $ filter (is_prime primesTo100) (reverse hopeful) where
	hopeful = extend base $ takeWhile (<base) primesTo100 where
	extend b x = if null d then x else extend (b*base) d where
		d = concatMap addDigit [1..base-1]
		-- we do *one* prime test, which seems good enough in practice
		addDigit a = filter (is_prime [3]) $ map (a*b+) x

main = mapM_ print $ map (\x->(x, left_trunc x)) [3..21]


def recurse(counter = 0)
    puts counter
    recurse(counter + 1)
end

recurse()


import std.c.stdio;

void recurse(in uint i=0) {
    printf("%u ", i);
    recurse(i + 1);
}

void main() {
    recurse();
}


program Project2;
{$APPTYPE CONSOLE}
uses
  SysUtils;

function Recursive(Level : Integer) : Integer;
begin
  try
    Level := Level + 1;
    Result := Recursive(Level);
  except
    on E: EStackOverflow do
      Result := Level;
  end;
end;

begin
  Writeln('Recursion Level is ', Recursive(0));
  Writeln('Press any key to Exit');
  Readln;
end.