' FB 1.05.0 Win64

Function isPrime(n As UInteger) As Boolean
  If n < 2 Then Return False
  If n Mod 2 = 0 Then Return n = 2
  If n Mod 3 = 0 Then Return n = 3
  Dim d As Integer = 5
  While d * d <= n
    If n Mod d = 0 Then Return False
    d += 2
    If n Mod d = 0 Then Return False
    d += 4
  Wend
  Return True
End Function

Function reverseNumber(n As UInteger) As UInteger
  If n < 10 Then Return n
  Dim As Integer sum = 0
  While n > 0
    sum = 10 * sum  + (n Mod 10)
    n \= 10
  Wend
  Return sum
End Function

Function isEmirp(n As UInteger) As Boolean
  If Not isPrime(n) Then Return False
  Dim As UInteger reversed = reverseNumber(n)
  Return reversed <> n AndAlso CInt(isPrime(reversed))
End Function

' We can immediately rule out all primes from 2 to 11 as these are palindromic
' and not therefore Emirp primes
Print "The first 20 Emirp primes are :"
Dim As UInteger count = 0, i = 13
Do
  If isEmirp(i) Then
    Print Using "####"; i;
    count + = 1
  End If
  i += 2
Loop Until count = 20
Print : Print
Print "The Emirp primes between 7700 and 8000 are:"
i = 7701
Do
  If isEmirp(i) Then Print Using "#####"; i;
  i += 2
Loop While i < 8000
Print : Print
Print "The 10,000th Emirp prime is : ";
i = 13 : count = 0
Do
  If isEmirp(i) Then count += 1
  If count = 10000 Then Exit Do
  i += 2
Loop
Print i
Print
Print "Press any key to quit"
Sleep


func ef(fr) {
  var ans = []
  if (fr >= 1) {
    return([fr]) if (fr.is_int)
    var intfr = fr.int
    ans << intfr
    fr -= intfr
  }
  var (x, y) = fr.nude
  while (x != 1) {
    ans << fr.inv.ceil.inv
    fr = ((-y % x) / y*fr.inv.ceil)
    (x, y) = fr.nude
  }
  ans << fr
  return ans
}

for fr in [43/48, 5/121, 2014/59] {
  "%s => %s\n".printf(fr.as_rat, ef(fr).map{.as_rat}.join(' + '))
}

var lenmax = (var denommax = [0])
for b in range(2, 99) {
  for a in range(1, b-1) {
    var fr = a/b
    var e = ef(fr)
    var (elen, edenom) = (e.length, e[-1].denominator)
    lenmax = [elen, fr] if (elen > lenmax[0])
    denommax = [edenom, fr] if (edenom > denommax[0])
  }
}

"Term max is %s with %i terms\n".printf(lenmax[1].as_rat, lenmax[0])
"Denominator max is %s with %i digits\n".printf(denommax[1].as_rat, denommax[0].size)
say denommax[0]


isEmirp[x] :=
{
   if isPrime[x]
   {
      s = toString[x]
      rev = reverse[s]
      return s != rev and isPrime[parseInt[rev]]
   }
   return false
}

// Functions that return finite and infinite enumerating expressions of emirps
emirps[] := select[primes[], getFunction["isEmirp", 1]]
emirps[begin, end] := select[primes[begin, end], getFunction["isEmirp", 1]]

println["First 20: " + first[emirps[], 20]]
println["Range:    " + emirps[7700, 8000]]
println["10000th:  " + last[first[emirps[], 10000]]]


package main

import (
	"flag"
	"fmt"
	"github.com/jbarham/primegen.go" // Sieve of Atkin implementation
	"math"
)

// primeCache is a simple cache of small prime numbers, it very
// well might be faster to just regenerate them as needed.
type primeCache struct {
	gen    *primegen.Primegen
	primes []uint64
}

func NewPrimeCache() primeCache {
	g := primegen.New()
	return primeCache{gen: g, primes: []uint64{g.Next()}}
}

// upto returns a slice of primes <= n.
// The returned slice is shared with all callers, do not modify it!
func (pc *primeCache) upto(n uint64) []uint64 {
	if p := pc.primes[len(pc.primes)-1]; p <= n {
		for p <= n {
			p = pc.gen.Next()
			pc.primes = append(pc.primes, p)
		}
		return pc.primes[:len(pc.primes)-1]
	}
	for i, p := range pc.primes {
		if p > n {
			return pc.primes[:i]
		}
	}
	panic("not reached")
}

var cache = NewPrimeCache()

func sqrt(x uint64) uint64 { return uint64(math.Sqrt(float64(x))) }

// isprime does a simple test if n is prime.
// See also math/big.ProbablyPrime().
func isprime(n uint64) bool {
	for _, p := range cache.upto(sqrt(n)) {
		if n%p == 0 {
			return false
		}
	}
	return true
}

func reverse(n uint64) (r uint64) {
	for n > 0 {
		r = 10*r + n%10
		n /= 10
	}
	return
}

// isEmirp does a simple test if n is Emirp, n must be prime
func isEmirp(n uint64) bool {
	r := reverse(n)
	return r != n && isprime(r)
}

// EmirpGen is a sequence generator for Emirp primes
type EmirpGen struct {
	pgen     *primegen.Primegen
	nextn    uint64
	r1l, r1h uint64
	r2l, r2h uint64
	r3l, r3h uint64
}

func NewEmirpGen() *EmirpGen {
	e := &EmirpGen{pgen: primegen.New()}
	e.Reset()
	return e
}

func (e *EmirpGen) Reset() {
	e.pgen.Reset()
	e.nextn = 0
	// Primes >7 cannot end in 2,4,5,6,8 (leaving 1,3,7)
	e.r1l, e.r1h = 20, 30
	e.r2l, e.r2h = 40, 70
	e.r3l, e.r3h = 80, 90
}

func (e *EmirpGen) next() (n uint64) {
	for n = e.pgen.Next(); !isEmirp(n); n = e.pgen.Next() {
		// Skip over inpossible ranges
		// Benchmarks show this saves ~20% when generating n upto 1e6
		switch {
		case e.r1l <= n && n < e.r1h:
			e.pgen.SkipTo(e.r1h)
		case e.r2l <= n && n < e.r2h:
			e.pgen.SkipTo(e.r2h)
		case e.r3l <= n && n < e.r3h:
			e.pgen.SkipTo(e.r3h)
		case n > e.r3h:
			e.r1l *= 10
			e.r1h *= 10
			e.r2l *= 10
			e.r2h *= 10
			e.r3l *= 10
			e.r3h *= 10
		}
	}
	return
}

func (e *EmirpGen) Next() (n uint64) {
	if n = e.nextn; n != 0 {
		e.nextn = 0
		return
	}
	return e.next()
}

func (e *EmirpGen) Peek() uint64 {
	if e.nextn == 0 {
		e.nextn = e.next()
	}
	return e.nextn
}

func (e *EmirpGen) SkipTo(nn uint64) {
	e.pgen.SkipTo(nn)
	e.nextn = 0
	return
}

// SequenceGen defines an arbitrary sequence generator.
// Both *primegen.Primegen and *EmirpGen implement this.
type SequenceGen interface {
	Next() uint64
	Peek() uint64
	Reset()
	SkipTo(uint64)
	//Count(uint64) uint64 // not implemented for *EmirpGen
}

func main() {
	var start, end uint64
	var n, skip uint
	var oneline, primes bool
	flag.UintVar(&n, "n", math.MaxUint64, "number of emirps to print")
	flag.UintVar(&skip, "skip", 0, "number of emirps to skip")
	flag.Uint64Var(&start, "start", 0, "start at x>=start")
	flag.Uint64Var(&end, "end", math.MaxUint64, "stop at x<=end")
	flag.BoolVar(&oneline, "oneline", false, "output on a single line")
	flag.BoolVar(&primes, "primes", false, "generate primes rather than emirps")
	flag.Parse()

	sep := "\n"
	if oneline {
		sep = " "
	}

	// Here's where making SequenceGen an interface comes in handy:
	var seq SequenceGen
	if primes {
		seq = primegen.New()
	} else {
		seq = NewEmirpGen()
	}

	for seq.Peek() < start {
		seq.Next()
	}
	for ; skip > 0; skip-- {
		seq.Next()
	}
	for ; n > 0 && seq.Peek() <= end; n-- {
		fmt.Print(seq.Next(), sep)
	}
	if oneline {
		fmt.Println()
	}
}


with Ada.Text_IO;
with Ada.IO_Exceptions;
with GNAT.Sockets;
procedure Echo_Server is
   Receiver   : GNAT.Sockets.Socket_Type;
   Connection : GNAT.Sockets.Socket_Type;
   Client     : GNAT.Sockets.Sock_Addr_Type;
   Channel    : GNAT.Sockets.Stream_Access;
begin
   GNAT.Sockets.Create_Socket (Socket => Receiver);
   GNAT.Sockets.Set_Socket_Option
     (Socket => Receiver,
      Level  => GNAT.Sockets.Socket_Level,
      Option => (Name    => GNAT.Sockets.Reuse_Address, Enabled => True));
   GNAT.Sockets.Bind_Socket
     (Socket  => Receiver,
      Address => (Family => GNAT.Sockets.Family_Inet,
                  Addr   => GNAT.Sockets.Inet_Addr ("127.0.0.1"),
                  Port   => 12321));
   GNAT.Sockets.Listen_Socket (Socket => Receiver);
   loop
      GNAT.Sockets.Accept_Socket
        (Server  => Receiver,
         Socket  => Connection,
         Address => Client);
      Ada.Text_IO.Put_Line
        ("Client connected from " & GNAT.Sockets.Image (Client));
      Channel := GNAT.Sockets.Stream (Connection);
      begin
         loop
            Character'Output (Channel, Character'Input (Channel));
         end loop;
      exception
         when Ada.IO_Exceptions.End_Error =>
            null;
      end;
      GNAT.Sockets.Close_Socket (Connection);
   end loop;
end Echo_Server;


# Just compute the denominator terms, as the numerators are always 1
proc egyptian {num denom} {
    set result {}
    while {$num} {
	# Compute ceil($denom/$num) without floating point inaccuracy
	set term [expr {$denom / $num + ($denom/$num*$num < $denom)}]
	lappend result $term
	set num [expr {-$denom % $num}]
	set denom [expr {$denom * $term}]
    }
    return $result
}


Imports System.Numerics
Imports System.Text

Module Module1

    Function Gcd(a As BigInteger, b As BigInteger) As BigInteger
        If b = 0 Then
            If a < 0 Then
                Return -a
            Else
                Return a
            End If
        Else
            Return Gcd(b, a Mod b)
        End If
    End Function

    Function Lcm(a As BigInteger, b As BigInteger) As BigInteger
        Return a / Gcd(a, b) * b
    End Function

    Public Class Rational
        Dim num As BigInteger
        Dim den As BigInteger

        Public Sub New(n As BigInteger, d As BigInteger)
            Dim c = Gcd(n, d)
            num = n / c
            den = d / c
            If den < 0 Then
                num = -num
                den = -den
            End If
        End Sub

        Public Sub New(n As BigInteger)
            num = n
            den = 1
        End Sub

        Public Function Numerator() As BigInteger
            Return num
        End Function

        Public Function Denominator() As BigInteger
            Return den
        End Function

        Public Overrides Function ToString() As String
            If den = 1 Then
                Return num.ToString()
            Else
                Return String.Format("{0}/{1}", num, den)
            End If
        End Function

        'Arithmetic operators
        Public Shared Operator +(lhs As Rational, rhs As Rational) As Rational
            Return New Rational(lhs.num * rhs.den + rhs.num * lhs.den, lhs.den * rhs.den)
        End Operator

        Public Shared Operator -(lhs As Rational, rhs As Rational) As Rational
            Return New Rational(lhs.num * rhs.den - rhs.num * lhs.den, lhs.den * rhs.den)
        End Operator

        'Comparison operators

        Public Shared Operator =(lhs As Rational, rhs As Rational) As Boolean
            Return lhs.num = rhs.num AndAlso lhs.den = rhs.den
        End Operator

        Public Shared Operator <>(lhs As Rational, rhs As Rational) As Boolean
            Return lhs.num <> rhs.num OrElse lhs.den <> rhs.den
        End Operator

        Public Shared Operator <(lhs As Rational, rhs As Rational) As Boolean
            'a/b < c/d
            'ad < bc
            Dim ad = lhs.num * rhs.den
            Dim bc = lhs.den * rhs.num
            Return ad < bc
        End Operator

        Public Shared Operator >(lhs As Rational, rhs As Rational) As Boolean
            'a/b > c/d
            'ad > bc
            Dim ad = lhs.num * rhs.den
            Dim bc = lhs.den * rhs.num
            Return ad > bc
        End Operator

        Public Shared Operator <=(lhs As Rational, rhs As Rational) As Boolean
            Return lhs < rhs OrElse lhs = rhs
        End Operator

        Public Shared Operator >=(lhs As Rational, rhs As Rational) As Boolean
            Return lhs > rhs OrElse lhs = rhs
        End Operator

        'Conversion operators
        Public Shared Widening Operator CType(ByVal bi As BigInteger) As Rational
            Return New Rational(bi)
        End Operator
        Public Shared Widening Operator CType(ByVal lo As Long) As Rational
            Return New Rational(lo)
        End Operator
    End Class

    Function Egyptian(r As Rational) As List(Of Rational)
        Dim result As New List(Of Rational)

        If r >= 1 Then
            If r.Denominator() = 1 Then
                result.Add(r)
                result.Add(New Rational(0))
                Return result
            End If
            result.Add(New Rational(r.Numerator / r.Denominator))
            r -= result(0)
        End If

        Dim modFunc = Function(m As BigInteger, n As BigInteger)
                          Return ((m Mod n) + n) Mod n
                      End Function

        While r.Numerator() <> 1
            Dim q = (r.Denominator() + r.Numerator() - 1) / r.Numerator()
            result.Add(New Rational(1, q))
            r = New Rational(modFunc(-r.Denominator(), r.Numerator()), r.Denominator * q)
        End While

        result.Add(r)
        Return result
    End Function

    Function FormatList(Of T)(col As List(Of T)) As String
        Dim iter = col.GetEnumerator()
        Dim sb As New StringBuilder

        sb.Append("[")
        If iter.MoveNext() Then
            sb.Append(iter.Current)
        End If
        While iter.MoveNext()
            sb.Append(", ")
            sb.Append(iter.Current)
        End While
        sb.Append("]")
        Return sb.ToString()
    End Function

    Sub Main()
        Dim rs = {New Rational(43, 48), New Rational(5, 121), New Rational(2014, 59)}
        For Each r In rs
            Console.WriteLine("{0} => {1}", r, FormatList(Egyptian(r)))
        Next

        Dim lenMax As Tuple(Of ULong, Rational) = Tuple.Create(0UL, New Rational(0))
        Dim denomMax As Tuple(Of BigInteger, Rational) = Tuple.Create(New BigInteger(0), New Rational(0))

        Dim query = (From i In Enumerable.Range(1, 100)
                     From j In Enumerable.Range(1, 100)
                     Select New Rational(i, j)).Distinct().ToList()
        For Each r In query
            Dim e = Egyptian(r)
            Dim eLen As ULong = e.Count
            Dim eDenom = e.Last().Denominator()
            If eLen > lenMax.Item1 Then
                lenMax = Tuple.Create(eLen, r)
            End If
            If eDenom > denomMax.Item1 Then
                denomMax = Tuple.Create(eDenom, r)
            End If
        Next

        Console.WriteLine("Term max is {0} with {1} terms", lenMax.Item2, lenMax.Item1)
        Dim dStr = denomMax.Item1.ToString()
        Console.WriteLine("Denominator max is {0} with {1} digits {2}...{3}", denomMax.Item2, dStr.Length, dStr.Substring(0, 5), dStr.Substring(dStr.Length - 5, 5))
    End Sub

End Module


class Emirp {

    //trivial prime algorithm, sub in whatever algorithm you want
    static boolean isPrime(long x) {
        if (x < 2) return false
        if (x == 2) return true
        if ((x & 1) == 0) return false

        for (long i = 3; i <= Math.sqrt(x); i += 2) {
            if (x % i == 0) return false
        }

        return true
    }

    static boolean isEmirp(long x) {
        String xString = Long.toString(x)
        if (xString.length() == 1) return false
        if (xString.matches("[24568].*") || xString.matches(".*[24568]")) return false //eliminate some easy rejects
        long xR = Long.parseLong(new StringBuilder(xString).reverse().toString())
        if (xR == x) return false
        return isPrime(x) && isPrime(xR)
    }

    static void main(String[] args) {
        int count = 0
        long x = 1

        println("First 20 emirps:")
        while (count < 20) {
            if (isEmirp(x)) {
                count++
                print(x + " ")
            }
            x++
        }

        println("\nEmirps between 7700 and 8000:")
        for (x = 7700; x <= 8000; x++) {
            if (isEmirp(x)) {
                print(x + " ")
            }
        }

        println("\n10,000th emirp:")
        x = 1
        count = 0
        for (; count < 10000; x++) {
            if (isEmirp(x)) {
                count++
            }
        }
        //--x to fix the last increment from the loop
        println(--x)
    }
}


void
readc(dispatch w, file i, file o, data b)
{
    integer e;
    data t;

    while (1) {
        e = f_b_read(i, t, 1 << 10);
        if (e < 1) {
            if (e == -1) {
                w_resign(w, i);
            }

            break;
        } else {
            e = b_frame(t, '\n');
            if (e != -1) {
                e += 1;
                b_rule(b, -1, t, 0, e);
                f_data(o, b);
                w_register(w, o);
                b_ecopy(b, t, e, ~t - e);
            } else {
                b_add(b, t);
            }
        }
    }
}

void
serve(dispatch w, file s)
{
    file i, o;
    data b;

    accept(i, o, s, NONBLOCKING_INPUT | NONBLOCKING_OUTPUT);
    w.watch(i, readc, w, i, o, b);
}

integer
main(void)
{
    dispatch w;
    file s;

    tcpip_listen(s, 12321, 0);
    w.watch(s, serve, w, s);
    w.press;

    0;
}


#SingleInstance Force
Network_Port = 12321
Network_Address = 127.0.0.1

NewData := false
DataReceived =
Gosub Connection_Init
return

Connection_Init:
OnExit, ExitSub
socket := PrepareForIncomingConnection(Network_Address, Network_Port)
if socket = -1
    ExitApp

Process, Exist
DetectHiddenWindows On
ScriptMainWindowId := WinExist("ahk_class AutoHotkey ahk_pid " . ErrorLevel)
DetectHiddenWindows Off

NotificationMsg = 0x5555
OnMessage(NotificationMsg, "ReceiveData")

ExitMsg = 0x6666
OnMessage(ExitMsg, "ExitData")

FD_READ = 1
FD_CLOSE = 32
FD_CONNECT = 20

if DllCall("Ws2_32\WSAAsyncSelect", "UInt", socket,
      "UInt", ScriptMainWindowId, "UInt", ExitMsg, "Int", FD_CLOSE)
{
    msgbox, closed
}

if DllCall("Ws2_32\WSAAsyncSelect", "UInt", socket,
        "UInt", ScriptMainWindowId, "UInt", NotificationMsg, "Int",
        FD_READ|FD_CONNECT)
{
    MsgBox % "WSAAsyncSelect() indicated Winsock error "
          . DllCall("Ws2_32\WSAGetLastError")
    DllCall("Ws2_32\WSAAsyncSelect", "UInt", socket,
          "UInt", ScriptMainWindowId, "UInt", ExitMsg, "Int", FD_CLOSE)
    ExitApp
}

SetTimer, NewConnectionCheck, 500
return

PrepareForIncomingConnection(IPAddress, Port)
{
    VarSetCapacity(wsaData, 32)
    result := DllCall("Ws2_32\WSAStartup", "UShort", 0x0002, "UInt", &wsaData)
    if ErrorLevel
    {
        MsgBox % "WSAStartup() could not be called due to error %ErrorLevel%. "
                . "Winsock 2.0 or higher is required."
        return -1
    }
    if result
    {
        MsgBox % "WSAStartup() indicated Winsock error "
                . DllCall("Ws2_32\WSAGetLastError")
        return -1
    }
    AF_INET = 2
    SOCK_STREAM = 1
    IPPROTO_TCP = 6
    socket := DllCall("Ws2_32\socket", "Int", AF_INET,
          "Int", SOCK_STREAM, "Int", IPPROTO_TCP)
    if socket = -1
    {
        MsgBox % "socket() indicated Winsock error "
                . DllCall("Ws2_32\WSAGetLastError")
        return -1
    }
    SizeOfSocketAddress = 16
    VarSetCapacity(SocketAddress, SizeOfSocketAddress)
    InsertInteger(2, SocketAddress, 0, AF_INET)
    InsertInteger(DllCall("Ws2_32\htons", "UShort", Port), SocketAddress, 2, 2)
    InsertInteger(DllCall("Ws2_32\inet_addr", "Str", IPAddress),
            SocketAddress, 4, 4)
    if DllCall("Ws2_32\bind", "UInt", socket,
            "UInt", &SocketAddress, "Int", SizeOfSocketAddress)
    {
        MsgBox % "bind() indicated Winsock error "
                . DllCall("Ws2_32\WSAGetLastError") . "?"
        return -1
    }
    if DllCall("Ws2_32\listen", "UInt", socket, "UInt", "SOMAXCONN")
    {
        MsgBox % "LISTEN() indicated Winsock error "
                . DllCall("Ws2_32\WSAGetLastError") . "?"
        return -1
    }
    return socket
}

ReceiveData(wParam, lParam)
{
    global DataReceived
    global NewData
    global mydata
    global ConnectionList
    socket := wParam
    ReceivedDataSize = 4096
    Loop
    {
        VarSetCapacity(ReceivedData, ReceivedDataSize, 0)
        ReceivedDataLength := DllCall("Ws2_32\recv", "UInt",
              socket, "Str", ReceivedData, "Int", ReceivedDataSize, "Int", 0)
	if ReceivedDataLength = 0
        {
            StringReplace, ConnectionList, ConnectionList, %socket%`n
            DllCall("Ws2_32\closesocket", "UInt", socket)
        }
        if ReceivedDataLength = -1
        {
            WinsockError := DllCall("Ws2_32\WSAGetLastError")
            if WinsockError = 10035
            {
                DataReceived = %TempDataReceived%
                NewData := true
                return 1
            }
            if WinsockError <> 10054
            {
                MsgBox % "recv() indicated Winsock error " . WinsockError
                StringReplace, ConnectionList, ConnectionList, %socket%`n
                DllCall("Ws2_32\closesocket", "UInt", socket)
            }
        }
        mydata := ReceivedData
        gosub myreceive
	if (A_Index = 1)
            TempDataReceived =
                TempDataReceived = %TempDataReceived%%ReceivedData%
    }
    return 1
}

ExitData(wParam, lParam)
{
    global ConnectionList
    socket := wParam
    ReceivedDataSize = 16
    VarSetCapacity(ReceivedData, ReceivedDataSize, 0)
    ReceivedDataLength := DllCall("Ws2_32\recv", "UInt", socket,
          "Str", ReceivedData, "Int", ReceivedDataSize, "Int", 0)
    StringReplace, ConnectionList, ConnectionList, %socket%`n
    DllCall("Ws2_32\closesocket", "UInt", socket)
    return 1
}

SendData(wParam,SendData)
{
    SendDataSize := VarSetCapacity(SendData)
    SendDataSize += 1
    Loop, parse, wParam, `n
    {
        If A_LoopField =
           Continue
        socket := A_LoopField
        sendret := DllCall("Ws2_32\send", "UInt", socket,
              "Str", SendData, "Int", SendDatasize, "Int", 0)
    }
}

InsertInteger(pInteger, ByRef pDest, pOffset = 0, pSize = 4)
{
    Loop %pSize%
        DllCall("RtlFillMemory", "UInt", &pDest + pOffset + A_Index-1,
                "UInt", 1, "UChar", pInteger >> 8*(A_Index-1) & 0xFF)
}

NewConnectionCheck:
ConnectionCheck := DllCall("Ws2_32\accept", "UInt", socket,
      "UInt", &SocketAddress, "Int", SizeOfSocketAddress)
if ConnectionCheck > 1
    ConnectionList = %ConnectionList%%ConnectionCheck%`n
Return

SendProcedure:
If ConnectionList <>
{
    SendText = %A_Hour%:%A_Min%:%A_Sec%
    SendData(ConnectionList,SendText)
}
Return

myreceive:
 TrayTip, server, %mydata%, ,16
  return

GuiClose:
ExitSub:
DllCall("Ws2_32\WSACleanup")
ExitApp


import "/big" for BigInt, BigRat

var toEgyptianHelper // recursive
toEgyptianHelper = Fn.new { |n, d, fracs|
    if (n == BigInt.zero) return
    var divRem = d.divMod(n)
    var div = divRem[0]
    if (divRem[1] > BigInt.zero) div = div.inc
    fracs.add(BigRat.new(BigInt.one, div))
    var n2 = (-d) % n
    if (n2 < BigInt.zero) n2 = n2 + n
    var d2 = d * div
    var f = BigRat.new(n2, d2)
    if (f.num == BigInt.one) {
        fracs.add(f)
        return
    }
    toEgyptianHelper.call(f.num, f.den, fracs)
}

var toEgyptian = Fn.new { |r|
    if (r.num == BigInt.zero) return [r]
    var fracs = []
    if (r.num.abs >= r.den.abs) {
        var div = BigRat.new(r.num/r.den, BigInt.one)
        var rem = r - div
        fracs.add(div)
        toEgyptianHelper.call(rem.num, rem.den, fracs)
    } else {
        toEgyptianHelper.call(r.num, r.den, fracs)
    }
    return fracs
}

BigRat.showAsInt = true
var fracs = [BigRat.new(43, 48), BigRat.new(5, 121), BigRat.new(2014, 59)]
for (frac in fracs) {
    var list = toEgyptian.call(frac)
    System.print("%(frac) -> %(list.join(" + "))")
}

for (r in [98, 998]) {
    if (r == 98) {
        System.print("\nFor proper fractions with 1 or 2 digits:")
    } else {
        System.print("\nFor proper fractions with 1, 2 or 3 digits:")
    }
    var maxSize = 0
    var maxSizeFracs = []
    var maxDen = BigInt.zero
    var maxDenFracs = []
    var sieve = List.filled(r + 1, null) // to eliminate duplicates
    for (i in 0..r) sieve[i] = List.filled(r + 2, false)
    for (i in 1..r) {
        for (j in (i + 1)..(r + 1)) {
            if (!sieve[i][j]) {
                var f = BigRat.new(i, j)
                var list = toEgyptian.call(f)
                var listSize = list.count
                if (listSize > maxSize) {
                    maxSize = listSize
                    maxSizeFracs.clear()
                    maxSizeFracs.add(f)
                } else if (listSize == maxSize) {
                    maxSizeFracs.add(f)
                }
                var listDen = list[-1].den
                if (listDen > maxDen) {
                    maxDen = listDen
                    maxDenFracs.clear()
                    maxDenFracs.add(f)
                } else if (listDen == maxDen) {
                    maxDenFracs.add(f)
                }
                if (i < r / 2) {
                    var k = 2
                    while (true) {
                        if (j * k > r + 1) break
                        sieve[i * k][j * k] = true
                        k = k + 1
                    }
                }
            }
        }
    }
    System.print("  largest number of items = %(maxSize)")
    System.print("  fraction(s) with this number : %(maxSizeFracs)")
    var md = maxDen.toString
    System.write("  largest denominator = %(md.count) digits, ")
    System.print("%(md[0...20])...%(md[-20..-1])")
    System.print("  fraction(s) with this denominator : %(maxDenFracs)")
}


#!/usr/bin/env runghc

import Data.HashSet (HashSet, fromList, member)
import Data.List
import Data.Numbers.Primes
import System.Environment
import System.Exit
import System.IO

-- optimization mentioned on the talk page
startDigOK :: Integer -> Bool
startDigOK n = head (show n) `elem` "1379"

-- infinite list of primes that have an acceptable first digit
filtPrimes :: [Integer]
filtPrimes = filter startDigOK primes

-- finite list of primes that have an acceptable first digit and
-- are the specified number of digits in length
nDigsFPr :: Integer -> [Integer]
nDigsFPr n =
  takeWhile (< hi) $ dropWhile (< lo) filtPrimes
  where lo = 10 ^ (n - 1)
        hi = 10 ^ n

-- hash set of the filtered primes of the specified number of digits
nDigsFPrHS :: Integer -> HashSet Integer
nDigsFPrHS n = fromList $ nDigsFPr n

-- infinite list of hash sets, where each hash set contains primes of
-- a specific number of digits, i. e. index 2 contains 2 digit primes,
-- index 3 contains 3 digit primes, etc.
-- Don't access index 0, because it will return an error
fPrByDigs :: [HashSet Integer]
fPrByDigs = map nDigsFPrHS [0 ..]

isEmirp :: Integer -> Bool
isEmirp n =
  let revStr = reverse $ show n
      reversed = read revStr
      hs = fPrByDigs !! length revStr
  in (startDigOK n) && (reversed /= n) && (reversed `member` hs)

emirps :: [Integer]
emirps = filter isEmirp primes

emirpSlice :: Integer -> Integer -> [Integer]
emirpSlice from to =
  genericTake numToTake $ genericDrop numToDrop emirps
  where
    numToDrop = from - 1
    numToTake = 1 + to - from

emirpValues :: Integer -> Integer -> [Integer]
emirpValues lo hi =
  dropWhile (< lo) $ takeWhile (<= hi) emirps

usage = do
  name <- getProgName
  putStrLn $ "usage: " ++ name ++ " lo hi [slice | values]"
  exitFailure

main = do
  hSetBuffering stdout NoBuffering
  args <- getArgs
  fixedArgs <- case length args of
    1 -> return $ args ++ args ++ ["slice"]
    2 -> return $ args ++ ["slice"]
    3 -> return args
    _ -> usage
  let lo = read $ fixedArgs !! 0
      hi = read $ fixedArgs !! 1
  case fixedArgs !! 2 of
   "slice" -> print $ emirpSlice lo hi
   "values" -> print $ emirpValues lo hi
   _ -> usage


OPEN "localhost:12321" FOR SERVER AS echo
WHILE TRUE
    fd = ACCEPT(echo)
    PRINT "Incoming connection from: ", GETPEER$(fd)
    RECEIVE data$ FROM fd
    SEND data$ & CR$ & NL$ TO fd
    CLOSE SERVER fd
WEND


      INSTALL @lib$+"SOCKLIB"
      PROC_initsockets

      maxSess% = 8
      DIM sock%(maxSess%-1), rcvd$(maxSess%-1), Buffer% 255

      ON ERROR PRINT REPORT$ : PROC_exitsockets : END
      ON CLOSE PROC_exitsockets : QUIT

      crlf$ = CHR$13 + CHR$10
      port$ = "12321"
      host$ = FN_gethostname
      PRINT "Host name is " host$

      listen% = FN_tcplisten(host$, port$)
      PRINT "Listening on port ";port$

      REPEAT
        socket% = FN_check_connection(listen%)
        IF socket% THEN
          FOR i% = 0 TO maxSess%-1
            IF sock%(i%) = 0 THEN
              sock%(i%) = socket%
              rcvd$(i%) = ""
              PRINT "Connection on socket "; sock%(i%) " opened"
              EXIT FOR
            ENDIF
          NEXT i%
          listen% = FN_tcplisten(host$, port$)
        ENDIF

        FOR i% = 0 TO maxSess%-1
          IF sock%(i%) THEN
            res% = FN_readsocket(sock%(i%), Buffer%, 256)
            IF res% >= 0 THEN
              Buffer%?res% = 0
              rcvd$(i%) += $$Buffer%
              crlf% = INSTR(rcvd$(i%), crlf$)
              IF crlf% THEN
                echo$ = LEFT$(rcvd$(i%), crlf%-1)
                res% = FN_writelinesocket(sock%(i%), echo$)
                rcvd$(i%) = MID$(rcvd$(i%), crlf%+2)
              ENDIF
            ELSE
              PROC_closesocket(sock%(i%))
              PRINT "Connection on socket " ; sock%(i%) " closed"
              sock%(i%) = 0
            ENDIF
          ENDIF
        NEXT i%

        WAIT 0
      UNTIL FALSE
      END


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <unistd.h>
#include <sys/wait.h>
#include <signal.h>

#define MAX_ENQUEUED 20
#define BUF_LEN 256
#define PORT_STR "12321"

/* ------------------------------------------------------------ */
/* How to clean up after dead child processes                   */
/* ------------------------------------------------------------ */

void wait_for_zombie(int s)
{
    while(waitpid(-1, NULL, WNOHANG) > 0) ;
}

/* ------------------------------------------------------------ */
/* Core of implementation of a child process                    */
/* ------------------------------------------------------------ */

void echo_lines(int csock)
{
    char buf[BUF_LEN];
    int r;

    while( (r = read(csock, buf, BUF_LEN)) > 0 ) {
        (void)write(csock, buf, r);
    }
    exit(EXIT_SUCCESS);
}

/* ------------------------------------------------------------ */
/* Core of implementation of the parent process                 */
/* ------------------------------------------------------------ */

void take_connections_forever(int ssock)
{
    for(;;) {
        struct sockaddr addr;
        socklen_t addr_size = sizeof(addr);
        int csock;

        /* Block until we take one connection to the server socket */
        csock = accept(ssock, &addr, &addr_size);

        /* If it was a successful connection, spawn a worker process to service it */
        if ( csock == -1 ) {
            perror("accept");
        } else if ( fork() == 0 ) {
            close(ssock);
            echo_lines(csock);
        } else {
            close(csock);
        }
    }
}

/* ------------------------------------------------------------ */
/* The server process's one-off setup code                      */
/* ------------------------------------------------------------ */

int main()
{
    struct addrinfo hints, *res;
    struct sigaction sa;
    int sock;

    /* Look up the address to bind to */
    memset(&hints, 0, sizeof(struct addrinfo));
    hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_flags = AI_PASSIVE;
    if ( getaddrinfo(NULL, PORT_STR, &hints, &res) != 0 ) {
        perror("getaddrinfo");
        exit(EXIT_FAILURE);
    }

    /* Make a socket */
    if ( (sock = socket(res->ai_family, res->ai_socktype, res->ai_protocol)) == -1 ) {
        perror("socket");
        exit(EXIT_FAILURE);
    }

    /* Arrange to clean up child processes (the workers) */
    sa.sa_handler = wait_for_zombie;
    sigemptyset(&sa.sa_mask);
    sa.sa_flags = SA_RESTART;
    if ( sigaction(SIGCHLD, &sa, NULL) == -1 ) {
        perror("sigaction");
        exit(EXIT_FAILURE);
    }

    /* Associate the socket with its address */
    if ( bind(sock, res->ai_addr, res->ai_addrlen) != 0 ) {
        perror("bind");
        exit(EXIT_FAILURE);
    }

    freeaddrinfo(res);

    /* State that we've opened a server socket and are listening for connections */
    if ( listen(sock, MAX_ENQUEUED) != 0 ) {
        perror("listen");
        exit(EXIT_FAILURE);
    }

    /* Serve the listening socket until killed */
    take_connections_forever(sock);
    return EXIT_SUCCESS;
}


# Just compute the denominator terms, as the numerators are always 1
fcn egyptian(num,denom){
   result,t := List(),Void;
   t,num=num.divr(denom);      // reduce fraction
   if(t) result.append(T(t));  // signal t isn't a denominator
   while(num){
      # Compute ceil($denom/$num) without floating point inaccuracy
      term:=denom/num + (denom/num*num < denom);
      result.append(term);
      z:=denom%num;
      num=(if(z) num-z else 0);
      denom*=term;
   }
   result
}
fcn efrac(fraction){  // list to string, format list of denominators
   fraction.pump(List,fcn(denom){
      if(denom.isType(List)) denom[0]
      else 		     String("1/",denom);
   }).concat(" + ")
}


emirp =: (] #~ ~: *. 1 p: ]) |.&.:":"0  NB. Input is array of primes


public class Emirp{

	//trivial prime algorithm, sub in whatever algorithm you want
	public static boolean isPrime(long x){
		if(x < 2) return false;
		if(x == 2) return true;
		if((x & 1) == 0) return false;

		for(long i = 3; i <= Math.sqrt(x);i+=2){
			if(x % i == 0) return false;
		}

		return true;
	}

	public static boolean isEmirp(long x){
		String xString = Long.toString(x);
		if(xString.length() == 1) return false;
		if(xString.matches("[24568].*") || xString.matches(".*[24568]")) return false; //eliminate some easy rejects
		long xR = Long.parseLong(new StringBuilder(xString).reverse().toString());
		if(xR == x) return false;
		return isPrime(x) && isPrime(xR);
	}

	public static void main(String[] args){
		int count = 0;
		long x = 1;

		System.out.println("First 20 emirps:");
		while(count < 20){
			if(isEmirp(x)){
				count++;
				System.out.print(x + " ");
			}
			x++;
		}

		System.out.println("\nEmirps between 7700 and 8000:");
		for(x = 7700; x <= 8000; x++){
			if(isEmirp(x)){
				System.out.print(x +" ");
			}
		}

		System.out.println("\n10,000th emirp:");
		for(x = 1, count = 0;count < 10000; x++){
			if(isEmirp(x)){
				count++;
			}
		}
		//--x to fix the last increment from the loop
		System.out.println(--x);
	}
}


using System.Net.Sockets;
using System.Threading;

namespace ConsoleApplication1
{
    class Program
    {
        static TcpListener listen;
        static Thread serverthread;

        static void Main(string[] args)
        {
            listen = new TcpListener(System.Net.IPAddress.Parse("127.0.0.1"), 12321);
            serverthread = new Thread(new ThreadStart(DoListen));
            serverthread.Start();
        }

        private static void DoListen()
        {
            // Listen
            listen.Start();
            Console.WriteLine("Server: Started server");

            while (true)
            {
                Console.WriteLine("Server: Waiting...");
                TcpClient client = listen.AcceptTcpClient();
                Console.WriteLine("Server: Waited");

                // New thread with client
                Thread clientThread = new Thread(new ParameterizedThreadStart(DoClient));
                clientThread.Start(client);
            }
        }

        private static void DoClient(object client)
        {
            // Read data
            TcpClient tClient = (TcpClient)client;

            Console.WriteLine("Client (Thread: {0}): Connected!", Thread.CurrentThread.ManagedThreadId);
            do
            {
                if (!tClient.Connected)
                {
                    tClient.Close();
                    Thread.CurrentThread.Abort();       // Kill thread.
                }

                if (tClient.Available > 0)
                {
                    // Resend
                    byte pByte = (byte)tClient.GetStream().ReadByte();
                    Console.WriteLine("Client (Thread: {0}): Data {1}", Thread.CurrentThread.ManagedThreadId, pByte);
                    tClient.GetStream().WriteByte(pByte);
                }

                // Pause
                Thread.Sleep(100);
            } while (true);
        }
    }
}


(use '[clojure.contrib.server-socket :only (create-server)])
(use '[clojure.contrib.duck-streams :only (read-lines write-lines)])

(defn echo [input output]
  (write-lines (java.io.PrintWriter. output true) (read-lines input)))

(create-server 12321 echo)


function isPrime(n) {
    if (!(n % 2) || !(n % 3)) return 0;

    var p = 1;
    while (p * p < n) {
        if (n % (p += 4) == 0 || n % (p += 2) == 0) {
            return false
        }
    }
    return true
}

function isEmirp(n) {
    var s = n.toString();
    var r = s.split("").reverse().join("");
    return r != n && isPrime(n) && isPrime(r);
}

function main() {
    var out = document.getElementById("content");

    var c = 0;
    var x = 11;
    var last;
    var str;

    while (c < 10000) {
        if (isEmirp(x)) {
            c += 1;

            // first twenty emirps
            if (c == 1) {
                str = "
" + x;
            }
            else if (c < 20) {
                str += " " + x;
            }
            else if (c == 20) {
                out.innerHTML = str + " " + x + "
";
            }

            // all emirps between 7,700 and 8,000
            else if (7700 <= x && x <= 8001) {
                if (last < 7700) {
                    str = "
" + x;
                } else {
                    str += " " + x;
                }
            }
            else if (x > 7700 && last < 8001) {
                out.innerHTML += str + "
";
            }

            // the 10,000th emirp
            else if (c == 10000) {
                out.innerHTML += "
" + x + "
";
            }

            last = x;
        }
        x += 2;
    }
}


net = require("net")
server = net.createServer (conn) ->
  console.log "Connection from #{conn.remoteAddress} on port  #{conn.remotePort}"
  conn.setEncoding "utf8"
  buffer = ""
  conn.on "data", (data) ->
    i = 0

    while i <= data.length
      char = data.charAt(i)
      buffer += char
      if char is "\n"
        conn.write buffer
        buffer = ""
      i++

server.listen 12321, "localhost"


(ql:quickload (list :usocket))
(defpackage :echo (:use :cl :usocket))
(in-package :echo)

(defun read-all (stream)
  (loop for char = (read-char-no-hang stream nil :eof)
     until (or (null char) (eql char :eof)) collect char into msg
     finally (return (values msg char))))

(defun echo-server (port &optional (log-stream *standard-output*))
  (let ((connections (list (socket-listen "127.0.0.1" port :reuse-address t))))
    (unwind-protect
	 (loop (loop for ready in (wait-for-input connections :ready-only t)
		  do (if (typep ready 'stream-server-usocket)
			 (push (socket-accept ready) connections)
			 (let* ((stream (socket-stream ready))
				(msg (concatenate 'string "You said: " (read-all stream))))
			   (format log-stream "Got message...~%")
			   (write-string msg stream)
			   (socket-close ready)
			   (setf connections (remove ready connections))))))
      (loop for c in connections do (loop while (socket-close c))))))

(echo-server 12321)


def is_prime:
  if  . == 2 then true
  else
     2 < . and . % 2 == 1 and
       (. as $in
       | (($in + 1) | sqrt) as $m
       | [false, 3] | until( .[0] or .[1] > $m; [$in % .[1] == 0, .[1] + 2])
       | .[0]
       | not)
  end ;

def relatively_prime:
  .[0] as $n
  | .[1] as $primes
  | ($n | sqrt) as $s
  | (.[1] | length) as $length
  | [0, true]
  | until( .[0] > $length or ($primes[.[0]] > $s) or .[1] == false;
          [.[0] + 1, ($n % $primes[.[0]] != 0)] )
  | .[1] ;

def primes:
  # The helper function, next, has arity 0 for tail recursion optimization;
  # its input must be an array of primes of length at least 2,
  # the last also being the greatest.
  def next:
     . as $previous
     | .[length-1] as $last
     | [(2 + $last), $previous]
     | until( relatively_prime ; .[0] += 2) as $nextp
     | ( $previous + [$nextp[0]] );
  2, ([2,3] | recurse( next ) | .[-1]) ;


using Primes

function collapse(n::Array{<:Integer})
    sum = 0
    for (p, d) in enumerate(n)
        sum += d * 10 ^ (p - 1)
    end
    return sum
end

Base.reverse(n::Integer) = collapse(reverse(digits(n)))
isemirp(n::Integer) = (if isprime(n) m = reverse(n); return m != n && isprime(m) end; false)

function firstnemirps(m::Integer)
    rst = zeros(typeof(m), m)
    i, n = 1, 2
    while i ≤ m
        if isemirp(n)
            rst[i] = n
            i += 1
        end
        n += 1
    end
    return rst
end

emirps = firstnemirps(10000)
println("First 20:\n", emirps[1:20])
println("Between 7700 and 8000:\n", filter(x -> 7700 ≤ x ≤ 8000, emirps))
println("10000th:\n", emirps[10000])


//  version 1.1.4

fun isPrime(n: Int) : Boolean {
    if (n < 2) return false
    if (n % 2 == 0) return n == 2
    if (n % 3 == 0) return n == 3
    var d = 5
    while (d * d <= n) {
        if (n % d == 0) return false
        d += 2
        if (n % d == 0) return false
        d += 4
    }
    return true
}

fun reverseNumber(n: Int) : Int {
    if (n < 10) return n
    var sum = 0
    var nn = n
    while (nn > 0) {
        sum = 10 * sum + nn % 10
        nn /= 10
    }
    return sum
}

fun isEmirp(n: Int) : Boolean {
    if (!isPrime(n)) return false
    val reversed = reverseNumber(n)
    return reversed != n && isPrime(reversed)
}

fun main(args: Array<String>) {
    println("The first 20 Emirp primes are :")
    var count = 0
    var i = 13
    do {
        if (isEmirp(i)) {
            print(i.toString() + " ")
            count++
        }
        i += 2
    }
    while (count < 20)
    println()
    println()
    println("The Emirp primes between 7700 and 8000 are :")
    i = 7701
    do {
        if (isEmirp(i)) print(i.toString() + " ")
        i += 2
    }
    while (i < 8000)
    println()
    println()
    print("The 10,000th Emirp prime is : ")
    i = 13
    count = 0
    do {
        if (isEmirp(i)) count++
        if (count == 10000) break
        i += 2
    }
    while(true)
    print(i)
}


import std.array, std.socket;

void main() {
    auto listener = new TcpSocket;
    assert(listener.isAlive);
    listener.bind(new InternetAddress(12321));
    listener.listen(10);

    Socket currSock;
    uint bytesRead;
    ubyte[1] buff;

    while (true) {
        currSock = listener.accept();
        while ((bytesRead = currSock.receive(buff)) > 0)
            currSock.send(buff);
        currSock.close();
        buff.clear();
    }
}


program EchoServer;

{$APPTYPE CONSOLE}

uses SysUtils, IdContext, IdTCPServer;

type
  TEchoServer = class
  private
    FTCPServer: TIdTCPServer;
  public
    constructor Create;
    destructor Destroy; override;
    procedure TCPServerExecute(AContext: TIdContext);
  end;

constructor TEchoServer.Create;
begin
  FTCPServer := TIdTCPServer.Create(nil);
  FTCPServer.DefaultPort := 12321;
  FTCPServer.OnExecute := TCPServerExecute;
  FTCPServer.Active := True;
end;

destructor TEchoServer.Destroy;
begin
  FTCPServer.Active := False;
  FTCPServer.Free;
  inherited Destroy;
end;

procedure TEchoServer.TCPServerExecute(AContext: TIdContext);
var
  lCmdLine: string;
begin
  lCmdLine := AContext.Connection.IOHandler.ReadLn;
  Writeln('>' + lCmdLine);
  AContext.Connection.IOHandler.Writeln('>' + lCmdLine);

  if SameText(lCmdLine, 'QUIT') then
  begin
    AContext.Connection.IOHandler.Writeln('Disconnecting');
    AContext.Connection.Disconnect;
  end;
end;

var
  lEchoServer: TEchoServer;
begin
  lEchoServer := TEchoServer.Create;
  try
    Writeln('Delphi Echo Server');
    Writeln('Press Enter to quit');
    Readln;
  finally
    lEchoServer.Free;
  end;
end.


function isPrime (n)
    if n < 2 then return false end
    if n < 4 then return true end
    if n % 2 == 0 then return false end
    for d = 3, math.sqrt(n), 2 do
        if n % d == 0 then return false end
    end
    return true
end

function isEmirp (n)
    if not isPrime(n) then return false end
    local rev = tonumber(string.reverse(n))
    if rev == n then return false end
    return isPrime(rev)
end

function emirpGen (mode, a, b)
    local count, n, eString = 0, 0, ""
    if mode == "between" then
        for n = a, b do
            if isEmirp(n) then eString = eString .. n .. " " end
        end
        return eString
    end
    while count < a do
        n = n + 1
        if isEmirp(n) then
            eString = eString .. n .. " "
            count = count + 1
        end
    end
    if mode == "first" then return eString end
    if mode == "Nth" then return n end
end

if #arg > 1 and #arg < 4 then
    print(emirpGen(arg[1], tonumber(arg[2]), tonumber(arg[3])))
else
    print("Wrong number of arguments")
end


-module(echo).
-export([start/0]).

start() ->
    spawn(fun () -> {ok, Sock} = gen_tcp:listen(12321, [{packet, line}]),
                    echo_loop(Sock)
          end).

echo_loop(Sock) ->
    {ok, Conn} = gen_tcp:accept(Sock),
    io:format("Got connection: ~p~n", [Conn]),
    Handler = spawn(fun () -> handle(Conn) end),
    gen_tcp:controlling_process(Conn, Handler),
    echo_loop(Sock).

handle(Conn) ->
    receive
        {tcp, Conn, Data} ->
            gen_tcp:send(Conn, Data),
            handle(Conn);
        {tcp_closed, Conn} ->
            io:format("Connection closed: ~p~n", [Conn])
    end.


defmodule Echo.Server do
  def start(port) do
    tcp_options = [:binary, {:packet, 0}, {:active, false}]
    {:ok, socket} = :gen_tcp.listen(port, tcp_options)
    listen(socket)
  end

  defp listen(socket) do
    {:ok, conn} = :gen_tcp.accept(socket)
    spawn(fn -> recv(conn) end)
    listen(socket)
  end

  defp recv(conn) do
    case :gen_tcp.recv(conn, 0) do
      {:ok, data} ->
        :gen_tcp.send(conn, data)
        recv(conn)
      {:error, :closed} ->
        :ok
    end
  end
end


open System.IO
open System.Net
open System.Net.Sockets

let service (client:TcpClient) =
    use stream = client.GetStream()
    use out = new StreamWriter(stream, AutoFlush = true)
    use inp = new StreamReader(stream)
    while not inp.EndOfStream do
        match inp.ReadLine() with
        | line -> printfn "< %s" line
                  out.WriteLine(line)
    printfn "closed %A" client.Client.RemoteEndPoint
    client.Close |> ignore

let EchoService =
    let socket = new TcpListener(IPAddress.Loopback, 12321)
    do socket.Start()
    printfn "echo service listening on %A" socket.Server.LocalEndPoint
    while true do
        let client = socket.AcceptTcpClient()
        printfn "connect from %A" client.Client.RemoteEndPoint
        let job = async {
            use c = client in try service client with _ -> () }
        Async.Start job

[<EntryPoint>]
let main _ =
    EchoService
    0


EmirpPrime := proc(n)
    local eprime;
    eprime := parse(StringTools:-Reverse(convert(n,string)));
    if n <> eprime and isprime(n) and isprime(eprime) then
        return n;
    end if;
end proc:
EmirpsList := proc( n )
    local i, values;
    values := Array([]):
    i := 0:
    do
        i := i + 1;
        if EmirpPrime(i) <> NULL then
            ArrayTools:-Append(values, i);
        end if;
    until numelems(values) = n;
    return convert(values,list);
end proc:
EmirpsList(20);
EmirpPrime~([seq(7700..8000)]);
EmirpsList(10000)[-1];


NN=(1:1:1e6); %Natural numbers between 1 and t
pns=NN(isprime(NN)); %prime numbers
p=fliplr(str2num(fliplr(num2str(pns))));
a=pns(isprime(p)); b=p(isprime(p)); c=a-b;
emirps=NN(a(c~=0));


USING: accessors io io.encodings.utf8 io.servers io.sockets threads ;
IN: rosetta.echo

CONSTANT: echo-port 12321

: handle-client ( -- )
   [ print flush ] each-line ;

: <echo-server> ( -- threaded-server )
    utf8 <threaded-server>
        "echo server" >>name
        echo-port >>insecure
        [ handle-client ] >>handler ;

: start-echo-server ( -- )
    <echo-server> [ start-server ] in-thread start-server drop ;


include unix/socket.fs

128 constant size

: (echo) ( sock buf -- sock buf )
  begin
    cr ." waiting..."
    2dup 2dup size read-socket nip
    dup 0>
  while
    ."  got: " 2dup type
    rot write-socket
  repeat
  drop drop drop ;

create buf size allot

: echo-server ( port -- )
  cr ." Listening on " dup .
  create-server
  dup 4 listen
  begin
    dup accept-socket
    cr ." Connection!"
    buf ['] (echo) catch
    cr ." Disconnected (" . ." )"
    drop close-socket
  again ;

12321 echo-server


package main

import (
	"fmt"
	"net"
	"bufio"
)

func echo(s net.Conn, i int) {
	defer s.Close();

	fmt.Printf("%d: %v <-> %v\n", i, s.LocalAddr(), s.RemoteAddr())
	b := bufio.NewReader(s)
	for {
		line, e := b.ReadBytes('\n')
		if e != nil {
			break
		}
		s.Write(line)
	}
	fmt.Printf("%d: closed\n", i)
}

func main() {
	l, e := net.Listen("tcp", ":12321")
	for i := 0; e == nil; i++ {
		var s net.Conn
		s, e = l.Accept()
		go echo(s, i)
	}
}


MODULE Emirp;
FROM Conversions IMPORT StrToLong;
FROM FormatString IMPORT FormatString;
FROM LongMath IMPORT sqrt;
FROM Terminal IMPORT WriteString,WriteLn,ReadChar;

PROCEDURE IsPrime(x : LONGINT) : BOOLEAN;
VAR
    i : LONGINT;
    u : LONGREAL;
    v : LONGINT;
BEGIN
    IF x<2 THEN RETURN FALSE END;
    IF x=2 THEN RETURN TRUE END;
    IF x MOD 2 = 0 THEN RETURN FALSE END;

    u := sqrt(FLOAT(x));
    v := TRUNC(u);

    FOR i:=3 TO v BY 2 DO
        IF x MOD i = 0 THEN RETURN FALSE END
    END;

    RETURN TRUE
END IsPrime;

PROCEDURE IsEmirp(x : LONGINT) : BOOLEAN;
VAR
    buf,rev : ARRAY[0..9] OF CHAR;
    i,j : INTEGER;
    y : LONGINT;
BEGIN
    (* Terminate early if the number is even *)
    IF x MOD 2 = 0 THEN RETURN FALSE END;

    (* First convert the input to a string *)
    FormatString("%l", buf, x);

    (* Create a copy of the string revered *)
    j := 0;
    WHILE buf[j] # 0C DO INC(j) END;
    DEC(j);
    i := 0;
    WHILE buf[i] # 0C DO
        rev[i] := buf[j];
        INC(i);
        DEC(j)
    END;
    rev[i] := 0C;

    (* Convert the reversed copy to a number *)
    StrToLong(rev,y);

    (* Terminate early if the number is even *)
    IF y MOD 2 = 0 THEN RETURN FALSE END;

    (* Discard palindromes *)
    IF x=y THEN RETURN FALSE END;

    RETURN IsPrime(x) AND IsPrime(y)
END IsEmirp;

VAR
    buf : ARRAY[0..63] OF CHAR;
    x,count : LONGINT;
BEGIN
    count := 0;
    x := 1;

    WriteString("First 20 emirps:");
    WriteLn;
    WHILE count<20 DO
        IF IsEmirp(x) THEN
            INC(count);
            FormatString("%l ", buf, x);
            WriteString(buf)
        END;
        INC(x)
    END;
    WriteLn;

    WriteString("Emirps between 7700 and 8000:");
    WriteLn;
    FOR x:=7700 TO 8000 DO
        IF IsEmirp(x) THEN
            FormatString("%l ", buf, x);
            WriteString(buf)
        END
    END;
    WriteLn;

    WriteString("10,000th emirp:");
    WriteLn;
    count := 0;
    x := 1;
    WHILE count<10000 DO
        IF IsEmirp(x) THEN
            INC(count);
        END;
        INC(x)
    END;
    FormatString("%l ", buf, x-1);
    WriteString(buf);
    WriteLn;

    ReadChar
END Emirp.


module Main where
import Network (withSocketsDo, accept, listenOn, sClose, PortID(PortNumber))
import Control.Monad (forever)
import System.IO (hGetLine, hPutStrLn, hFlush, hClose)
import System.IO.Error (isEOFError)
import Control.Concurrent (forkIO)
import Control.Exception (bracket)

-- For convenience in testing, ensure that the listen socket is closed if the main loop is aborted
withListenOn port body = bracket (listenOn port) sClose body

echo (handle, host, port) = catch (forever doOneLine) stop where
  doOneLine = do line <- hGetLine handle
                 print (host, port, init line)
                 hPutStrLn handle line
                 hFlush handle
  stop error = do putStrLn $ "Closed connection from " ++ show (host, port) ++ " due to " ++ show error
                  hClose handle

main = withSocketsDo $
  withListenOn (PortNumber 12321) $ \listener ->
    forever $ do
      acc@(_, host, port) <- accept listener
      putStrLn $ "Accepted connection from " ++ show (host, port)
      forkIO (echo acc)


global mlck, nCons

procedure main()
    mlck := mutex()
    nCons := 0
    while f := open(":12321","na") do {
        handle_client(f)
        critical mlck: if nCons <= 0 then close(f)
        }
end

procedure handle_client(f)
    critical mlck: nCons +:= 1
    thread {
        select(f,1000) & repeat writes(f,reads(f))
        critical mlck: nCons -:= 1
        }
end


import math

# Increments to find the next divisor when testing primality.
const Incr = [4, 2, 4, 2, 4, 6, 2, 6]

#---------------------------------------------------------------------------------------------------

func reversed(n: int): int =
  ## Return the reversed number in base 10 representation.
  var n = n
  while true:
    result = 10 * result + n mod 10
    n = n div 10
    if n == 0:
      break

#---------------------------------------------------------------------------------------------------

func isPrime(n: int): bool =
  ## Check if a number is prime.
  ## We are already sure that "n" is not a multiple of 2, 3 or 5,
  ## so we don’t check the modulo.
  var k = 7
  var i = 0
  while k <= int(sqrt(n.toFloat)):
    if n mod k == 0:
      return false
    inc k, Incr[i]
    i = if i == Incr.high: 0 else: i + 1
  result = true

#---------------------------------------------------------------------------------------------------

iterator emirps(): int =
  ## Yield the emirps.
  var n = 13
  var i = 2   # Current index in the increment array.
  while true:
    # We find the reversed number first as it allows to eliminate candidates.
    let r = reversed(n)
    if r != n and r mod 10 in [1, 3, 7, 9] and n.isPrime and r.isPrime:
      yield n
    inc n, Incr[i]
    i = if i == Incr.high: 0 else: i + 1

#———————————————————————————————————————————————————————————————————————————————————————————————————

stdout.write "First 20 emirps:"
var count = 0
for n in emirps():
  stdout.write ' ', n
  inc count
  if count == 20:
    echo ""
    break

stdout.write "Emirps between 7700 and 8000:"
for n in emirps():
  if n in 7700..8000:
    stdout.write ' ', n
  elif n > 8000:
    echo ""
    break

stdout.write "The 10000th emirp: "
count = 0
for n in emirps():
  inc count
  if count == 10000:
    echo n
    break


: isEmirp(n)
   n isPrime ifFalse: [ false return ]
   n asString reverse asInteger dup n == ifTrue: [ drop false ] else: [ isPrime ] ;

: main(min, max, length)
| l |
   ListBuffer new ->l
   min while(l size length < ) [
      dup max > ifTrue: [ break ]
      dup isEmirp ifTrue: [ dup l add ] 1 +
      ]
   drop l ;


rev(n)=subst(Polrev(digits(n)),'x,10);
emirp(n)=my(r=rev(n)); isprime(r) && isprime(n) && n!=r
select(emirp, primes(100))[1..20]
select(emirp, primes([7700,8000]))
s=10000; forprime(p=2,,if(emirp(p) && s--==0, return(p)))


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

public class EchoServer {

    public static void main(String[] args) throws IOException {
        try (ServerSocket listener = new ServerSocket(12321)) {
            while (true) {
                Socket conn = listener.accept();
                Thread clientThread = new Thread(() -> handleClient(conn));
                clientThread.start();
            }
        }
    }

    private static void handleClient(Socket connArg) {
        Charset utf8 = StandardCharsets.UTF_8;

        try (Socket conn = connArg) {
            BufferedReader in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream(), utf8));

            PrintWriter out = new PrintWriter(
                    new OutputStreamWriter(conn.getOutputStream(), utf8),
                    true);

            String line;
            while ((line = in.readLine()) != null) {
                out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}


const net = require('net');

function handleClient(conn) {
    console.log('Connection from ' + conn.remoteAddress + ' on port ' + conn.remotePort);

    conn.setEncoding('utf-8');

    let buffer = '';

    function handleData(data) {
        for (let i = 0; i < data.length; i++) {
            const char = data.charAt(i);
            buffer += char;
            if (char === '\n') {
                conn.write(buffer);
                buffer = '';
            }
        }
    }

    conn.on('data', handleData);
}

net.createServer(handleClient).listen(12321, 'localhost');


BEGIN # find Duffinian numbers: non-primes relatively prime to their divisor count #
    INT max number            := 500 000;      # largest number we will consider   #
    # iterative Greatest Common Divisor routine, returns the gcd of m and n        #
    PROC gcd = ( INT m, n )INT:
         BEGIN
            INT a := ABS m, b := ABS n;
            WHILE b /= 0 DO
                INT new a = b;
                b        := a MOD b;
                a        := new a
            OD;
            a
         END # gcd # ;
    # construct a table of the divisor counts                                      #
    [ 1 : max number ]INT ds; FOR i TO UPB ds DO ds[ i ] := 1 OD;
    FOR i FROM 2 TO UPB ds
        DO FOR j FROM i BY i TO UPB ds DO ds[ j ] +:= i OD
    OD;
    # set the divisor counts of non-Duffinian numbers to 0                         #
    ds[ 1 ] := 0;  # 1 is not Duffinian                                            #
    FOR n FROM 2 TO UPB ds DO
        IF INT nds = ds[ n ];
           IF nds = n + 1 THEN TRUE ELSE gcd( n, nds ) /= 1 FI
        THEN
            # n is prime or is not relatively prime to its divisor sum             #
            ds[ n ] := 0
        FI
    OD;
    # show the first 50 Duffinian numbers                                          #
    print( ( "The first 50 Duffinian numbers:", newline ) );
    INT dcount := 0;
    FOR n WHILE dcount < 50 DO
        IF ds[ n ] /= 0
        THEN # found a Duffinian number                                            #
            print( ( " ", whole( n, -3) ) );
            IF ( dcount +:= 1 ) MOD 25 = 0 THEN print( ( newline ) ) FI
        FI
    OD;
    print( ( newline ) );
    # show the duffinian triplets below UPB ds                                     #
    print( ( "The Duffinian triplets up to ", whole( UPB ds, 0 ), ":", newline ) );
    dcount := 0;
    FOR n FROM 3 TO UPB ds DO
        IF ds[ n - 2 ] /= 0 AND ds[ n - 1 ] /= 0 AND ds[ n ] /= 0
        THEN # found a Duffinian triplet                                           #
            print( ( " (", whole( n - 2, -7 ), " ", whole( n - 1, -7 ), " ", whole( n, -7 ), ")" ) );
            IF ( dcount +:= 1 ) MOD 4 = 0 THEN print( ( newline ) ) FI
        FI
    OD
END


program Emirp;
//palindrome prime 13 <-> 31
{$IFDEF FPC}
  {$MODE DELPHI}
  {$OPTIMIZATION ON}
  {$OPTIMIZATION REGVAR}
  {$OPTIMIZATION PEEPHOLE}
  {$OPTIMIZATION CSE}
  {$OPTIMIZATION ASMCSE}
  {$Smartlink ON}
  {$CODEALIGN proc=32}
{$ELSE}
  {$APPLICATION CONSOLE}
{$ENDIF}
uses
  primtrial,sysutils; //IntToStr
const
  helptext : array[0..5] of string =
     ('  usage ',
      '  t     -> test of functions',
      '  b l u -> Emirps betwenn l,u       b 7700 8000',
      '  c n   -> count of Emirps up to n  c 99999',
      '  f n   -> output n first Emirp     f 20',
      '  n     -> output the n.th Emirps   10000');

  StepToNextPrimeEnd : Array[0..9] of byte =
              (1,0,3,0,7,7,7,0,9,0);

  base = 10;

var
  s: AnsiString;
  pow,
  powLen  : NativeUint;

procedure OutputHelp;
var
  i : NativeUint;
Begin
  For i := Low(helptext) to High(helptext) do
    writeln(helptext[i]);
  writeln;
end;

function GetNumber(const s: string;var n:NativeUint):boolean;
var
  ErrCode: Word;
Begin
  val(s,n,Errcode);
  result := ErrCode = 0;
end;

procedure RvsStr(var s: AnsiString);
var
  i, j: NativeUint;
  swapChar : Ansichar;
Begin
  i := 1;
  j := Length(s);
  While j>i do Begin
    swapChar:= s[i];s[i] := s[j];s[j] := swapChar;
    inc(i);dec(j) end;
end;

function RvsNumL(var n: NativeUint):NativeUint;
//reverse and last digit
var
  q, c: NativeUint;
Begin
  result := n;
  q := 0;
  repeat
    c:= result div Base;
    q := q*Base+(result-c*Base);
    result := c;
  until result < Base;
  n := q*Base+result;

end;

procedure InitP(var p: NativeUint);
Begin
  powLen := 2;
  pow := Base;
  InitPrime;
  repeat p :=NextPrime until p >= 11;
end;

function isEmirp(p: NativeUint):boolean;
var
  rvsp: NativeUint;
Begin
  s := IntToStr(p);
  result := StepToNextPrimeEnd[Ord(s[1])-48] = 0;
  IF result then
  Begin
    RvsStr(s);
    rvsp := StrToInt(s);
    result := false;
    IF rvsp<>p then
      result := isPrime(rvsp);
  end;
end;

function NextEmirp:NativeUint;
var
 r,Ldgt: NativeUint;
Begin
  result:= NextPrime;
  repeat
    r := result;
    //reverse
    Ldgt := RvsNumL(r);
    Ldgt := StepToNextPrimeEnd[Ldgt];
    IF Ldgt = 0 then
    Begin
      IF r<>result then
        IF isPrime(r) then
          EXIT;
      result:= NextPrime;
    end
    else
    Begin
      while actPrime > pow*Base do
      Begin
        inc(PowLen);
        pow := pow*base;
      end;
      result := Ldgt*pow;
      result := PrimeGELimit(result);
    end;
  until false;
end;

function GetIthEmirp(i: NativeUint):NativeUint;
var
  p : NativeUint;
Begin
  InitP(p);
  Repeat
    dec(i);
    p:= NextEmirp;
  until i = 0;
  result := p;
end;

procedure nFirstEmirp(n: NativeUint);
var
  p : NativeUint;

Begin
  InitP(p);
  Writeln('the first ',n,' Emirp primE: ');
  Repeat
    dec(n);
    p:= NextEmirp;
    write(p,' ');
  until n = 0;
  Writeln;
end;

function CntToLimit(n: NativeUint):NativeUint;
var
  p,cnt : NativeUint;
Begin
  cnt := 0;
  InitP(p);
  p:= NextEmirp;
  While p <= n do
  Begin
    inc(cnt);
    p:= NextEmirp;
  end;
  result := cnt;
end;

procedure InRange(l,u:NativeUint);
var
  p : NativeUint;
  b : boolean;
Begin
  InitP(p);
  IF l > u then Begin p:=l;l:=u;u:=p end;
  Writeln('Emirp primes between ',l,' and ',u,' : ');
  p := PrimeGELimit(l);

  b := IsEmirp(p);
  if b then
    write(p,' ');
  p:= NextEmirp;
  IF (p> u) AND NOT b  then
    Writeln('none')
  else
  Begin
    while p < u do
      Begin
      write(p,' ');
      p:= NextEmirp;
    end;
    Writeln;
  end;
end;

var
  i,u: NativeUint;
  select : char;
Begin
  IF paramcount >= 1 then
    select := Lowercase(paramstr(1)[1]);
  case paramcount of
  1: Begin
       if select='t' then
       Begin
         nFirstEmirp(20);
         InRange(7700,8000);
         Writeln('the ',10000,'.th Emirp prime: ',GetIthEmirp(10000));
         writeln(CntToLimit(9999),' Emirp primes up to ',9999);
         // as a gag
         InRange(400000000,700000000);
       end
       else
         IF GetNumber(paramstr(1),i) then
           Writeln('the ',i,'.th Emirp prime: ',GetIthEmirp(i))
         else
           OutPutHelp;
     end;
  2: Begin
       case select of
       'c': If GetNumber(paramstr(2),i) then
              writeln(CntToLimit(i),' Eemirp primes up to ',i)
            else
              OutPutHelp;
       'f': If GetNumber(paramstr(2),i) then
              nFirstEmirp(i)
            else
              OutPutHelp;
        else
          OutPutHelp;
        end;
     end;
  3: IF (select ='b') AND
        GetNumber(paramstr(2),i) AND GetNumber(paramstr(3),u) Then
       InRange(i,u)
     else
        OutPutHelp;
  else
    OutPutHelp;
  end;
End.


using Sockets # for version 1.0
println("Echo server on port 12321")
try
    server = listen(12321)
    instance = 0
    while true
        sock = accept(server)
        instance += 1
        socklabel = "$(getsockname(sock)) number $instance"
        @async begin
            println("Server connected to socket $socklabel")
            write(sock, "Connected to echo server.\r\n")
            while isopen(sock)
                str = readline(sock)
                write(sock,"$str\r\n")
                println("Echoed $str to socket $socklabel")
            end
            println("Closed socket $socklabel")
        end
    end
catch y
    println("Caught exception: $y")
end


import java.net.ServerSocket
import java.net.Socket

fun main() {

    fun handleClient(conn: Socket) {
        conn.use {
            val input = conn.inputStream.bufferedReader()
            val output = conn.outputStream.bufferedWriter()

            input.forEachLine { line ->
                output.write(line)
                output.newLine()
                output.flush()
            }
        }
    }

    ServerSocket(12321).use { listener ->
        while (true) {
            val conn = listener.accept()
            Thread { handleClient(conn) }.start()
        }
    }
}


(defun start ()
  (spawn (lambda ()
           (let ((`#(ok ,socket) (gen_tcp:listen 12321 `(#(packet line)))))
             (echo-loop socket)))))

(defun echo-loop (socket)
  (let* ((`#(ok ,conn) (gen_tcp:accept socket))
         (handler (spawn (lambda () (handle conn)))))
    (lfe_io:format "Got connection: ~p~n" (list conn))
    (gen_tcp:controlling_process conn handler)
    (echo-loop socket)))

(defun handle (conn)
  (receive
    (`#(tcp ,conn ,data)
     (gen_tcp:send conn data))
    (`#(tcp_closed ,conn)
     (lfe_io:format "Connection closed: ~p~n" (list conn)))))


on aliquotSum(n)
    if (n < 2) then return 0
    set sum to 1
    set sqrt to n ^ 0.5
    set limit to sqrt div 1
    if (limit = sqrt) then
        set sum to sum + limit
        set limit to limit - 1
    end if
    repeat with i from 2 to limit
        if (n mod i is 0) then set sum to sum + i + n div i
    end repeat

    return sum
end aliquotSum

on hcf(a, b)
    repeat until (b = 0)
        set x to a
        set a to b
        set b to x mod b
    end repeat

    if (a < 0) then return -a
    return a
end hcf

on isDuffinian(n)
    set aliquot to aliquotSum(n) -- = sigma sum - n. = 1 if n's prime.
    return ((aliquot > 1) and (hcf(n, aliquot + n) = 1))
end isDuffinian

-- Task code:
on matrixToText(matrix, w)
    script o
        property matrix : missing value
        property row : missing value
    end script

    set o's matrix to matrix
    set padding to "          "
    repeat with r from 1 to (count o's matrix)
        set o's row to o's matrix's item r
        repeat with i from 1 to (count o's row)
            set o's row's item i to text -w thru end of (padding & o's row's item i)
        end repeat
        set o's matrix's item r to join(o's row, "")
    end repeat

    return join(o's matrix, linefeed)
end matrixToText

on join(lst, delim)
    set astid to AppleScript's text item delimiters
    set AppleScript's text item delimiters to delim
    set txt to lst as text
    set AppleScript's text item delimiters to astid
    return txt
end join

on task(duffTarget, tupTarget, tupSize)
    if ((duffTarget < 1) or (tupTarget < 1) or (tupSize < 2)) then error "Duff parameter(s)."
    script o
        property duffinians : {}
        property tuplets : {}
    end script

    -- Populate o's duffinians and tuplets lists.
    set n to 1
    set tuplet to {}
    repeat while (((count o's tuplets) < tupTarget) or ((count o's duffinians) < duffTarget))
        if (isDuffinian(n)) then
            if ((count o's duffinians) < duffTarget) then set end of o's duffinians to n
            if (tuplet ends with n - 1) then
                set end of tuplet to n
            else
                if ((count tuplet) = tupSize) then set end of o's tuplets to tuplet
                set tuplet to {n}
            end if
        end if
        set n to n + 1
    end repeat

    -- Format for output.
    set duffinians to {}
    repeat with i from 1 to duffTarget by 20
        set j to i + 19
        if (j > duffTarget) then set j to duffTarget
        set end of duffinians to items i thru j of o's duffinians
    end repeat
    set part1 to "First " & duffTarget & " Duffinian numbers:" & linefeed & ¬
        matrixToText(duffinians, (count (end of o's duffinians as text)) + 2)
    set tupletTypes to {missing value, "twins", "triplets:", "quadruplets:", "quintuplets:"}
    set part2 to "First " & tupTarget & " Duffinian " & item tupSize of tupletTypes & linefeed & ¬
        matrixToText(o's tuplets, (count (end of end of o's tuplets as text)) + 2)

    return part1 & (linefeed & linefeed & part2)
end task

return task(50, 20, 3) -- First 50 Duffinians, first 20 3-item tuplets.


use feature 'say';
use ntheory qw(forprimes is_prime);

# Return the first $count emirps using expanding segments.
# Can efficiently generate millions of emirps.
sub emirp_list {
  my $count = shift;
  my($i, $inc, @n) = (13, 100+10*$count);
  while (@n < $count) {
    forprimes {
      push @n, $_ if is_prime(reverse $_) && $_ ne reverse($_);
    } $i, $i+$inc-1;
    ($i, $inc) = ($i+$inc, int($inc * 1.03) + 1000);
  }
  splice @n, $count;  # Trim off excess emirps
  @n;
}

say "First 20: ", join " ", emirp_list(20);
print "Between 7700 and 8000:";
forprimes { print " $_" if is_prime(reverse $_) && $_ ne reverse($_) } 7700,8000;
print "\n";
say "The 10_000'th emirp: ", (emirp_list(10000))[-1];


with javascript_semantics
sequence emirps = {}

function rev(integer n)
    integer res = 0
    while n do
        res = res*10+remainder(n,10)
        n = floor(n/10)
    end while
    return res
end function

function emirp(integer n)
    if is_prime(n) then
        integer r = rev(n)
        if r!=n and is_prime(r) then
            return true
        end if
    end if
    return false
end function

procedure usage()
    printf(1,"use a single command line argument, with no spaces, eg \"1-20\" (first 20), \n")
    printf(1,"\"7700..8000\" (between 7700 and 8000), or \"10000\" (the 10,000th).\n")
    {} = wait_key()
    abort(0)
end procedure

procedure main(string arg3)
    sequence args
    integer n,m
    if find('-',arg3) then      -- nth to mth emirp range
        args = scanf(arg3,"%d-%d")
        if length(args)!=1 then usage() end if
        {{n,m}} = args
        integer k = 1
        while length(emirps)<m do
            if emirp(k) then emirps &= k end if
            k += 1
        end while
        printf(1,"emirps %d to %d: %v\n",{n,m,emirps[n..m]})
    elsif match("..",arg3) then -- emirps between n amd m
        args = scanf(arg3,"%d..%d")
        if length(args)!=1 then usage() end if
        {{n,m}} = args
        integer k = 1
        while length(emirps)=0 or emirps[$]<m do
            if emirp(k) then emirps &= k end if
            k += 1
        end while
        sequence s = {}
        for i=1 to length(emirps) do
            if emirps[i]>n then
                for j=i to length(emirps) do
                    if emirps[j]>m then
                        printf(1,"emirps between %d and %d: %v\n",{n,m,emirps[i..j-1]})
                        exit
                    end if
                end for
                exit
            end if
        end for
    else                        -- nth emirp
        args = scanf(arg3,"%d")
        if length(args)!=1 then usage() end if
        {{n}} = args
        integer k = 1
        while length(emirps)<n do
            if emirp(k) then emirps &= k end if
            k += 1
        end while
        printf(1,"emirp %d: %d\n",{n,emirps[n]})
    end if
end procedure

sequence cl = command_line()
if length(cl)=2 then
    main("1-20")
    main("7700..8000")
    main("10000")
elsif length(cl)=3 then
    main(cl[3])
else
    usage()
end if


local socket = require("socket")

local function has_value(tab, value)
    for i, v in ipairs(tab) do
        if v == value then return i end
    end
    return false
end

local function checkOn(client)
   local line, err = client:receive()
	if line then
		client:send(line .. "\n")
	end
	if err and err ~= "timeout" then
		print(tostring(client) .. " " .. err)
		client:close()
		return true  -- end this connection
   end
	return false  -- do not end this connection
end

local server = assert(socket.bind("*",12321))
server:settimeout(0)  -- make non-blocking
local connections = { }  -- a list of the client connections
while true do
	local newClient = server:accept()
	if newClient then
		newClient:settimeout(0)  -- make non-blocking
		table.insert(connections, newClient)
	end
	local readList = socket.select({server, table.unpack(connections)})
	for _, conn in ipairs(readList) do
		if conn ~= server and checkOn(conn) then
			table.remove(connections, has_value(connections, conn))
		end
	end
end


server = SocketOpen[12321];
SocketListen[server, Function[{assoc},
  With[{client = assoc["SourceSocket"], input = assoc["Data"]},
   WriteString[client, ByteArrayToString[input]];
   ]
  ]]


duffinian?: function [n]->
    and? [not? prime? n]
         [
             fn: factors n
             [1] = intersection factors sum fn fn
         ]

first50: new []
i: 0
while [50 > size first50][
    if duffinian? i -> 'first50 ++ i
    i: i + 1
]

print "The first 50 Duffinian numbers:"
loop split.every: 10 first50 'row [
    print map to [:string] row 'item -> pad item 3
]

first15: new []
i: 0
while [15 > size first15][
    if every? i..i+2 => duffinian? [
        'first15 ++ @[@[i, i+1, i+2]]
        i: i+2
    ]
    i: i + 1
]

print ""
print "The first 15 Duffinian triplets:"
loop split.every: 5 first15 'row [
    print map row 'item -> pad.right as.code item 17
]


#include <iomanip>
#include <iostream>
#include <numeric>
#include <sstream>

bool duffinian(int n) {
    if (n == 2)
        return false;
    int total = 1, power = 2, m = n;
    for (; (n & 1) == 0; power <<= 1, n >>= 1)
        total += power;
    for (int p = 3; p * p <= n; p += 2) {
        int sum = 1;
        for (power = p; n % p == 0; power *= p, n /= p)
            sum += power;
        total *= sum;
    }
    if (m == n)
        return false;
    if (n > 1)
        total *= n + 1;
    return std::gcd(total, m) == 1;
}

int main() {
    std::cout << "First 50 Duffinian numbers:\n";
    for (int n = 1, count = 0; count < 50; ++n) {
        if (duffinian(n))
            std::cout << std::setw(3) << n << (++count % 10 == 0 ? '\n' : ' ');
    }
    std::cout << "\nFirst 50 Duffinian triplets:\n";
    for (int n = 1, m = 0, count = 0; count < 50; ++n) {
        if (duffinian(n))
            ++m;
        else
            m = 0;
        if (m == 3) {
            std::ostringstream os;
            os << '(' << n - 2 << ", " << n - 1 << ", " << n << ')';
            std::cout << std::left << std::setw(24) << os.str()
                      << (++count % 3 == 0 ? '\n' : ' ');
        }
    }
    std::cout << '\n';
}


<?php

function is_prime($n) {
    if ($n <= 3) {
        return $n > 1;
    } elseif (($n % 2 == 0) or ($n % 3 == 0)) {
        return false;
    }
    $i = 5;
    while ($i * $i <= $n) {
        if ($n % $i == 0) {
            return false;
        }
        $i += 2;
        if ($n % $i == 0) {
            return false;
        }
        $i += 4;
    }
    return true;
}

function is_emirp($n) {
    $r = (int) strrev((string) $n);
    return (($r != $n) and is_prime($r) and is_prime($n));
}

$c = $x = 0;
$first20 = $between = '';
do {
    $x++;
    if (is_emirp($x)) {
        $c++;
        if ($c <= 20) {
            $first20 .= $x . ' ';
        }
        if (7700 <= $x and $x <= 8000) {
            $between .= $x . ' ';
        }
    }
} while ($c < 10000);

echo
    'First twenty emirps :', PHP_EOL, $first20, PHP_EOL,
    'Emirps between 7,700 and 8,000 :', PHP_EOL, $between, PHP_EOL,
    'The 10,000th emirp :', PHP_EOL, $x, PHP_EOL;


import asyncnet, asyncdispatch

proc processClient(client: AsyncSocket) {.async.} =
  while true:
    let line = await client.recvLine()
    await client.send(line & "\c\L")

proc serve() {.async.} =
  var server = newAsyncSocket()
  server.bindAddr(Port(12321))
  server.listen()

  while true:
    let client = await server.accept()
    echo "Accepting connection from client", client.getLocalAddr[0]
    discard processClient(client)

discard serve()
runForever()


use Net;
use Concurrency;

bundle Default {
  class SocketServer {
    id : static : Int;

    function : Main(args : String[]) ~ Nil {
      server := TCPSocketServer->New(12321);
      if(server->Listen(5)) {
        while(true) {
          client := server->Accept();
          service := Service->New(id->ToString());
          service->Execute(client);
          id += 1;
        };
      };
      server->Close();
    }
  }

  class Service from Thread {
    New(name : String) {
      Parent(name);
    }

    method : public : Run(param : Base) ~ Nil {
      client := param->As(TCPSocket);
      line := client->ReadString();
      while(line->Size() > 0) {
        line->PrintLine();
        line := client->ReadString();
      };
    }
  }
}


USING: combinators.short-circuit.smart grouping io kernel lists
lists.lazy math math.primes math.primes.factors math.statistics
prettyprint sequences sequences.deep ;

: duffinian? ( n -- ? )
    { [ prime? not ] [ dup divisors sum simple-gcd 1 = ] } && ;

: duffinians ( -- list ) 3 lfrom [ duffinian? ] lfilter ;

: triples ( -- list )
    duffinians dup cdr dup cdr lzip lzip [ flatten ] lmap-lazy
    [ differences { 1 1 } = ] lfilter ;

"First 50 Duffinian numbers:" print
50 duffinians ltake list>array 10 group simple-table. nl

"First 15 Duffinian triplets:" print
15 triples ltake list>array simple-table.


package main

import (
    "fmt"
    "math"
    "rcu"
)

func isSquare(n int) bool {
    s := int(math.Sqrt(float64(n)))
    return s*s == n
}

func main() {
    limit := 200000 // say
    d := rcu.PrimeSieve(limit-1, true)
    d[1] = false
    for i := 2; i < limit; i++ {
        if !d[i] {
            continue
        }
        if i%2 == 0 && !isSquare(i) && !isSquare(i/2) {
            d[i] = false
            continue
        }
        sigmaSum := rcu.SumInts(rcu.Divisors(i))
        if rcu.Gcd(sigmaSum, i) != 1 {
            d[i] = false
        }
    }

    var duff []int
    for i := 1; i < len(d); i++ {
        if d[i] {
            duff = append(duff, i)
        }
    }
    fmt.Println("First 50 Duffinian numbers:")
    rcu.PrintTable(duff[0:50], 10, 3, false)

    var triplets [][3]int
    for i := 2; i < limit; i++ {
        if d[i] && d[i-1] && d[i-2] {
            triplets = append(triplets, [3]int{i - 2, i - 1, i})
        }
    }
    fmt.Println("\nFirst 56 Duffinian triplets:")
    for i := 0; i < 14; i++ {
        s := fmt.Sprintf("%6v", triplets[i*4:i*4+4])
        fmt.Println(s[1 : len(s)-1])
    }
}


sigmasum=: >:@#.~/.~&.q:
composite=: 1&< * 0 = 1&p:
duffinian=: composite * 1 = ] +. sigmasum


      is←{ t←⍵ ⋄ ⎕this⍎⍺,'←t' } ⍝⍝ the 'Slick Willie' function ;)
      'test' is ⍳2 3
      test
 1 1  1 2  1 3
 2 1  2 2  2 3


(de prime? (N)
   (and
      (bit? 1 N)
      (let S (sqrt N)
         (for (D 3  T  (+ D 2))
            (T (> D S) N)
            (T (=0 (% N D)) NIL) ) ) ) )
(de palindr? (A)
   (and
      (<>
         (setq A (chop A))
         (setq @@ (reverse A)) )
      (format @@) ) )
(de emirp? (N)
   (and (palindr? N) (prime? @) (prime? N)) )
(de take1 (N)
   (let I 11
      (make
         (for (X 1 (>= 20 X))
            (and
               (emirp? (inc 'I 2))
               (link @)
               (inc 'X) ) ) ) ) )
(de take2 (NIL)
   (make
      (for (I 7701 (> 8000 I) (+ I 2))
         (and (emirp? I) (link @)) ) ) )
(de take3 (NIL)
   (let I 11
      (for (X 1 (>= 10000 X))
         (and (emirp? (inc 'I 2)) (inc 'X)) )
      I ) )

(println (take1 20))
(println (take2))
(println (take3))


*process or(!);
 pt1: Proc(run) Options(main);
 /*********************************************************************
 * 25.03.2014 Walter Pachl
 * Note: Prime number computations are extended as needed
 *********************************************************************/
 Dcl debug Bit(1) Init('0'b);
 Dcl run Char(100) Var;
 Dcl primes(200000) Bin Fixed(31) Init(2,3,5,7,11,13,17,(200000-7)0);
 Dcl nn Bin Fixed(31) Init(0);
 Dcl np Bin Fixed(31) Init(7);
 Dcl hp Bin Fixed(31) Init(17);
 Dcl ip Bin Fixed(31);
 Dcl (p,r) Bin Fixed(31);
 Put Edit('run=',run,'<')(Skip,a,a,a);
 np=7;
 call cprimes(20,1,'A');

 main_loop:
 Do ip=1 To 100000;                    /* loop over all primes       */
   p=primes(ip);                       /* candidate                  */
   If p=0 Then
     call cprimes(20,hp+1,'.');
   p=primes(ip);                       /* candidate                  */
   r=rev(p);                           /* reversed candidate         */
   If p=r Then;                        /* skip palindromic prime     */
   Else Do;                            /* p is eligible              */
     If is_prime(r) Then Do;           /* reversed p is a prime      */
       nn=nn+1;                        /* increment number of hits   */
       Select;
         When(run<='1') Do;
           If nn<21 Then Call show_1;  /* call appropriate output    */
           If nn=20 Then
             Leave main_loop;
           End;
         When(run='2') Do;
           If hp<8000 Then
             Call cprimes(1,8000,'B');
           If 7700<p & p<8000 Then Call show_2;
           If p>8000 Then
             Leave main_loop;
           End;
         When(run='3') Do;
           If np<10000 Then
             Call cprimes(10000,1,'C');
           If nn=10000 Then Do;
             Call show_3;
             Leave main_loop;
             End;
           End;
         Otherwise Do;
           Put skip list('Invoke as pt1 1/2/3');
           Return;
           End;
         End;
       End;
     End;
   End;

 show_1: Proc;
 Dcl first Bit(1) Static Init('1'b);
 If first Then Do;
   Put Edit('the first 20 emirps:')(Skip,a);
   first='0'b;
   Put Skip;
   End;
 If nn=11 Then
   Put Skip;
 Put Edit(p)(F(4));
 End;

 show_2: Proc;
 Dcl first Bit(1) Static Init('1'b);
 If first Then Do;
   Put Edit('emirps between 7700 and 8000:')(Skip,a);
   first='0'b;
   Put Skip;
   End;
 Put Edit(p)(F(5));
 End;

 show_3: Proc;
 Dcl first Bit(1) Static Init('1'b);
 If first Then Do;
   Put Edit('the 10000th emirp:')(Skip,a);
   first='0'b;
   Put Skip;
   End;
 Put Edit(p)(F(6));
 End;

 cprimes: Proc(num,mp,s);
 /*********************************************************************
 * Fill the array primes with prime numbers
 * so that it contains at least num primes and all primes<=mp
 *********************************************************************/
 dcl o Char(60) Var;
 If debug Then
   Put String(o) Edit('cprimes: ',s,np,hp)(a,a,2(f(6)));
 Dcl num Bin Fixed(31);                /* number of primes needed    */
 Dcl mp  Bin Fixed(31);                /* max prime must be > mp     */
 Dcl p   Bin Fixed(31);                /* candidate for next prime   */
 Dcl s   Char(1);                      /* place of invocation        */
 loop:
 Do p=hp+2 By 2 Until(np>=num & hp>mp); /* only odd numbers are elig.*/
   If mod(p, 3)=0 Then Iterate;
   If mod(p, 5)=0 Then Iterate;
   If mod(p, 7)=0 Then Iterate;
   If mod(p,11)=0 Then Iterate;
   If mod(p,13)=0 Then Iterate;
   Do k=7 By 1 While(primes(k)**2<=p);
     If mod(p,primes(k))=0 Then
       Iterate loop;
     End;
   np=np+1;
   primes(np)=p;
   hp=p;
   End;
  If debug Then
    Put Edit(o,' -> ',np,hp)(Skip,a,a,2(f(6)));
  End;

 rev: Proc(x) Returns(Bin Fixed(31));
 /*********************************************************************
 * reverse the given number
 *********************************************************************/
 Dcl x Bin Fixed(31);
 Dcl p Pic'ZZZZZZ9';
 Dcl qq Char(7) Init('');
 Dcl q Pic'ZZZZZZ9' based(addr(qq));
 Dcl v Char(8) Var;
 p=x;
 v=trim(p);
 v=reverse(v);
 substr(qq,8-length(v))=v;
 Return(q);
 End;

 is_prime: Proc(x) Returns(Bit(1));
 /*********************************************************************
 * check if x is a prime number (binary search in primes)
 *********************************************************************/
 Dcl x  Bin Fixed(31);
 Dcl lo Bin Fixed(31) Init(1);
 Dcl hi Bin Fixed(31);
 Dcl m  Bin Fixed(31);
 If x>hp Then Do;                 /* x is outside of range in primes */
   If debug Then
     Put Edit('is_prime x=',x,'hp=',hp)(Skip,2(a,f(8),x(1)));
   Call cprimes(1,x,'D');         /* extend range of primes          */
   End;
 hi=np;
 Do While(lo<=hi);                /* lookup                          */
   m=(lo+hi)/2;
   Select;
     When        (x=primes(m))   Return('1'b); /* x is a prime number*/
     When        (x<primes(m))   hi=m-1;
     Otherwise /* x>primes(m) */ lo=m+1;
     End;
   End;
 Return('0'b);                    /* x is not a prime number         */
 End;

 End;


(define (timestamp) (syscall 201 "%c"))

(define (on-accept name fd)
(lambda ()
   (print "# " (timestamp) "> we got new visitor: " name)

   (let*((ss1 ms1 (clock)))
      (let loop ((str #null) (stream (force (port->bytestream fd))))
         (cond
            ((null? stream)
               #false)
            ((function? stream)
               (let ((message (list->string (reverse str))))
                  (print "# " (timestamp) "> client " name " wrote " message)
                  (print-to fd message))
               (loop #null (force stream)))
            (else
               (loop (cons (car stream) str) (cdr stream)))))
      (syscall 3 fd)
      (let*((ss2 ms2 (clock)))
         (print "# " (timestamp) "> visitor leave us. It takes "  (+ (* (- ss2 ss1) 1000) (- ms2 ms1)) "ms.")))))

(define (run port)
(let ((socket (syscall 41)))
   ; bind
   (let loop ((port port))
      (if (not (syscall 49 socket port)) ; bind
         (loop (+ port 2))
         (print "Server binded to " port)))
   ; listen
   (if (not (syscall 50 socket)) ; listen
      (shutdown (print "Can't listen")))

   ; accept
   (let loop ()
      (if (syscall 23 socket) ; select
         (let ((fd (syscall 43 socket))) ; accept
            (fork (on-accept (syscall 51 fd) fd))))
      (sleep 0)
      (loop))))

(run 12321)


using Primes

function σ(n)
    f = [one(n)]
    for (p,e) in factor(n)
        f = reduce(vcat, [f*p^j for j in 1:e], init=f)
    end
    return sum(f)
end

isDuffinian(n) = !isprime(n) && gcd(n, σ(n)) == 1

function testDuffinians()
    println("First 50 Duffinian numbers:")
    foreach(p -> print(rpad(p[2], 4), p[1] % 25 == 0 ? "\n" : ""),
        enumerate(filter(isDuffinian, 2:217)))
    n, found = 2, 0
    println("\nFifteen Duffinian triplets:")
    while found < 15
        if isDuffinian(n) && isDuffinian(n + 1) && isDuffinian(n + 2)
            println(lpad(n, 6), lpad(n +1, 6), lpad(n + 2, 6))
            found += 1
        end
        n += 1
    end
end

testDuffinians()


ClearAll[DuffianQ]
DuffianQ[n_Integer] := CompositeQ[n] \[And] CoprimeQ[DivisorSigma[1, n], n]
dns = Select[DuffianQ][Range[1000000]];
Take[dns, UpTo[50]]
triplets = ToString[dns[[#]]] <> "\[LongDash]" <> ToString[dns[[# + 2]]] & /@ SequencePosition[Differences[dns], {1, 1}][[All, 1]]
Multicolumn[triplets, {Automatic, 5}, Appearance -> "Horizontal"]


use strict;
use warnings;
use feature <say state>;
use List::Util 'max';
use ntheory qw<divisor_sum is_prime gcd>;

sub table { my $t = shift() * (my $c = 1 + max map {length} @_); ( sprintf( ('%'.$c.'s')x@_, @_) ) =~ s/.{1,$t}\K/\n/gr }

sub duffinian {
    my($n) = @_;
    state $c = 1; state @D;
    do { push @D, $c if ! is_prime ++$c and 1 == gcd($c,divisor_sum($c)) } until @D > $n;
    $D[$n];
}

say "First 50 Duffinian numbers:";
say table 10, map { duffinian $_-1 } 1..50;

my(@d3,@triples) = (4, 8, 9); my $n = 3;
while (@triples < 39) {
    push @triples, '('.join(', ',@d3).')' if $d3[1] == 1+$d3[0] and $d3[2] == 2+$d3[0];
    shift @d3 and push @d3, duffinian ++$n;
}

say 'First 39 Duffinian triplets:';
say table 3, @triples;


name: strip input "enter a variable name: "
value: strip input "enter a variable value: "

let name value

print ["the value of variable" name "is:" var name]


InputBox, Dynamic, Variable Name
%Dynamic% = hello
ListVars
MsgBox % %dynamic%  ; says hello


# syntax: GAWK -f DYNAMIC_VARIABLE_NAMES.AWK
# Variables created in GAWK's internal SYMTAB (symbol table) can only be accessed via SYMTAB[name]
BEGIN {
    PROCINFO["sorted_in"] = "@ind_str_asc"
    show_symbol_table()
    while (1) {
      printf("enter variable name? ")
      getline v_name
      if (v_name in SYMTAB) {
        printf("name already exists with a value of '%s'\n",SYMTAB[v_name])
        continue
      }
      if (v_name ~ /^$/) {
        printf("name is null\n")
        continue
      }
      if (v_name !~ /^[A-Za-z][A-Za-z0-9_]*$/) {
        printf("name illegally constructed\n")
        continue
      }
      break
    }
    printf("enter value? ")
    getline v_value
    SYMTAB[v_name] = v_value
    printf("variable '%s' has been created and assigned the value '%s'\n\n",v_name,v_value)
    show_symbol_table()
    exit(0)
}
function show_symbol_table(  count,i) {
    for (i in SYMTAB) {
      printf("%s ",i)
      if (isarray(SYMTAB[i])) { count++ }
    }
    printf("\nsymbol table contains %d names of which %d are arrays\n\n",length(SYMTAB),count)
}


10 INPUT "Enter a variable name", v$
20 KEYIN "LET "+v$+"=42"


from __future__ import print_function
from prime_decomposition import primes, is_prime
from heapq import *
from itertools import islice

def emirp():
    largest = set()
    emirps = []
    heapify(emirps)
    for pr in primes():
        while emirps and pr > emirps[0]:
            yield heappop(emirps)
        if pr in largest:
            yield pr
        else:
            rp = int(str(pr)[::-1])
            if rp > pr and is_prime(rp):
                heappush(emirps, pr)
                largest.add(rp)

print('First 20:\n  ', list(islice(emirp(), 20)))
print('Between 7700 and 8000:\n  [', end='')
for pr in emirp():
    if pr >= 8000: break
    if pr >= 7700: print(pr, end=', ')
print(']')
print('10000th:\n  ', list(islice(emirp(), 10000-1, 10000)))


  1000000 eratosthenes

  [ [] swap
    [ dup 0 != while
      10 /mod
      rot swap join swap
      again ]
    swap
    witheach
      [ dip [ 10 * ] + ] ] is revnum ( n --> n )

  [ dup isprime not iff
      [ drop false ] done
    dup revnum tuck = iff
      [ drop false ] done
    isprime ]              is emirp  ( n --> b )

  [] 0
  [ 1+ dup emirp if
      [ tuck join swap ]
    over size 20 = until ]
  drop
  echo cr
  [] 7700
    [ 1+ dup emirp if
      [ tuck join swap ]
    dup 8000 = until ]
  drop
  echo cr
  0 0
  [ 1+ dup emirp if
      [ dip 1+ ]
    over 10000 = until ]
  nip echo cr


declare
  ServerSocket = {New Open.socket init}

  proc {Echo Socket}
     case {Socket getS($)} of false then skip
     [] Line then
        {System.showInfo "Received line: "#Line}
        {Socket write(vs:Line#"\n")}
        {Echo Socket}
     end
  end

  class TextSocket from Open.socket Open.text end
in
  {ServerSocket bind(takePort:12321)}
  {System.showInfo "Socket bound."}

  {ServerSocket listen}
  {System.showInfo "Started listening."}

  for do
     ClientHost ClientPort
     ClientSocket = {ServerSocket accept(accepted:$
					 acceptClass:TextSocket
					 host:?ClientHost
					 port:?ClientPort
					)}
  in
     {System.showInfo "Connection accepted from "#ClientHost#":"#ClientPort#"."}
     thread
        {Echo ClientSocket}

	{System.showInfo "Connection lost: "#ClientHost#":"#ClientPort#"."}
        {ClientSocket close}
     end
  end


use IO::Socket;
my $use_fork = 1;

my $sock = new IO::Socket::INET (
                                 LocalHost => '127.0.0.1',
                                 LocalPort => '12321',
                                 Proto => 'tcp',
                                 Listen => 1,   # maximum queued connections
                                 Reuse => 1,
                                )
		or die "socket: $!";	# no newline, so perl appends stuff

$SIG{CHLD} = 'IGNORE' if $use_fork;	# let perl deal with zombies

print "listening...\n";
while (1) {
	# declare $con 'my' so it's closed by parent every loop
        my $con = $sock->accept()
		or die "accept: $!";
	fork and next if $use_fork;	# following are for child only

	print "incoming..\n";
	print $con $_ while(<$con>);	# read each line and write back
	print "done\n";

	last	if $use_fork;	# if not forking, loop
}

# child will reach here and close its copy of $sock before exit


with javascript_semantics
sequence duffinian = {false}
integer n = 2, count = 0, triplet = 0, triple_count = 0
while triple_count<50 do
    bool bDuff = not is_prime(n) and gcd(n,sum(factors(n,1)))=1
    duffinian &= bDuff
    if bDuff then
        count += 1
        if count=50 then
            sequence s50 = apply(true,sprintf,{{"%3d"},find_all(true,duffinian)})
            printf(1,"First 50 Duffinian numbers:\n%s\n",join_by(s50,1,25," "))
        end if
        triplet += 1
        triple_count += (triplet>=3)
    else
        triplet = 0
    end if
    n += 1
end while
sequence s = apply(true,sq_add,{match_all({true,true,true},duffinian),{{0,1,2}}}),
         p = apply(true,pad_tail,{apply(true,sprintf,{{"[%d,%d,%d]"},s}),24})
printf(1,"First 50 Duffinian triplets:\n%s\n",{join_by(p,1,4," ")})


use Prime::Factor;

my @duffinians = lazy (3..*).hyper.grep: { !.is-prime && $_ gcd .&divisors.sum == 1 };

put "First 50 Duffinian numbers:\n" ~
@duffinians[^50].batch(10)».fmt("%3d").join: "\n";

put "\nFirst 40 Duffinian triplets:\n" ~
    ((^∞).grep: -> $n { (@duffinians[$n] + 1 == @duffinians[$n + 1]) && (@duffinians[$n] + 2 == @duffinians[$n + 2]) })[^40]\
    .map( { "({@duffinians[$_ .. $_+2].join: ', '})" } ).batch(4)».fmt("%-24s").join: "\n";


@echo off
setlocal enableDelayedExpansion

set /p "name=Enter a variable name: "
set /p "value=Enter a value: "

::Create the variable and set its value
set "%name%=%value%"

::Display the value without delayed expansion
call echo %name%=%%%name%%%

::Display the value using delayed expansion
echo %name%=!%name%!


      INPUT "Enter a variable name: " name$
      INPUT "Enter a numeric value: " numeric$
      dummy% = EVAL("FNassign("+name$+","+numeric$+")")
      PRINT "Variable " name$ " now has the value "; EVAL(name$)
      END

      DEF FNassign(RETURN n, v) : n = v : = 0


( put$"Enter a variable name: "
& get$:?name
&   whl
  ' ( put$"Enter a numeric value: "
    & get$:?numeric:~#
    )
& !numeric:?!name
& put$(str$("Variable " !name " now has the value " !!name \n))
);


using System;
using System.Dynamic;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        string varname = Console.ReadLine();
        //Let's pretend the user has entered "foo"
        dynamic expando = new ExpandoObject();
        var map = expando as IDictionary<string, object>;
        map.Add(varname, "Hello world!");

        Console.WriteLine(expando.foo);
    }
}


library(gmp)

emirp <- function(start = 1, end = Inf, howmany = Inf, ignore = 0) {
	count <- 0
	p <- start

	while (count<howmany+ignore && p <= end) {
		p <- nextprime(p)
		p_reverse <- as.bigz(paste0(rev(unlist(strsplit(as.character(p), ""))), collapse = ""))
		if (p != p_reverse && isprime(p_reverse) > 0) {
			if (count >= ignore) cat(as.character(p)," ",sep="")
			count <- count + 1
		}
	}
	cat("\n")
}
cat("First 20 emirps: ")
emirp(howmany = 20)

cat("Emirps between 7700 and 8000: ")
emirp(start = 7700, end = 8000)

cat("The 10000th emirp: ")
emirp(ignore = 9999, howmany = 1)


(my naive version finds the 10,0000th in ... ms)


-- demo\rosetta\EchoServer.exw
without js
include builtins\sockets.e
constant ESCAPE = #1B
procedure echo(atom sockd)
    ?{"socket opened",sockd}
    string buffer = ""
    integer bytes_sent
    bool first = true
    while true do
        {integer len, string s} = recv(sockd)
        if len<=0 then exit end if
        if first then
            bytes_sent = send(sockd, s) -- partial echo, see note
            first = false
        end if
        buffer &= s
        if s[$]='\n' then
            bytes_sent = send(sockd, buffer)
            buffer = ""
        end if
    end while
    ?{"socket disconnected",sockd}
end procedure

atom list_s = socket(AF_INET,SOCK_STREAM,NULL),
     pSockAddr = sockaddr_in(AF_INET, "", 12321)
if list_s<0 then ?9/0 end if
if bind(list_s, pSockAddr)=SOCKET_ERROR then crash("bind (%v)",{get_socket_error()}) end if
if listen(list_s,100)=SOCKET_ERROR then crash("listen (%v)",{get_socket_error()}) end if
puts(1,"echo server started, press escape or q to exit\n")
while not find(get_key(),{ESCAPE,'q','Q'}) do
    {integer code} = select({list_s},{},{},250000)  -- (0.25s)
    if code=SOCKET_ERROR then crash("select (%v)",{get_socket_error()}) end if
    if code>0 then  -- (not timeout)
        atom conn_s = accept(list_s)
        if conn_s=SOCKET_ERROR then ?9/0 end if
        atom hThread = create_thread(echo,{conn_s})
    end if
end while
list_s = closesocket(list_s)
WSACleanup()


func is_duffinian(n) {
    n.is_composite && n.is_coprime(n.sigma)
}

say "First 50 Duffinian numbers:"
say 50.by(is_duffinian)

say "\nFirst 15 Duffinian triplets:"
15.by{|n| ^3 -> all {|k| is_duffinian(n+k) } }.each {|n|
    printf("(%s, %s, %s)\n", n, n+1, n+2)
}


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

var limit = 200000  // say
var d = Int.primeSieve(limit-1, false)
d[1] = false
for (i in 2...limit) {
    if (!d[i]) continue
    if (i % 2 == 0 && !Int.isSquare(i) && !Int.isSquare(i/2)) {
        d[i] = false
        continue
    }
    var sigmaSum = Nums.sum(Int.divisors(i))
    if (Int.gcd(sigmaSum, i) != 1) d[i] = false
}

var duff = (1...d.count).where { |i| d[i] }.toList
System.print("First 50 Duffinian numbers:")
for (chunk in Lst.chunks(duff[0..49], 10)) Fmt.print("$3d", chunk)

var triplets = []
for (i in 2...limit) {
    if (d[i] && d[i-1] && d[i-2]) triplets.add([i-2, i-1, i])
}
System.print("\nFirst 50 Duffinian triplets:")
for (chunk in Lst.chunks(triplets[0..49], 4)) Fmt.print("$-25s", chunk)


func IsPrime(N);        \Return 'true' if N is prime
int  N, I;
[if N <= 2 then return N = 2;
if (N&1) = 0 then \even >2\ return false;
for I:= 3 to sqrt(N) do
    [if rem(N/I) = 0 then return false;
    I:= I+1;
    ];
return true;
];

func    SumDiv(Num);    \Return sum of proper divisors of Num
int     Num, Div, Sum, Quot;
[Div:= 2;
Sum:= 0;
loop    [Quot:= Num/Div;
        if Div > Quot then quit;
        if rem(0) = 0 then
            [Sum:= Sum + Div;
            if Div # Quot then Sum:= Sum + Quot;
            ];
        Div:= Div+1;
        ];
return Sum+1;
];

func GCD(A, B);         \Return greatest common divisor of A and B
int  A, B;
[while A#B do
  if A>B then A:= A-B
         else B:= B-A;
return A;
];

func Duff(N);           \Return 'true' if N is a Duffinian number
int  N;
[if IsPrime(N) then return false;
return GCD(SumDiv(N), N) = 1;
];

int C, N;
[Format(4, 0);
C:= 0;  N:= 4;
loop    [if Duff(N) then
            [RlOut(0, float(N));
            C:= C+1;
            if C >= 50 then quit;
            if rem(C/20) = 0 then CrLf(0);
            ];
        N:= N+1;
        ];
CrLf(0);  CrLf(0);
Format(5, 0);
C:= 0;  N:= 4;
loop    [if Duff(N) & Duff(N+1) & Duff(N+2) then
            [RlOut(0, float(N));  RlOut(0, float(N+1));  RlOut(0, float(N+2));
            CrLf(0);
            C:= C+1;
            if C >= 15 then quit;
            ];
        N:= N+1;
        ];
]


(setq var-name (read))  ; reads a name into var-name
(set var-name 1)        ; assigns the value 1 to a variable named as entered by the user


local :var-name !run-blob !compile-string dup concat( ":" !prompt "Enter a variable name: " )
local var-name 42

#Assuming the user types THISISWEIRD, otherwise this'll error
!. THISISWEIRD