def makeNounExpr := <elang:evm.makeNounExpr>

def dynVarName(name) {
    def variable := makeNounExpr(null, name, null)

    return e`{

        def a := 1
        def b := 2
        def c := 3

        {
            def $variable := "BOO!"
            [a, b, c]
        }

    }`.eval(safeScope)
}

? dynVarName("foo")
# value: [1, 2, 3]

? dynVarName("b")
# value: [1, "BOO!", 3]

? dynVarName("c")
# value: [1, 2, "BOO!"]


import system'dynamic;
import extensions;

class TestClass
{
    object theVariables;

    constructor()
    {
        theVariables := new DynamicStruct()
    }

    function()
    {
        auto prop := new MessageName(console.write:"Enter the variable name:".readLine());
        (prop.setPropertyMessage())(theVariables,42);

        console.printLine(prop.toPrintable(),"=",(prop.getPropertyMessage())(theVariables)).readChar()
    }
}

public program = new TestClass();


(set (intern (read-string "Enter variable name: ")) 123)


use Math::Primesieve;

sub prime-hash (Int $max) {
    my $sieve = Math::Primesieve.new;
    my @primes = $sieve.primes($max);
    @primes.Set;
}

sub MAIN ($start, $stop = Nil, $display = <slice>) {
    my $end = $stop // $start;
    my %primes = prime-hash(100*$end);
    my @emirps = lazy gather for 1 .. * -> $n {
        take $n if %primes{$n} and %primes{$n.flip} and $n != $n.flip
    }

    given $display {
        when 'slice'  { return @emirps[$start-1 .. $end-1] };
        when 'values' {
            my @values = gather for @emirps {
                .take if $start < $_ < $end;
                last if $_> $end
            }
            return @values
        }
    }
}


/*REXX program finds  emirp  primes (base 10):  when a prime reversed, is another prime.*/
parse arg x y .                                  /*obtain optional arguments from the CL*/
if x=='' | x==","  then do;  x=1;  y=20;  end    /*Not specified?  Then use the default.*/
if y==''  then y=x                               /* "      "         "   "   "     "    */
r=y<0;    y=abs(y)                               /*display a  range  of  emirp primes ? */
rly=length(y) + \r                               /*adjusted length of the  Y  value.    */
!.=0;  c=0;   _=2 3 5 7 11 13 17;   $=           /*isP; emirp count; low primes; emirps.*/
    do #=1  for words(_);   p=word(_,#);   @.#=p;    !.p=1;    end  /*#*/
#=#-1;   ip=#;  s.#[email protected].#**2                       /*adjust # (for the DO loop);  last P².*/
                            /*▒▒▒▒▒▒▒▒▒▒▒▒▒▒ [↓]   generate more primes within range.   */
    do [email protected].#+2  by 2                             /*only find  odd  primes from here on. */
    if length(#)>rly  then leave                 /*have we enough primes for emirps?    */
    if j//3      ==0  then iterate               /*is  J  divisible by three?           */
    if right(j,1)==5  then iterate               /*is the right-most digit a "5" ?      */
    if j//7      ==0  then iterate               /*is  J  divisible by seven?           */
    if j//11     ==0  then iterate               /*is  J  divisible by eleven?          */
    if j//13     ==0  then iterate               /*is  J  divisible by thirteen?        */
                                                 /*[↑]  the above five lines saves time.*/
          do k=ip  while  s.k<=j                 /*divide by the known  odd  primes.    */
          if j//@.k==0  then iterate j           /*J divisible by X?  Then ¬prime.   ___*/
          end   /*k*/                            /* [↑]  divide by odd primes up to √ j */
    #=#+1                                        /*bump the number of primes found.     */
    @.#=j;      s.#=j*j;     !.j=1               /*assign to sparse array; prime²; prime*/
    end         /*j*/                            /* [↑]  keep generating until enough.  */
                            /*▒▒▒▒▒▒▒▒▒▒▒▒▒▒ [↓]    filter  emirps  for the display.    */
    do j=6  to @.#;   [email protected].j                      /*traipse through the regular primes.  */
    if (r&_>y) | (\r&c==y)  then leave           /*is the prime not within the range?   */
    __=reverse(_)                                /*reverse (digits) of the regular prime*/
    if \!.__   | _==__    then iterate           /*is the  reverse  a different prime ? */
    c=c+1                                        /*bump the emirp prime counter.        */
    if (r&_<x) | (\r&c<x) then iterate           /*is  emirp  not within allowed range? */
    $=$ _                                        /*append prime to the emirpPrime list. */
    end   /*j*/                                  /* [↑]  list:  by value  or  by range. */
                                                 /* [↓]  display the emirp list.        */
say strip($);   say;   n=words($);   ?=(n\==1)   /*display the  emirp primes  wanted.   */
if ?  then say  n   'emirp primes shown.'        /*stick a fork in it,  we're all done. */


$socket = socket_create(AF_INET,SOCK_STREAM,SOL_TCP);
socket_bind($socket, '127.0.0.1', 12321);
socket_listen($socket);

$client_count = 0;
while (true){
  if (($client = socket_accept($socket)) === false) continue;
  $client_count++;

  $client_name = 'Unknown';
  socket_getpeername($client, $client_name);
  echo "Client {$client_count} ({$client_name}) connected\n";
  $pid = pcntl_fork();
  if($pid == -1) die('Could not fork');
  if($pid){
    pcntl_waitpid(-1, $status, WNOHANG);
    continue;
  }

  //In a child process
  while(true){
    if($input = socket_read($client, 1024)){
      socket_write($client, $input);
    } else {
      socket_shutdown($client);
      socket_close($client);
      echo "Client {$client_count} ({$client_name}) disconnected\n";
      exit();
    }
  }
}


(setq Port (port 12321))

(loop
   (setq Sock (listen Port))           # Listen
   (NIL (fork) (close Port))           # Accepted
   (close Sock) )                      # Parent: Close socket and continue

# Child:
(prinl (stamp) " -- (Pid " *Pid ") Client connected from " *Adr)

(in Sock
   (until (eof)                        # Echo lines
      (out Sock (prinl (line))) ) )

(prinl (stamp) " -- (Pid " *Pid ") Client disconnected")
(bye)                                  # Terminate child


--Add user-defined variable to the stack
const VarName: io.prompt("Input Variable Name: "),
	VarValue: io.prompt("Input Variable Value: ")

debug.newvar(VarName,VarValue)

--Outputting the results
log(debug.getvar(VarName))


-module( dynamic_variable_names ).

-export( [task/0] ).

task() ->
    {ok,[Variable_name]} = io:fread( "Variable name? ",	"~a" ),
    Form = runtime_evaluation:form_from_string( erlang:atom_to_list(Variable_name) ++ "." ),
    io:fwrite( "~p has value ~p~n", [Variable_name, runtime_evaluation:evaluate_form(Form, {Variable_name, 42})] ).


s" VARIABLE " pad swap move
." Variable name: " pad 9 + 80 accept
pad swap 9 + evaluate


' FB 1.05.0 Win64

Type DynamicVariable
  As String name
  As String value
End Type

Function FindVariableIndex(a() as DynamicVariable, v as String, nElements As Integer) As Integer
  v = LCase(Trim(v))
  For i As Integer = 1 To nElements
    If a(i).name = v Then Return i
  Next
  Return 0
End Function

Dim As Integer n, index
Dim As String v
Cls

Do
 Input "How many variables do you want to create (max 5) "; n
Loop Until n > 0 AndAlso n < 6

Dim a(1 To n) As DynamicVariable
Print
Print "OK, enter the variable names and their values, below"

For i As Integer = 1 to n
  Print
  Print "  Variable"; i
  Input "    Name  : ", a(i).name
  a(i).name = LCase(Trim(a(i).name)) ' variable names are not case sensitive in FB
  If i > 0 Then
     index = FindVariableIndex(a(), a(i).name, i - 1)
     If index > 0 Then
       Print "  Sorry, you've already created a variable of that name, try again"
       i -= 1
       Continue For
     End If
  End If
  Input "    Value : ", a(i).value
  a(i).value = LCase(Trim(a(i).value))
Next

Print
Print "Press q to quit"
Do
  Print
  Input "Which variable do you want to inspect "; v
  If v = "q" OrElse v = "Q" Then Exit Do
  index = FindVariableIndex(a(), v, n)
  If index = 0 Then
    Print "Sorry there's no variable of that name, try again"
  Else
    Print "It's value is "; a(index).value
  End If
Loop
End


nr = 1
m = 2
see "first 20 :" + nl
while nr < 21
      emirp = isEmirp(m)
      if emirp = 1 see m see " "
         nr++ ok
      m++
end
see nl + nl

nr = 1
m = 7701
see "between 7700 8000 :" + nl
while m > 7700 and m < 8000
      emirp = isEmirp(m)
      if emirp = 1 see m see " " nr++ ok
      m++
end
see nl + nl

nr = 1
m = 2
see "Nth 10000 :" + nl
while nr > 0 and nr < 101
      emirp = isEmirp(m)
      if emirp = 1 nr++ ok
      m++
end
see m + nl

func isEmirp n
     if not isPrime(n) return false ok
     cStr = string(n)
     cstr2 = ""
     for x = len(cStr) to 1 step -1 cStr2 += cStr[x] next
     rev = number(cstr2)
     if rev = n return false ok
     return isPrime(rev)

func isPrime n
     if n < 2 return false ok
     if n < 4 return true ok
     if n % 2 = 0 return false ok
     for d = 3 to sqrt(n) step 2
         if n % d = 0 return false ok
     next
     return true


require 'prime'

emirp = Enumerator.new do |y|
  Prime.each do |prime|
    rev = prime.to_s.reverse.to_i
    y << prime  if rev.prime? and rev != prime
  end
end

puts "First 20 emirps:", emirp.first(20).join(" ")
puts "Emirps between 7,700 and 8,000:"
emirp.with_index(1) do |prime,i|
  print "#{prime} "  if (7700..8000).cover?(prime)
  if i==10000
    puts "", "10,000th emirp:", prime
    break
  end
end


#![feature(iterator_step_by)]

extern crate primal;

fn is_prime(n: u64) -> bool {
    if n == 2 || n == 3 || n == 5 || n == 7 || n == 11 || n == 13 { return true; }
    if n % 2 == 0 || n % 3 == 0 || n % 5 == 0 || n % 7 == 0 || n % 11 == 0 || n % 13 == 0 { return false; }
    let root = (n as f64).sqrt() as u64 + 1;
    (17..root).step_by(2).all(|i| n % i != 0)
}

fn is_emirp(n: u64) -> bool {
    let mut aux = n;
    let mut rev_prime = 0;
    while aux > 0 {
        rev_prime = rev_prime * 10 + aux  % 10;
        aux /= 10;
    }
    if n == rev_prime { return false; }
    is_prime(rev_prime)
}

fn calculate() -> (Vec<usize>, Vec<usize>, usize) {
    let mut count = 1;
    let mut vec1 = Vec::new();
    let mut vec2 = Vec::new();
    let mut emirp_10_000 = 0;

    for i in primal::Primes::all() {
        if is_emirp(i as u64) {
            if count < 21 { vec1.push(i) }
            if i > 7_700 && i < 8_000 { vec2.push(i) }
            if count == 10_000 {
                emirp_10_000 = i;
                break;
            }
            count += 1;
        }
    }

    (vec1, vec2, emirp_10_000)
}

fn main() {
    let (vec1, vec2, emirp_10_000) = calculate();

    println!("First 20 emirp-s : {:?}", vec1);
    println!("Emirps-s between 7700 and 8000 : {:?}", vec2);
    println!("10.000-th emirp : {}", emirp_10_000);
}


NewMap RecData.s()
OpenWindow(0, 100, 200, 200, 100, "Echo Server", #PB_Window_SystemMenu | #PB_Window_MinimizeGadget )
InitNetwork()
CreateNetworkServer(1, 12321)

Repeat
   Event = NetworkServerEvent()
   ClientID = EventClient()

   If Event = #PB_NetworkEvent_Connect    ; When a new client has been connected...
      AddMapElement(RecData(), Str(ClientID))

   ElseIf Event = #PB_NetworkEvent_Data
      *Buffer = AllocateMemory(20000)
      count = ReceiveNetworkData(ClientID, *Buffer, 20000)
      For i = 1 To count
         RecData(Str(ClientID)) + Mid( PeekS(*Buffer, count), i , 1)
         If Right( RecData(Str(ClientID)), 2) = #CRLF$
            SendNetworkString (ClientID, RecData(Str(ClientID)))
            Debug  IPString(GetClientIP(ClientID)) + ":" + Str(GetClientPort(ClientID)) + "  " + RecData(Str(ClientID))
            RecData(Str(ClientID)) = ""
         EndIf
      Next
      FreeMemory(*Buffer)

   ElseIf Event = #PB_NetworkEvent_Disconnect  ; When a client has closed the connection...
      DeleteMapElement(RecData(), Str(ClientID))
   EndIf

   Event = WaitWindowEvent(10)
Until Event = #PB_Event_CloseWindow


import SocketServer

HOST = "localhost"
PORT = 12321

# this server uses ThreadingMixIn - one thread per connection
# replace with ForkMixIn to spawn a new process per connection

class EchoServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
    # no need to override anything - default behavior is just fine
    pass

class EchoRequestHandler(SocketServer.StreamRequestHandler):
    """
    Handles one connection to the client.
    """
    def handle(self):
        print "connection from %s" % self.client_address[0]
        while True:
            line = self.rfile.readline()
            if not line: break
            print "%s wrote: %s" % (self.client_address[0], line.rstrip())
            self.wfile.write(line)
        print "%s disconnected" % self.client_address[0]

# Create the server
server = EchoServer((HOST, PORT), EchoRequestHandler)

# Activate the server; this will keep running until you
# interrupt the program with Ctrl-C
print "server listening on %s:%s" % server.server_address
server.serve_forever()


# As is, will not work if val is a String
Assign := function(var, val)
	Read(InputTextString(Concatenation(var, " := ", String(val), ";")));
end;


defvar (intern 'This is not a pipe.') 42
define |<weird>| 2009


package main

import (
    "bufio"
    "fmt"
    "log"
    "os"
    "strconv"
    "strings"
)

func check(err error) {
    if err != nil {
        log.Fatal(err)
    }
}

func main() {
    scanner := bufio.NewScanner(os.Stdin)
    n := 0
    for n < 1 || n > 5 {
        fmt.Print("How many integer variables do you want to create (max 5) : ")
        scanner.Scan()
        n, _ = strconv.Atoi(scanner.Text())
        check(scanner.Err())
    }
    vars := make(map[string]int)
    fmt.Println("OK, enter the variable names and their values, below")
    for i := 1; i <= n; {
        fmt.Println("\n  Variable", i)
        fmt.Print("    Name  : ")
        scanner.Scan()
        name := scanner.Text()
        check(scanner.Err())
        if _, ok := vars[name]; ok {
            fmt.Println("  Sorry, you've already created a variable of that name, try again")
            continue
        }
        var value int
        var err error
        for {
            fmt.Print("    Value : ")
            scanner.Scan()
            value, err = strconv.Atoi(scanner.Text())
            check(scanner.Err())
            if err != nil {
                fmt.Println("  Not a valid integer, try again")
            } else {
                break
            }
        }
        vars[name] = value
        i++
    }
    fmt.Println("\nEnter q to quit")
    for {
        fmt.Print("\nWhich variable do you want to inspect : ")
        scanner.Scan()
        name := scanner.Text()
        check(scanner.Err())
        if s := strings.ToLower(name); s == "q" {
            return
        }
        v, ok := vars[name]
        if !ok {
            fmt.Println("Sorry there's no variable of that name, try again")
        } else {
            fmt.Println("It's value is", v)
        }
    }
}


def varname = 'foo'
def value = 42

new GroovyShell(this.binding).evaluate("${varname} = ${value}")

assert foo == 42


def isEmirp( v:Long ) : Boolean = {
 val b = BigInt(v.toLong)
 val r = BigInt(v.toString.reverse.toLong)
 b != r && b.isProbablePrime(16) && r.isProbablePrime(16)
}

// Generate the output
{
  val (a,b1,b2,c) = (20,7700,8000,10000)
  println( "%32s".format(          "First %d emirps: ".format( a )) + Stream.from(2).filter( isEmirp(_) ).take(a).toList.mkString(",") )
  println( "%32s".format( "Emirps between %d and %d: ".format( b1, b2 )) + {for( i <- b1 to b2 if( isEmirp(i) ) ) yield i}.mkString(",") )
  println( "%32s".format(                "%,d emirp: ".format( c )) + Iterator.from(2).filter( isEmirp(_) ).drop(c-1).next )
}


; Primality test by simple trial division.
(define prime?
  (lambda (num)
    (if (< num 2)
      #f
      (let loop ((div 2))
        (cond ((> (* div div) num) #t)
              ((zero? (modulo num div)) #f)
              (else (loop (1+ div))))))))

; Check if number is an emirp prime.
(define emirp?
  (lambda (num)
    (and (prime? num)
         (let ((rev (string->number (list->string (reverse (string->list (number->string num)))))))
           (and (not (= num rev)) (prime? rev))))))

(printf "The first 20 emirps:")
(do ((num 1 (1+ num)) (cnt 0))
    ((>= cnt 20))
  (when (emirp? num)
    (set! cnt (1+ cnt))
    (printf " ~d" num)))
(newline)

(printf "All emirps between 7700 and 8000:")
(do ((num 7700 (1+ num)))
    ((>= num 8000))
  (when (emirp? num)
    (printf " ~d" num)))
(newline)

(printf "The 10000th emirp: ~d~%"
        (do ((num 1 (1+ num)) (cnt 0))
            ((>= cnt 10000) (1- num))
          (when (emirp? num) (set! cnt (1+ cnt)))))


#lang racket
(define listener (tcp-listen 12321))
(let echo-server ()
  (define-values [I O] (tcp-accept listener))
  (thread (λ() (copy-port I O) (close-output-port O)))
  (echo-server))


my $socket = IO::Socket::INET.new:
    :localhost<localhost>,
    :localport<12321>,
    :listen;

while $socket.accept -> $conn {
    say "Accepted connection";
    start {
        while $conn.recv -> $stuff {
            say "Echoing $stuff";
            $conn.print($stuff);
        }
        $conn.close;
    }
}


Class EchoSocket
Inherits TCPSocket
  Sub DataAvailable()
    If Instr(Me.LookAhead, EndofLine.Windows) > 0 Then
      Dim data As String = Me.ReadAll
      Dim lines() As String = Split(data, EndofLine.Windows)
      For i As Integer = 0 To Ubound(lines)
        Me.Write(lines(i) + EndOfLine.Windows)
        Print(lines(i))
      Next
    End If
  End Sub
End Class

Class EchoServer
Inherits ServerSocket
  Function AddSocket() As TCPSocket
    Return New EchoSocket
  End Function
End Class

Class App
Inherits ConsoleApplication
  Function Run(args() As String) As Integer
    Listener = New EchoServer
    Listener.Port = 12321
    Listener.Listen()
    While True
      DoEvents() 'pump the event loop
    Wend
  End Function
  Private Listener As EchoServer
End Class


data Var a = Var String a deriving Show
main = do
    putStrLn "please enter you variable name"
    vName <- getLine
    let var = Var vName 42
    putStrLn $ "this is your variable: " ++ show var


require 'misc'
(prompt 'Enter variable name: ')=: 0


public static void main(String... args){
        HashMap<String, Integer> vars = new HashMap<String, Integer>();
        //The variable name is stored as the String. The var type of the variable can be
        //changed by changing the second data type mentiones. However, it must be an object
        //or a wrapper class.
        vars.put("Variable name", 3); //declaration of variables
        vars.put("Next variable name", 5);
        Scanner sc = new Scanner(System.in);
        String str = sc.next();
        vars.put(str, sc.nextInt()); //accpeting name and value from user

        System.out.println(vars.get("Variable name")); //printing of values
        System.out.println(vars.get(str));
}


var varname = 'foo';  // pretend a user input that
var value = 42;
eval('var ' + varname + '=' + value);


"Enter a variable name:",
(input as $var
 | ("Enter a value:" ,
    (input as $value | { ($var) : $value })))


func forprimes(a, b, callback) {
    for (var p = a.dec.next_prime; p <= b; p.next_prime!) {
        callback(p)
    }
}

func is_emirp(p) {
    var str = Str(p)
    var rev = str.reverse
    (str != rev) && is_prime(Num(rev))
}

func emirp_list(count) {
    var i = 13
    var inc = (100 + 10*count)
    var n = []
    while (n.len < count) {
        forprimes(i, i+inc - 1, {|p|
            is_emirp(p) && (n << p)
        })
        (i, inc) = (i+inc, int(inc * 1.03) + 1000)
    }
    n.splice(count)
    return n
}

say ("First 20: ", emirp_list(20).join(' '))
say ("Between 7700 and 8000: ", gather {
        forprimes(7700, 8000, {|p| is_emirp(p) && take(p) })
    }.join(' '))
say ("The 10,000'th emirp: ", emirp_list(10000)[-1])


isEmirp :=
    [:p | |e|
        (e := p asString reversed asNumber) isPrime
        and:[ e ~= p ]
    ].


server-port: open/lines tcp://:12321
forever [
    connection-port: first server-port
    until [
        wait connection-port
        error? try [insert connection-port first connection-port]
    ]
    close connection-port
]
close server-port


require 'socket'
server = TCPServer.new(12321)

while (connection = server.accept)
  Thread.new(connection) do |conn|
    port, host = conn.peeraddr[1,2]
    client = "#{host}:#{port}"
    puts "#{client} is connected"
    begin
      loop do
        line = conn.readline
        puts "#{client} says: #{line}"
        conn.puts(line)
      end
    rescue EOFError
      conn.close
      puts "#{client} has disconnected"
    end
  end
end


use std::net::{TcpListener, TcpStream};
use std::io::{BufReader, BufRead, Write};
use std::thread;

fn main() {
    let listener = TcpListener::bind("127.0.0.1:12321").unwrap();
    println!("server is running on 127.0.0.1:12321 ...");

    for stream in listener.incoming() {
        let stream = stream.unwrap();
        thread::spawn(move || handle_client(stream));
    }
}

fn handle_client(stream: TcpStream) {
    let mut stream = BufReader::new(stream);
    loop {
        let mut buf = String::new();
        if stream.read_line(&mut buf).is_err() {
            break;
        }
        stream
            .get_ref()
            .write(buf.as_bytes())
            .unwrap();
    }
}


import java.io.PrintWriter
import java.net.{ServerSocket, Socket}

import scala.io.Source

object EchoServer extends App {
  private val serverSocket = new ServerSocket(23)
  private var numConnections = 0

  class ClientHandler(clientSocket: Socket) extends Runnable {
    private val (connectionId, closeCmd) = ({numConnections += 1; numConnections}, ":exit")

    override def run(): Unit =
      new PrintWriter(clientSocket.getOutputStream, true) {
        println(s"Connection opened, close with entering '$closeCmd'.")
        Source.fromInputStream(clientSocket.getInputStream).getLines
          .takeWhile(!_.toLowerCase.startsWith(closeCmd))
          .foreach { line =>
            Console.println(s"Received on #$connectionId: $line")
            println(line)  // Echo
          }
        Console.println(s"Gracefully closing connection, #$connectionId")
        clientSocket.close()
    }

    println(s"Handling connection, $connectionId")
  }

  while (true) new Thread(new ClientHandler(serverSocket.accept())).start()
}


print("Insert the variable name: ")

variable   = Symbol(readline(STDIN))
expression = quote
    $variable = 42
    println("Inside quote:")
    @show $variable
end

eval(expression)

println("Outside quote:")
@show variable
println("If I named the variable x:")
@show x


// version 1.1.4

fun main(args: Array<String>) {
    var n: Int
    do {
        print("How many integer variables do you want to create (max 5) : ")
        n = readLine()!!.toInt()
    }
    while (n < 1 || n > 5)

    val map = mutableMapOf<String, Int>()
    var name: String
    var value: Int
    var i = 1
    println("OK, enter the variable names and their values, below")
    do {
        println("\n  Variable $i")
        print("    Name  : ")
        name = readLine()!!
        if (map.containsKey(name)) {
            println("  Sorry, you've already created a variable of that name, try again")
            continue
        }
        print("    Value : ")
        value = readLine()!!.toInt()
        map.put(name, value)
        i++
    }
    while (i <= n)

    println("\nEnter q to quit")
    var v: Int?
    while (true) {
        print("\nWhich variable do you want to inspect : ")
        name = readLine()!!
        if (name.toLowerCase() == "q") return
        v = map[name]
        if (v == null) println("Sorry there's no variable of that name, try again")
        else println("It's value is $v")
    }
}


local(thename = web_request->param('thename')->asString)
if(#thename->size) => {^
	var(#thename = math_random)
	var(#thename)
else
	'Please give the variable a name!'
^}


-- varName might contain a string that was entered by a user at runtime

-- A new global variable with a user-defined name can be created at runtime like this:
(the globals)[varName] = 23 -- or (the globals).setProp(varName, 23)

-- An new instance variable (object property) with a user-defined name can be created at runtime like this:
obj[varName] = 23 -- or obj.setProp(varName, 23)


? make readword readword
julie
12
? show :julie
12


import Foundation

extension BinaryInteger {
  var isPrime: Bool {
    if self == 0 || self == 1 {
      return false
    } else if self == 2 {
      return true
    }

    let max = Self(ceil((Double(self).squareRoot())))

    for i in stride(from: 2, through: max, by: 1) where self % i == 0  {
      return false
    }

    return true
  }
}

func isEmirp<T: BinaryInteger>(n: T) -> Bool {
  guard n.isPrime else {
    return false
  }

  var aux = n
  var revPrime = T(0)

  while aux > 0 {
    revPrime = revPrime * 10 + aux % 10
    aux /= 10
  }

  guard n != revPrime else {
    return false
  }

  return revPrime.isPrime
}

let lots = (2...).lazy.filter(isEmirp).prefix(10000)
let rang = (7700...8000).filter(isEmirp)

print("First 20 emirps: \(Array(lots.prefix(20)))")
print("Emirps between 7700 and 8000: \(rang)")
print("10,000th emirp: \(Array(lots).last!)")


package require math::numtheory

# Import only to keep line lengths down
namespace import math::numtheory::isprime
proc emirp? {n} {
    set r [string reverse $n]
    expr {$n != $r && [isprime $n] && [isprime $r]}
}

# Generate the various emirps
for {set n 2;set emirps {}} {[llength $emirps] < 20} {incr n} {
    if {[emirp? $n]} {lappend emirps $n}
}
puts "first20: $emirps"

for {set n 7700;set emirps {}} {$n <= 8000} {incr n} {
    if {[emirp? $n]} {lappend emirps $n}
}
puts "7700-8000: $emirps"

for {set n 2;set ne 0} true {incr n} {
    if {[emirp? $n] && [incr ne] == 10000} break
}
puts "10,000: $n"


; Needed in Guile for read-line
(use-modules (ice-9 rdelim))

; Variable used to hold child PID returned from forking
(define child #f)

; Start listening on port 12321 for connections from any address
(let ((s (socket PF_INET SOCK_STREAM 0)))
  (setsockopt s SOL_SOCKET SO_REUSEADDR 1)
  (bind s AF_INET INADDR_ANY 12321)
  (listen s 5) ; Queue size of 5

  (simple-format #t "Listening for clients in pid: ~S" (getpid))
  (newline)

; Wait for connections forever
  (while #t
    (let* ((client-connection (accept s))
        (client-details (cdr client-connection))
        (client (car client-connection)))
; Once something connects fork
      (set! child (primitive-fork))
      (if (zero? child)
      (begin
; Then have child fork to avoid zombie children (grandchildren aren't our responsibility)
        (set! child (primitive-fork))
        (if (zero? child)
          (begin
; Display some connection details
          (simple-format #t "Got new client connection: ~S" client-details)
          (newline)
          (simple-format #t "Client address: ~S"
            (gethostbyaddr (sockaddr:addr client-details)))
          (newline)
; Wait for input from client and then echo the input back forever (or until client quits)
          (do ((line (read-line client)(read-line client))) ((zero? 1))
            (display line client)(newline client))))
; Child exits after spawning grandchild.
        (primitive-exit))
; Parent waits for child to finish spawning grandchild
      (waitpid child)))))


$ include "seed7_05.s7i";
  include "socket.s7i";
  include "listener.s7i";

const proc: main is func
  local
    var listener: aListener is listener.value;
    var file: existingConnection is STD_NULL;
    var file: newConnection is STD_NULL;
  begin
    aListener := openInetListener(12321);
    listen(aListener, 10);
    while TRUE do
      waitForRequest(aListener, existingConnection, newConnection);
      if existingConnection <> STD_NULL then
        if eof(existingConnection) then
          writeln("Close connection " <& numericAddress(address(existingConnection)) <&
                  " port " <& port(existingConnection));
          close(existingConnection);
        else
          write(existingConnection, gets(existingConnection, 1024));
        end if;
      end if;
      if newConnection <> STD_NULL then
        writeln("New connection " <& numericAddress(address(newConnection)) <&
                " port " <& port(newConnection));
      end if;
    end while;
  end func;


# How to handle an incoming new connection
proc acceptEcho {chan host port} {
    puts "opened connection from $host:$port"
    fconfigure $chan -blocking 0 -buffering line -translation crlf
    fileevent $chan readable [list echo $chan $host $port]
}

# How to handle an incoming message on a connection
proc echo {chan host port} {
    if {[gets $chan line] >= 0} {
        puts $chan $line
    } elseif {[eof $chan]} {
        close $chan
        puts "closed connection from $host:$port"
    }
    # Other conditions causing a short read need no action
}

# Make the server socket and wait for connections
socket -server acceptEcho -myaddr localhost 12321
vwait forever


| ?- create_object(Id, [], [set_logtalk_flag(dynamic_declarations,allow)], []),
     write('Variable name:  '), read(Name),
     write('Variable value: '), read(Value),
     Fact =.. [Name, Value],
     Id::assertz(Fact).

Variable name:  foo.
Variable value: 42.
Id = o1,
Name = foo,
Value =  42,
Fact = foo(42).

?- o1::current_predicate(foo/1).
true.

| ?- o1::foo(X).
X = 42.


_G[io.read()] = 5 --puts 5 in a global variable named by the user


Module DynamicVariable {
      input "Variable Name:", a$
      a$=filter$(a$," ,+-*/^~'\({=<>})|!$&"+chr$(9)+chr$(127))
      While a$ ~ "..*"  {a$=mid$(a$, 2)}
      If len(a$)=0 then Error "No name found"
      If chrcode(a$)<65 then Error "Not a Valid name"
      Inline a$+"=1000"
      Print eval(a$)=1000
      \\ use of a$ as pointer to variable
      a$.+=100
      Print eval(a$)=1100
      \\ list of variables
      List
}
Keyboard "George"+chr$(13)
DynamicVariable


Enter foo, please.
define(`inp',esyscmd(`echoinp'))
define(`trim',substr(inp,0,decr(len(inp))))
define(trim,42)
foo


varname = InputString["Enter a variable name"];
varvalue = InputString["Enter a value"];
ReleaseHold[ Hold[Set["nameholder", "value"]] /. {"nameholder" -> Symbol[varname], "value" -> varvalue}];
Print[varname, " is now set to ", Symbol[varname]]


/* Use :: for indirect assignment */
block([name: read("name?"), x: read("value?")], name :: x);


Option Explicit

Private Const MAX As Long = 5000000
Private Emirps As New Collection
Private CollTemp As New Collection

Sub Main()
Dim t
t = Timer
    FillCollectionOfEmirps
    Debug.Print "At this point : Execution time = " & Timer - t & " seconds."
    Debug.Print "We have a Collection of the " & Emirps.Count & " first Emirps."
    Debug.Print "---------------------------"
    'show the first   twenty   emirps
    Debug.Print "the first 20 emirps: "; ExtractEmirps(1, 20)
    'show all emirps between 7,700 and 8,000
    Debug.Print "all emirps between 7,700 and 8,000: "; ExtractEmirps(7700, 8000, True)
    'show the   10,000th   emirp
    Debug.Print "the 10,000th emirp: "; ExtractEmirps(10000, 10000)
  End Sub

Private Function ExtractEmirps(First As Long, Last As Long, Optional Value = False) As String
Dim temp$, i As Long, e
    If First = Last Then
        ExtractEmirps = Emirps(First)
    Else
        If Not Value Then
            For i = First To Last
                temp = temp & ", " & Emirps(i)
            Next
        Else
            For Each e In Emirps
                If e > First And e < Last Then
                    temp = temp & ", " & e
                End If
                If e = Last Then Exit For
            Next e
        End If
        ExtractEmirps = Mid(temp, 3)
    End If
End Function

Private Sub FillCollectionOfEmirps()
Dim Primes() As Long, e, i As Long
    Primes = Atkin
    For i = LBound(Primes) To UBound(Primes)
        CollTemp.Add Primes(i), CStr(Primes(i))
    Next i
    For Each e In CollTemp
        If IsEmirp(e) Then Emirps.Add e
    Next
End Sub

Private Function Atkin() As Long()
Dim MyBool() As Boolean
Dim SQRT_MAX As Long, i&, j&, N&, cpt&, MAX_TEMP As Long, temp() As Long
    ReDim MyBool(MAX)
    SQRT_MAX = Sqr(MAX) + 1
    MAX_TEMP = Sqr(MAX / 4) + 1
    For i = 1 To MAX_TEMP
        For j = 1 To SQRT_MAX
            N = 4 * i * i + j * j
            If N <= MAX And (N Mod 12 = 1 Or N Mod 12 = 5) Then
                MyBool(N) = True
            End If
        Next j
    Next i
    MAX_TEMP = Sqr(MAX / 3) + 1
    For i = 1 To MAX_TEMP
        For j = 1 To SQRT_MAX
            N = 3 * i * i + j * j
            If N <= MAX And N Mod 12 = 7 Then
                MyBool(N) = True
            End If
        Next j
    Next i
    For i = 1 To SQRT_MAX
        For j = 1 To SQRT_MAX
            N = 3 * i * i - j * j
            If i > j And N <= MAX And N Mod 12 = 11 Then
                MyBool(N) = True
            End If
        Next j
    Next i
    For i = 5 To SQRT_MAX Step 2
        If MyBool(i) Then
            For j = i * i To MAX Step i
                MyBool(j) = False
            Next
        End If
    Next
    ReDim temp(MAX / 2)
    temp(0) = 2: temp(1) = 3: cpt = 2
    For i = 5 To MAX Step 2
        If MyBool(i) Then temp(cpt) = i: cpt = cpt + 1
    Next
    ReDim Preserve temp(cpt - 1)
    Atkin = temp
End Function

Private Function IsEmirp(N) As Boolean
Dim a As String, b As String
    a = StrReverse(CStr(N)): b = CStr(N)
    If a <> b Then
        On Error Resume Next
        CollTemp.Add a, a
        If Err.Number > 0 Then
            IsEmirp = True
        Else
            CollTemp.Remove a
        End If
        On Error GoTo 0
    End If
End Function


; x86_64 Linux NASM

global _start

%define af_inet 2
%define sock_stream 1
%define default_proto 0
%define sol_sock 1
%define reuse_addr 2
%define reuse_port 15
%define server_port 9001
%define addr_any 0
%define family_offset 0
%define port_offset 2
%define addr_offset 4
%define unused_offset 8
%define addr_len 16
%define buffer_len 64
%define max_connections 3

section .text

; rdi - 16 bit value to be byte swapped
; return - byte swapped value
htn_swap16:

  xor rax, rax
  mov rdx, 0x000000ff

  mov rsi, rdi
  and rsi, rdx
  shl rsi, 8
  or rax, rsi
  shl rdx, 8

  mov rsi, rdi
  and rsi, rdx
  shr rsi, 8
  or rax, rsi
  ret

; return - server socket
create_server_socket:

  mov rax, 41
  mov rdi, af_inet
  mov rsi, sock_stream
  mov rdx, default_proto
  syscall
  push rax

  mov rax, 54
  mov rdi, qword [rsp]
  mov rsi, sol_sock
  mov rdx, reuse_addr
  mov qword [rsp - 16], 1
  lea r10, [rsp - 16]
  mov r8, 4
  syscall

  mov rax, 54
  mov rdi, qword [rsp]
  mov rsi, sol_sock
  mov rdx, reuse_port
  mov qword [rsp - 16], 1
  lea r10, [rsp - 16]
  mov r8, 4
  syscall

  pop rax
  ret

; rdi - socket
; rsi - port
; rdx - connections
; return - void
bind_and_listen:

  push rdi
  push rdx

  mov rdi, rsi
  call htn_swap16

  lea rsi, [rsp - 16]
  mov word [rsi + family_offset], af_inet
  mov word [rsi + port_offset], ax
  mov dword [rsi + addr_offset], addr_any
  mov qword [rsi + unused_offset], 0

  mov rax, 49
  mov rdi, qword [rsp + 8]
  mov rdx, addr_len
  syscall

  mov rax, 50
  pop rsi
  pop rdi
  syscall
  ret

; rdi - server socket
; return - client socket
accept:

  mov rax, 43
  lea rsi, [rsp - 16]
  lea rdx, [rsp - 24]
  syscall
  ret

; rdi - client socket
; return - void
echo:

  push rdi
  mov rax, 0
  lea rsi, [rsp - 104]
  mov rdx, buffer_len
  syscall

  pop rdi
  mov rdx, rax
  lea rsi, [rsp - 112]
  mov rax, 1
  syscall
  ret

_start:

  call create_server_socket
  mov r14, rax

  mov rdi, rax
  mov rsi, server_port
  mov rdx, max_connections
  call bind_and_listen

accept_connection:

  mov rdi, r14
  call accept

  mov r15, rax
  mov rax, 57
  syscall

  test rax, rax
  jz handle_connection

  ; close client socket
  mov rax, 3
  mov rdi, r15
  syscall
  jmp accept_connection

handle_connection:

  mov rdi, r15
  call echo

  close_client:
    mov rax, 3
    mov rdi, r15
    syscall

  close_server:
    mov rax, 3
    mov rdi, r14
    syscall

  exit:
    mov rax, 60
    xor rdi, rdi
    syscall


/* echo_server.wren */

var MAX_ENQUEUED = 20
var BUF_LEN = 256
var PORT_STR = "12321"

var AF_UNSPEC = 0
var SOCK_STREAM = 1
var AI_PASSIVE = 1

foreign class AddrInfo {
    foreign static getAddrInfo(name, service, req, pai)

    construct new() {}

    foreign family

    foreign family=(f)

    foreign sockType

    foreign sockType=(st)

    foreign flags

    foreign flags=(f)

    foreign protocol

    foreign addr

    foreign addrLen
}

foreign class AddrInfoPtr {
    construct new() {}

    foreign deref

    foreign free()
}

class Socket {
    foreign static create(domain, type, protocol)

    foreign static bind(fd, addr, len)

    foreign static listen(fd, n)

    foreign static accept(fd, addr, addrLen)
}

foreign class SockAddrPtr {
    construct new() {}

    foreign size
}

class SigAction {
    foreign static cleanUpProcesses()
}

foreign class Buffer {
    construct new(size) {}
}

class Posix {
    foreign static read(fd, buf, nbytes)

    foreign static write(fd, buf, n)

    foreign static fork()

    foreign static close(fd)
}

// Child process.
var echoLines = Fn.new { |csock|
    var buf = Buffer.new(BUF_LEN)
    var r
    while ((r = Posix.read(csock, buf, BUF_LEN)) > 0) {
        Posix.write(csock, buf, r)
    }
}

// Parent process.
var takeConnectionsForever = Fn.new { |ssock|
    while (true) {
        var addr = SockAddrPtr.new()
        var addrSize = addr.size

        /* Block until we take one connection to the server socket */
        var csock = Socket.accept(ssock, addr, addrSize)

        /* If it was a successful connection, spawn a worker process to service it. */
        if (csock == -1) {
            System.print("Error accepting socket.")
        } else if (Posix.fork() == 0) {
            Posix.close(ssock)
            echoLines.call(csock)
            return
        } else {
            Posix.close(csock)
        }
    }
}

/* Look up the address to bind to. */
var hints = AddrInfo.new()
hints.family = AF_UNSPEC
hints.sockType = SOCK_STREAM
hints.flags = AI_PASSIVE
var addrInfoPtr = AddrInfoPtr.new()
if (AddrInfo.getAddrInfo("", PORT_STR, hints, addrInfoPtr) != 0) {
    Fiber.abort("Failed to get pointer to addressinfo.")
}

/* Make a socket. */
var res = addrInfoPtr.deref
var sock = Socket.create(res.family, res.sockType, res.protocol)
if (sock == -1) Fiber.abort("Failed to make a socket.")

/* Arrange to clean up child processes (the workers). */
SigAction.cleanUpProcesses()

/* Associate the socket with its address. */
if (Socket.bind(sock, res.addr, res.addrLen) != 0) {
    Fiber.abort("Failed to bind socket.")
}

addrInfoPtr.free()

/* State that we've opened a server socket and are listening for connections. */
if (Socket.listen(sock, MAX_ENQUEUED) != 0) {
    Fiber.abort("Failed to listen for connections.")
}

/* Serve the listening socket until killed */
takeConnectionsForever.call(sock)


USER>KILL ;Clean up workspace

USER>WRITE ;show all variables and definitions

USER>READ "Enter a variable name: ",A
Enter a variable name: GIBBERISH
USER>SET @A=3.14159

USER>WRITE

A="GIBBERISH"
GIBBERISH=3.14159


print "Enter a variable name: "
name = input()

print name + " = "
exec(name + " = 42")
exec("println " + name)


import tables

var
  theVar: int = 5
  varMap = initTable[string, pointer]()

proc ptrToInt(p: pointer): int =
  result = cast[ptr int](p)[]

proc main() =
  write(stdout, "Enter a var name: ")
  let sVar = readLine(stdin)
  varMap[$svar] = theVar.addr
  echo "Variable ", sVar, " is ", ptrToInt(varMap[$sVar])

when isMainModule:
  main()


varname = input ("Enter variable name: ", "s");
value = input ("Enter value: ", "s");
eval([varname,"=",value]);


: createVar(varname)
   "tvar: " varname + eval ;

"myvar" createVar

12 myvar put
myvar at .


PROGRAM ExDynVar;

{$IFDEF FPC}
    {$mode objfpc}{$H+}{$J-}{R+}
{$ELSE}
    {$APPTYPE CONSOLE}
{$ENDIF}

(*)
    Free Pascal Compiler version 3.2.0 [2020/06/14] for x86_64
    The free and readable alternative at C/C++ speeds
    compiles natively to almost any platform, including raspberry PI

    This demo uses a dictionary because it is compiled: it cannot  make
    dynamic variables at runtime.
(*)

USES
    Generics.Collections,
    SysUtils,
    Variants;

TYPE

    Tdict =
    {$IFDEF FPC}
    specialize
    {$ENDIF}
     TDictionary < ansistring, variant > ;

VAR
    VarName:  ansistring;
    strValue: ansistring;
    VarValue:    variant;
    D:             Tdict;

    FUNCTION SetType ( strVal: ansistring ) : variant ;

    (*)
       If the value is numeric, store it as numeric, otherwise store it as ansistring
    (*)

        BEGIN

            TRY
                SetType := StrToFloat ( strVal ) ;
            EXCEPT
                SetType :=                strVal ;
            END;

        END;

BEGIN

    D := TDict.Create;
    REPEAT
        Write  ( 'Enter variable name : '  ) ;
        ReadLn ( VarName  ) ;
        Write  ( 'Enter variable Value : ' ) ;
        ReadLn ( strValue ) ;
        VarValue :=     SetType ( strValue ) ;
        TRY
            BEGIN
                D.AddOrSetValue ( VarName, VarValue ) ;
                Write                     ( VarName ) ;
                Write                     (  ' = '  ) ;
                WriteLn             ( D [ VarName ] ) ;
            END;
        EXCEPT
            WriteLn ( 'Something went wrong.. Try again' ) ;
        END;
    UNTIL ( strValue = '' ) ;
    D.Free;

END.


Imports System.Runtime.CompilerServices

Module Module1
    <Extension()>
    Function ToHashSet(Of T)(source As IEnumerable(Of T)) As HashSet(Of T)
        Return New HashSet(Of T)(source)
    End Function

    <Extension()>
    Function Reverse(number As Integer) As Integer
        If number < 0 Then
            Return -Reverse(-number)
        End If
        If number < 10 Then
            Return number
        End If

        Dim rev = 0
        While number > 0
            rev = rev * 10 + number Mod 10
            number = number \ 10
        End While

        Return rev
    End Function

    <Extension()>
    Function Delimit(Of T)(source As IEnumerable(Of T), Optional seperator As String = " ") As String
        Return String.Join(If(seperator, " "), source)
    End Function

    Iterator Function Primes(bound As Integer) As IEnumerable(Of Integer)
        If bound < 2 Then
            Return
        End If
        Yield 2

        Dim composite As New BitArray((bound - 1) / 2)
        Dim limit As Integer = Int((Int(Math.Sqrt(bound)) - 1) / 2)
        For i = 0 To limit - 1
            If composite(i) Then
                Continue For
            End If
            Dim prime = 2 * i + 3
            Yield prime

            For j As Integer = Int((prime * prime - 2) / 2) To composite.Count - 1 Step prime
                composite(j) = True
            Next
        Next
        For i = limit To composite.Count - 1
            If Not composite(i) Then
                Yield 2 * i + 3
            End If
        Next
    End Function

    Iterator Function FindEmirpPrimes(limit As Integer) As IEnumerable(Of Integer)
        Dim ps = Primes(limit).ToHashSet()

        For Each p In ps
            Dim rev = p.Reverse()
            If rev <> p AndAlso ps.Contains(rev) Then
                Yield p
            End If
        Next
    End Function

    Sub Main()
        Dim limit = 1_000_000
        Console.WriteLine("First 20:")
        Console.WriteLine(FindEmirpPrimes(limit).Take(20).Delimit())
        Console.WriteLine()

        Console.WriteLine("Between 7700 and 8000:")
        Console.WriteLine(FindEmirpPrimes(limit).SkipWhile(Function(p) p < 7700).TakeWhile(Function(p) p < 8000).Delimit())
        Console.WriteLine()

        Console.WriteLine("10000th:")
        Console.WriteLine(FindEmirpPrimes(limit).ElementAt(9999))
    End Sub

End Module


const PORT=12321;
pipe:=Thread.Pipe(); // how server tells thread to connect to user

fcn echo(socket){		// a thread, one per connection
   text:=Data();
   while(t:=socket.read()){
      text.append(t);
      if(text.find("\n",text.cursor)){ text.readln().print(); }
   }
   // socket was closed
}

   // Set up the server socket.
server:=Network.TCPServerSocket.open(PORT);
println("Listening on %s:%s".fmt(server.hostname,server.port));
server.listen(echo.launch);  // Main event loop


print "Enter a variable name: ";
$varname = <STDIN>; # type in "foo" on standard input
chomp($varname);
$$varname = 42; # when you try to dereference a string, it will be
                # treated as a "symbolic reference", where they
                # take the string as the name of the variable
print "$foo\n"; # prints "42"


constant globals = new_dict()

while 1 do
    string name = prompt_string("Enter name or press Enter to quit:")
    if length(name)=0 then exit end if
    bool bExists = (getd_index(name,globals)!=NULL)
    string prompt = iff(not bExists?"No such name, enter a value:"
                   :sprintf("Already exists, new value[%s]:",{getd(name,globals)}))
    string data = prompt_string(prompt)
    if length(data) then
        setd(name,data,globals)
    end if
end while


<?php
$varname = rtrim(fgets(STDIN)); # type in "foo" on standard input
$$varname = 42;
echo "$foo\n"; # prints "42"
?>


(de userVariable ()
   (prin "Enter a variable name: ")
   (let Var (line T)                                  # Read transient symbol
      (prin "Enter a value: ")
      (set Var (read))                                # Set symbol's value
      (println 'Variable Var 'Value (val Var)) ) )    # Print them


$variableName = Read-Host
New-Variable $variableName 'Foo'
Get-Variable $variableName


editvar /newvar /value=a /userinput=1 /title=Enter a variable name:
editvar /newvar /value=b /userinput=1 /title=Enter a variable title:
editvar /newvar /value=-a- /title=-b-


test :- read(Name), atomics_to_string([Name, "= 50, writeln('", Name, "' = " , Name, ")"], String), term_string(Term, String), Term.


import "/math" for Int

var isEmirp = Fn.new{ |n|
    if (!Int.isPrime(n)) return false
    var ns = "%(n)"
    var rs = ns[-1..0]
    var r = Num.fromString(rs)
    if (r == n) return false
    if (Int.isPrime(r)) return true
    return false
}

System.print("The first 20 emirps are:")
var count = 0
var i = 3
while (count < 20) {
    if (isEmirp.call(i)) {
        count = count + 1
        System.write("%(i) ")
    }
    i = i + 2
}

System.print("\n\nThe emirps between 7700 and 8000 are:")
i = 7701
while (i < 8000) {
    if (isEmirp.call(i)) System.write("%(i) ")
    i = i + 2
}

System.write("\n\nThe 10,000th emirp is ")
count = 0
i = 1
while (count < 10000) {
    i = i + 2
    if (isEmirp.call(i)) {
        count = count + 1
    }
}
System.print(i)


var PS=Import("Src/ZenKinetic/sieve").postponed_sieve;
var ps=Utils.Generator(PS), plist=ps.walk(10).copy();

fcn isEmirp(p){ rp:=p.toString().reverse().toInt();
   if(p==rp) return(False);
   if(plist.holds(rp)) return(True);
   tp:=p; mp:=p.max(rp); while(tp<mp) { plist.append(tp=ps.next()) }
   return(tp==rp);
}

Utils.Generator(PS).filter(20,isEmirp);

Utils.Generator(PS).filter(fcn(p){if(p>8000)return(Void.Stop); p>7700 and isEmirp(p)});

Utils.Generator(PS).reduce(fcn(N,p){N+=isEmirp(p); (N==10000) and T(Void.Stop,p) or N },0);


F iseban(n)
   I n == 0
      R 0B
   V (b, r) = divmod(n, 1'000'000'000)
   (V m, r) = divmod(r, 1'000'000)
   (V t, r) = divmod(r, 1'000)
   m = I m C 30..66 {m % 10} E m
   t = I t C 30..66 {t % 10} E t
   r = I r C 30..66 {r % 10} E r
   R Set([b, m, t, r]) <= Set([0, 2, 4, 6])

print(‘eban numbers up to and including 1000:’)
L(i) 0..100
   I iseban(i)
      print(i, end' ‘ ’)

print("\n\neban numbers between 1000 and 4000 (inclusive):")
L(i) 1000..4000
   I iseban(i)
      print(i, end' ‘ ’)

print()
L(maxn) (10'000, 100'000, 1'000'000, 10'000'000)
   V count = 0
   L(i) 0..maxn
      I iseban(i)
         count++
   print("\nNumber of eban numbers up to and including #8: #4".format(maxn, count))


>>> name = raw_input("Enter a variable name: ")
Enter a variable name: X
>>> globals()[name] = 42
>>> X
42


  [ say "The word "
    dup echo$
    names find names found iff
      [  say " exists." ]
    else
      [ say " does not exist." ] ]       is exists? ( $ --> )

  [ $ "Please enter a name: " input
    cr
    dup exists?
    cr cr
    dup say "Creating " echo$
    say "..."
    $ "[ stack ] is " over join quackery
    cr cr
    exists? cr ]                         is task    (   --> )


# Read the name in from a command prompt
varname <- readline("Please name your variable >")
# Make sure the name is valid for a variable
varname <- make.names(varname)
message(paste("The variable being assigned is '", varname, "'"))
# Assign the variable (with value 42) into the user workspace (global environment)
assign(varname, 42)
#Check that the value has been assigned ok
ls(pattern=varname)
get(varname)


-> (begin (printf "Enter some name: ")
          (namespace-set-variable-value! (read) 123))
Enter some name: bleh
-> bleh
123


our $our-var = 'The our var';
my  $my-var  = 'The my var';

my $name  = prompt 'Variable name: ';
my $value = $::('name'); # use the right sigil, etc

put qq/Var ($name) starts with value ｢$value｣/;

$::('name') = 137;

put qq/Var ($name) ends with value ｢{$::('name')}｣/;


rebol [
	Title: "Dynamic Variable Name"
	URL: http://rosettacode.org/wiki/Dynamic_variable_names
]

; Here, I ask the user for a name, then convert it to a word and
; assign the value "Hello!" to it. To read this phrase, realize that
; REBOL collects terms from right to left, so "Hello!" is stored for
; future use, then the prompt string "Variable name? " is used as the
; argument to ask (prompts user for input). The result of ask is
; converted to a word so it can be an identifier, then the 'set' word
; accepts the new word and the string ("Hello!") to be assigned.

set  to-word  ask "Variable name? "  "Hello!"


:newVariable ("-)  s:get var ;

newVariable: foo


(*
    Quickly generate all the (positive) eban numbers up to and including the
    specified end number, then lose those before the start number.
    0 is taken as "zero" rather than as "nought" or "nil".

    WARNING: The getEbans() handler returns a potentially very long list of numbers.
    Don't let such a list get assigned to a persistent variable or be the end result displayed in an editor!
*)

on getEbans(startNumber, endNumber)
    script o
        property output : {}
        property listCollector : missing value
        property temp : missing value
    end script

    if (startNumber > endNumber) then set {startNumber, endNumber} to {endNumber, startNumber}
    -- The range is limited to between 0 and 10^15 to keep within AppleScript's current number precision.
    -- Even so, some of the numbers may not /look/ right when displayed in a editor.
    set limit to 10 ^ 15 - 1
    if (endNumber > limit) then set endNumber to limit
    if (startNumber > limit) then set startNumber to limit

    -- Initialise the output list with 0 and the sub-1000 ebans, stopping if the end number's reached.
    -- The 0's needed for rest of the process, but is removed at the end.
    repeat with tens in {0, 30, 40, 50, 60}
        repeat with units in {0, 2, 4, 6}
            set thisEban to tens + units
            if (thisEban ≤ endNumber) then set end of o's output to thisEban
        end repeat
    end repeat

    -- Repeatedly sweep the output list, adding new ebans formed from the addition of those found previously
    -- to a suitable power of 1000 times each one. Stop when the end number's reached or exceeded.
    -- The output list may become very long and appending items to it individually take forever, so results are
    -- collected in short, 1000-item lists, which are concatenated to the output at the end of each sweep.
    set sweepLength to (count o's output)
    set multiplier to 1000
    repeat while (thisEban < endNumber) -- Per sweep.
        set o's temp to {}
        set o's listCollector to {o's temp}
        repeat with i from 2 to sweepLength -- Per eban found already. (Not the 0.)
            set baseAmount to (item i of o's output) * multiplier
            repeat with j from 1 to sweepLength by 1000 -- Per 1000-item list.
                set z to j + 999
                if (z > sweepLength) then set z to sweepLength
                repeat with k from j to z -- Per new eban.
                    set thisEban to baseAmount + (item k of o's output)
                    if (thisEban ≤ endNumber) then set end of o's temp to thisEban
                    if (thisEban ≥ endNumber) then exit repeat
                end repeat
                if (thisEban ≥ endNumber) then exit repeat
                set o's temp to {}
                set end of o's listCollector to o's temp
            end repeat
            if (thisEban ≥ endNumber) then exit repeat
        end repeat

        -- Concatentate this sweep's new lists together
        set listCount to (count o's listCollector)
        repeat until (listCount is 1)
            set o's temp to {}
            repeat with i from 2 to listCount by 2
                set end of o's temp to (item (i - 1) of o's listCollector) & (item i of o's listCollector)
            end repeat
            if (listCount mod 2 is 1) then set item -1 of o's temp to (end of o's temp) & (end of o's listCollector)
            set o's listCollector to o's temp
            set o's temp to {}
            set listCount to (count o's listCollector)
        end repeat
        -- Concatenate the result to the output list and prepare to go round again.
        set o's output to o's output & (beginning of o's listCollector)
        set sweepLength to sweepLength * sweepLength
        set multiplier to multiplier * multiplier
    end repeat

    -- Lose the initial 0 and any ebans before the specified start number.
    set resultCount to (count o's output)
    if (resultCount is 1) then
        set o's output to {}
    else
        repeat with i from 2 to resultCount
            if (item i of o's output ≥ startNumber) then exit repeat
        end repeat
        set o's output to items i thru resultCount of o's output
    end if
    if (endNumber = limit) then set end of o's output to "(Limit of AppleScript's number precision.)"

    return o's output
end getEbans

-- Task code:
on runTask()
    set output to {}
    set astid to AppleScript's text item delimiters
    set AppleScript's text item delimiters to ", "

    set ebans to getEbans(0, 1000)
    set end of output to ((count ebans) as text) & " eban numbers between 0 and 1,000:" & (linefeed & "  " & ebans)
    set ebans to getEbans(1000, 4000)
    set end of output to ((count ebans) as text) & " between 1,000 and 4,000:" & (linefeed & "  " & ebans)
    set end of output to ((count getEbans(0, 10000)) as text) & " up to and including 10,000"
    set end of output to ((count getEbans(0, 100000)) as text) & " up to and including 100,000"
    set end of output to ((count getEbans(0, 1000000)) as text) & " up to and including 1,000,000"
    set end of output to ((count getEbans(0, 10000000)) as text) & " up to and including 10,000,000"
    set ebans to getEbans(6.606606602E+10, 1.0E+12)
    set end of output to ((count ebans) as text) & " between 66,066,066,020 and 1,000,000,000,000:" & (linefeed & "  " & ebans)

    set AppleScript's text item delimiters to linefeed
    set output to output as text
    set AppleScript's text item delimiters to astid

    return output
end runTask

runTask()


/*REXX program demonstrates the use of dynamic variable names & setting a val.*/
parse arg newVar newValue
say 'Arguments as they were entered via the command line: '   newVar    newValue
say
call value newVar, newValue
say 'The newly assigned value (as per the VALUE bif)------' newVar value(newVar)
                                       /*stick a fork in it,  we're all done. */


See "Enter the variable name: " give cName eval(cName+"=10")
See "The variable name = " + cName + " and the variable value = " + eval("return "+cName) + nl


>> s = "myusername"
myusername
>> $$.[s] = 10;
>> myusername
  10


p "Enter a variable name"
x = "@" + gets.chomp!
instance_variable_set x, 42
p "The value of #{x} is #{instance_variable_get x}"


=> (define (create-variable name initial-val)
     (eval `(define ,name ,initial-val) (interaction-environment)))

=> (create-variable (read) 50)
<hello

=> hello
50


var name = read("Enter a variable name: ", String);     # type in 'foo'

class DynamicVar(name, value) {
    method init {
        DynamicVar.def_method(name, ->(_) { value })
    }
}

var v = DynamicVar(name, 42);       # creates a dynamic variable
say v.foo;                          # retrieves the value


define: #name -> (query: 'Enter a variable name: ') intern. "X"
define: name -> 42.
X print.


| varName |
varName := FillInTheBlankMorph
	request: 'Enter a variable name'.
Compiler
	evaluate:('| ', varName, ' | ', varName, ' := 42.
	Transcript
		show: ''value of ', varName, ''';
		show: '' is '';
		show: ', varName).


*       # Get var name from user
        output = 'Enter variable name:'
        invar = trim(input)

*       # Get value from user, assign
        output = 'Enter value:'
        $invar = trim(input)

*       Display
        output = invar ' == ' $invar
end


display "Name?" _request(s)
scalar $s=10
display $s


puts "Enter a variable name:"
gets stdin varname
set $varname 42
puts "I have set variable $varname to [set $varname]"


Local varName,value
InputStr "Variable name", varName
Prompt value
value → #varName


$$ MODE TUSCRIPT
ASK "Enter variablename": name=""
ASK "Enter value": value=""
TRACE [email protected]
@name=$value
PRINT @name


read name
declare $name=42
echo "${name}=${!name}"


import "io" for Stdin, Stdout

var userVars = {}
System.print("Enter three variables:")
for (i in 0..2) {
    System.write("\n  name : ")
    Stdout.flush()
    var name = Stdin.readLine()
    System.write("  value: ")
    Stdout.flush()
    var value = Num.fromString(Stdin.readLine())
    userVars[name] = value
}

System.print("\nYour variables are:\n")
for (kv in userVars) {
    System.print("  %(kv.key) = %(kv.value)")
}


#include "stdio.h"
#include "stdbool.h"

#define ARRAY_LEN(a,T) (sizeof(a) / sizeof(T))

struct Interval {
    int start, end;
    bool print;
};

int main() {
    struct Interval intervals[] = {
        {2, 1000, true},
        {1000, 4000, true},
        {2, 10000, false},
        {2, 100000, false},
        {2, 1000000, false},
        {2, 10000000, false},
        {2, 100000000, false},
        {2, 1000000000, false},
    };
    int idx;

    for (idx = 0; idx < ARRAY_LEN(intervals, struct Interval); ++idx) {
        struct Interval intv = intervals[idx];
        int count = 0, i;

        if (intv.start == 2) {
            printf("eban numbers up to and including %d:\n", intv.end);
        } else {
            printf("eban numbers between %d and %d (inclusive:)", intv.start, intv.end);
        }

        for (i = intv.start; i <= intv.end; i += 2) {
            int b = i / 1000000000;
            int r = i % 1000000000;
            int m = r / 1000000;
            int t;

            r = i % 1000000;
            t = r / 1000;
            r %= 1000;
            if (m >= 30 && m <= 66) m %= 10;
            if (t >= 30 && t <= 66) t %= 10;
            if (r >= 30 && r <= 66) r %= 10;
            if (b == 0 || b == 2 || b == 4 || b == 6) {
                if (m == 0 || m == 2 || m == 4 || m == 6) {
                    if (t == 0 || t == 2 || t == 4 || t == 6) {
                        if (r == 0 || r == 2 || r == 4 || r == 6) {
                            if (intv.print) printf("%d ", i);
                            count++;
                        }
                    }
                }
            }
        }
        if (intv.print) {
            printf("\n");
        }
        printf("count = %d\n\n", count);
    }

    return 0;
}


org &8000
WaitChar equ &BB06  ;Amstrad CPC BIOS call, loops until user presses a key. That key's ASCII value is returned in A.
PrintChar equ &BB5A ;Amstrad CPC BIOS call, A is treated as an ASCII value and is printed to the screen.

getInput:
	call WaitChar
	;returns key press in A

	or a ;set flags according to accumulator
	jp m,getInput
	;most keyboards aren't capable of going over ascii 127
	;but just in case they can prevent it.
        ;IX/IY offsets are signed, thus a key press outside of 7-bit ASCII would index out of bounds

	push af
	call PrintChar          ;prints the user variable name to the screen.
	pop af

	call NewLine

	ld (LoadFromUserNamedVariable+2),a ;offset byte is at addr+2
	ld (StoreToUserNamedVariable+2),a

; This self-modifying code turns both instances of (IX+0) into (IX+varname)

	ld a,&42 		;set the value of the dynamically named variable
				; to &42

	ld ix,ExtraRam          ;storage location of dynamically named variables

StoreToUserNamedVariable:
	ld (IX+0),a		;store 42 at the named offset
	                        ;"+0" is overwritten with the dynamic user ram name

	xor a
	dec a
	;just to prove that the value is indeed stored where the code
	;   is intending to, set A to 255 so that the next section of
	;   code will show that the variable is indeed retrieved and
	;   is shown to the screen

LoadFromUserNamedVariable:
	ld a,(IX+0)	          ;retrieve the value at the stored offset. The "+0" was overwritten with the user-defined offset.

	call ShowHex              ;prints to the terminal the value stored at the dynamically named user variable

ReturnToBasic
	RET

ShowHex:	                   ;credit to Keith S. of Chibiakumas
	push af
		and %11110000
			rrca
			rrca
			rrca
			rrca
		call PrintHexChar
	pop af
	and %00001111
	;call PrintHexChar
	;execution flows into it naturally.
PrintHexChar:
	or a	;Clear Carry Flag
	daa
	add a,&F0
	adc a,&40
	jp PrintChar
	;ret

NewLine:
	push af
	ld a,13		;Carriage return
	call PrintChar
	ld a,10		;Line Feed
	call PrintChar
	pop af
	ret

        org &9000
ExtraRam:
       ds 256,0         ;256 bytes of ram, each initialized to zero


vname:="foo";  // or vname:=ask("var name = ");
klass:=Compiler.Compiler.compileText("var %s=123".fmt(vname))(); // compile & run the constructor
klass.vars.println();
klass.foo.println();
klass.setVar(vname).println();  // setVar(name,val) sets the var


using System;

namespace EbanNumbers {
    struct Interval {
        public int start, end;
        public bool print;

        public Interval(int start, int end, bool print) {
            this.start = start;
            this.end = end;
            this.print = print;
        }
    }

    class Program {
        static void Main() {
            Interval[] intervals = {
                new Interval(2, 1_000, true),
                new Interval(1_000, 4_000, true),
                new Interval(2, 10_000, false),
                new Interval(2, 100_000, false),
                new Interval(2, 1_000_000, false),
                new Interval(2, 10_000_000, false),
                new Interval(2, 100_000_000, false),
                new Interval(2, 1_000_000_000, false),
            };
            foreach (var intv in intervals) {
                if (intv.start == 2) {
                    Console.WriteLine("eban numbers up to and including {0}:", intv.end);
                } else {
                    Console.WriteLine("eban numbers between {0} and {1} (inclusive):", intv.start, intv.end);
                }

                int count = 0;
                for (int i = intv.start; i <= intv.end; i += 2) {
                    int b = i / 1_000_000_000;
                    int r = i % 1_000_000_000;
                    int m = r / 1_000_000;
                    r = i % 1_000_000;
                    int t = r / 1_000;
                    r %= 1_000;
                    if (m >= 30 && m <= 66) m %= 10;
                    if (t >= 30 && t <= 66) t %= 10;
                    if (r >= 30 && r <= 66) r %= 10;
                    if (b == 0 || b == 2 || b == 4 || b == 6) {
                        if (m == 0 || m == 2 || m == 4 || m == 6) {
                            if (t == 0 || t == 2 || t == 4 || t == 6) {
                                if (r == 0 || r == 2 || r == 4 || r == 6) {
                                    if (intv.print) Console.Write("{0} ", i);
                                    count++;
                                }
                            }
                        }
                    }
                }
                if (intv.print) {
                    Console.WriteLine();
                }
                Console.WriteLine("count = {0}\n", count);
            }
        }
    }
}


eban = cluster is numbers
    rep = null

    % Next valid E-ban number in the range [0..999]
    next = proc (n: int) returns (int) signals (no_more)
        if n>=66 then signal no_more end
        if n<0 then return(0) end

        % advance low digit (two four six)
        if     (n//10=0) then n := (n/10)*10 + 2
        elseif (n//10=2) then n := (n/10)*10 + 4
        elseif (n//10=4) then n := (n/10)*10 + 6
        elseif (n//10=6) then n := (n/10)*10 + 10
        end

        % this might put us into tEn, twEnty which are invalid
        if     (n//100/10 =  1) then n := n + 20   % ten + 20    = 30
        elseif (n//100/10 =  2) then n := n + 10   % twEnty + 10 = 30
        end
        return(n)
    end next

    % Yield all valid E_ban numbers
    % (sextillion and upwards aren't handled)
    numbers = iter () yields (int)
        parts: array[int] := array[int]$[0: 2]

        while true do
            num: int := 0
            for m: int in array[int]$indexes(parts) do
                num := num + parts[m] * 1000 ** m
            end
            yield(num)

            for m: int in array[int]$indexes(parts) do
                begin
                    parts[m] := next(parts[m])
                    break
                end except when no_more:
                    parts[m] := 0
                end
            end

            if array[int]$top(parts) = 0 then
                array[int]$addh(parts,2)
            end
       end
    end numbers
end eban

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

    count: int := 0
    upto_1k: int := 0
    between_1k_4k: int := 0

    disp_1k: bool := false
    disp_4k: bool := false

    nextmagn: int := 10000

    for i: int in eban$numbers() do
        while i>nextmagn do
            stream$putl(po, int$unparse(count)
                        || " eban numbers <= "
                        || int$unparse(nextmagn))
            nextmagn := nextmagn * 10
        end

        count := count + 1

        if i<1000 then upto_1k := upto_1k + 1
        elseif i<=4000 then between_1k_4k := between_1k_4k + 1
        end

        if i>1000 & ~disp_1k then
            disp_1k := true
            stream$putl(po, "\n" || int$unparse(upto_1k)
                        || " eban numbers <= 1000\n")
        end

        if i<=4000 then stream$putright(po, int$unparse(i), 5) end

        if i>4000 & ~disp_4k then
            disp_4k := true
            stream$putl(po, "\n" || int$unparse(between_1k_4k)
                        || " eban numbers 1000 <= x <= 4000\n")
        end

        if nextmagn>maxmagn then break end
    end
end start_up


USING: arrays formatting fry io kernel math math.functions
math.order math.ranges prettyprint sequences ;

: eban? ( n -- ? )
    1000000000 /mod 1000000 /mod 1000 /mod
    [ dup 30 66 between? [ 10 mod ] when ] [email protected] 4array
    [ { 0 2 4 6 } member? ] all? ;

: .eban ( m n -- ) "eban numbers in [%d, %d]: " printf ;
: eban ( m n q -- o ) '[ 2dup .eban [a,b] [ eban? ] @ ] call ; inline
: .eban-range ( m n -- ) [ filter ] eban "%[%d, %]\n" printf ;
: .eban-count ( m n -- ) "count of " write [ count ] eban . ;

1 1000 1000 4000 [ .eban-range ] [email protected]
4 9 [a,b] [ [ 1 10 ] dip ^ .eban-count ] each


' Eban_numbers
' Un número eban es un número que no tiene la letra e cuando el número está escrito en inglés.
' O más literalmente, los números escritos que contienen la letra e están prohibidos.
'
' Usaremos la versión americana de los números de ortografía (a diferencia de los británicos).
'  2000000000 son dos billones, no dos millardos (mil millones).
'

Data 2, 1000, 1
Data 1000, 4000, 1
Data 2, 10000, 0
Data 2, 100000, 0
Data 2, 1000000, 0
Data 2, 10000000, 0
Data 2, 100000000, 0
Data 0, 0, 0

Dim As Double tiempo = Timer
Dim As Integer start, ended, printable, count
Dim As Long i, b, r, m, t
Do
    Read start, ended, printable

    If start = 0 Then Exit Do
    If start = 2 Then
        Print "eban numbers up to and including"; ended; ":"
    Else
        Print "eban numbers between "; start; " and "; ended; " (inclusive):"
    End If

    count = 0
    For i = start To ended Step 2
        b = Int(i / 1000000000)
        r = (i Mod 1000000000)
        m = Int(r / 1000000)
        r = (i Mod 1000000)
        t = Int(r / 1000)
        r = (r Mod 1000)
        If m >= 30 And m <= 66 Then m = (m Mod 10)
        If t >= 30 And t <= 66 Then t = (t Mod 10)
        If r >= 30 And r <= 66 Then r = (r Mod 10)
        If b = 0 Or b = 2 Or b = 4 Or b = 6 Then
            If m = 0 Or m = 2 Or m = 4 Or m = 6 Then
                If t = 0 Or t = 2 Or t = 4 Or t = 6 Then
                    If r = 0 Or r = 2 Or r = 4 Or r = 6 Then
                        If printable Then Print i;
                        count += 1
                    End If
                End If
            End If
        End If
    Next i
    If printable Then Print
    Print "count = "; count & Chr(10)
Loop
tiempo = Timer - tiempo
Print "Run time: " & (tiempo) & " seconds."
End


package main

import "fmt"

type Range struct {
    start, end uint64
    print      bool
}

func main() {
    rgs := []Range{
        {2, 1000, true},
        {1000, 4000, true},
        {2, 1e4, false},
        {2, 1e5, false},
        {2, 1e6, false},
        {2, 1e7, false},
        {2, 1e8, false},
        {2, 1e9, false},
    }
    for _, rg := range rgs {
        if rg.start == 2 {
            fmt.Printf("eban numbers up to and including %d:\n", rg.end)
        } else {
            fmt.Printf("eban numbers between %d and %d (inclusive):\n", rg.start, rg.end)
        }
        count := 0
        for i := rg.start; i <= rg.end; i += 2 {
            b := i / 1000000000
            r := i % 1000000000
            m := r / 1000000
            r = i % 1000000
            t := r / 1000
            r %= 1000
            if m >= 30 && m <= 66 {
                m %= 10
            }
            if t >= 30 && t <= 66 {
                t %= 10
            }
            if r >= 30 && r <= 66 {
                r %= 10
            }
            if b == 0 || b == 2 || b == 4 || b == 6 {
                if m == 0 || m == 2 || m == 4 || m == 6 {
                    if t == 0 || t == 2 || t == 4 || t == 6 {
                        if r == 0 || r == 2 || r == 4 || r == 6 {
                            if rg.print {
                                fmt.Printf("%d ", i)
                            }
                            count++
                        }
                    }
                }
            }
        }
        if rg.print {
            fmt.Println()
        }
        fmt.Println("count =", count, "\n")
    }
}


class Main {
    private static class Range {
        int start
        int end
        boolean print

        Range(int s, int e, boolean p) {
            start = s
            end = e
            print = p
        }
    }

    static void main(String[] args) {
        List<Range> rgs = Arrays.asList(
                new Range(2, 1000, true),
                new Range(1000, 4000, true),
                new Range(2, 10_000, false),
                new Range(2, 100_000, false),
                new Range(2, 1_000_000, false),
                new Range(2, 10_000_000, false),
                new Range(2, 100_000_000, false),
                new Range(2, 1_000_000_000, false)
        )
        for (Range rg : rgs) {
            if (rg.start == 2) {
                println("eban numbers up to and including $rg.end")
            } else {
                println("eban numbers between $rg.start and $rg.end")
            }
            int count = 0
            for (int i = rg.start; i <= rg.end; ++i) {
                int b = (int) (i / 1_000_000_000)
                int r = i % 1_000_000_000
                int m = (int) (r / 1_000_000)
                r = i % 1_000_000
                int t = (int) (r / 1_000)
                r %= 1_000
                if (m >= 30 && m <= 66) m %= 10
                if (t >= 30 && t <= 66) t %= 10
                if (r >= 30 && r <= 66) r %= 10
                if (b == 0 || b == 2 || b == 4 || b == 6) {
                    if (m == 0 || m == 2 || m == 4 || m == 6) {
                        if (t == 0 || t == 2 || t == 4 || t == 6) {
                            if (r == 0 || r == 2 || r == 4 || r == 6) {
                                if (rg.print) {
                                    print("$i ")
                                }
                                count++
                            }
                        }
                    }
                }
            }
            if (rg.print) {
                println()
            }
            println("count = $count")
            println()
        }
    }
}


{-# LANGUAGE NumericUnderscores #-}
import Data.List (intercalate)
import Text.Printf (printf)
import Data.List.Split (chunksOf)

isEban :: Int -> Bool
isEban n = all (`elem` [0, 2, 4, 6]) z
 where
  (b, r1) = n  `quotRem` (10 ^ 9)
  (m, r2) = r1 `quotRem` (10 ^ 6)
  (t, r3) = r2 `quotRem` (10 ^ 3)
  z       = b : map (\x -> if x >= 30 && x <= 66 then x `mod` 10 else x) [m, t, r3]

ebans = map f
 where
  f x = (thousands x, thousands $ length $ filter isEban [1..x])

thousands:: Int -> String
thousands = reverse . intercalate "," . chunksOf 3 . reverse . show

main :: IO ()
main = do
  uncurry (printf "eban numbers up to and including 1000: %2s\n%s\n\n") $ r [1..1000]
  uncurry (printf "eban numbers between 1000 and 4000: %2s\n%s\n\n") $ r [1000..4000]
  mapM_ (uncurry (printf "eban numbers up and including %13s: %5s\n")) ebanCounts
 where
  ebanCounts = ebans [        10_000
                     ,       100_000
                     ,     1_000_000
                     ,    10_000_000
                     ,   100_000_000
                     , 1_000_000_000 ]
  r = ((,) <$> thousands . length <*> show) . filter isEban


Filter =: (#~`)(`:6)

itemAmend =: (29&< *. <&67)`(,: 10&|)}
iseban =: [: *./ 0 2 4 6 e.~ [: itemAmend [: |: (4#1000)&#:

   (;~ #) iseban Filter >: i. 1000
┌──┬─────────────────────────────────────────────────────┐
│19│2 4 6 30 32 34 36 40 42 44 46 50 52 54 56 60 62 64 66│
└──┴─────────────────────────────────────────────────────┘

   NB. INPUT are the correct integers, head and tail shown
   ({. , {:) INPUT =: 1000 + i. 3001
1000 4000

   (;~ #)  iseban Filter INPUT
┌──┬────────────────────────────────────────────────────────────────────────────────────────────────────────┐
│21│2000 2002 2004 2006 2030 2032 2034 2036 2040 2042 2044 2046 2050 2052 2054 2056 2060 2062 2064 2066 4000│
└──┴────────────────────────────────────────────────────────────────────────────────────────────────────────┘
   (, ([: +/ [: iseban [: >: i.))&> 10000 * 10 ^ i. +:2
 10000   79
100000  399
   1e6  399
   1e7 1599


import java.util.List;

public class Main {
    private static class Range {
        int start;
        int end;
        boolean print;

        public Range(int s, int e, boolean p) {
            start = s;
            end = e;
            print = p;
        }
    }

    public static void main(String[] args) {
        List<Range> rgs = List.of(
            new Range(2, 1000, true),
            new Range(1000, 4000, true),
            new Range(2, 10_000, false),
            new Range(2, 100_000, false),
            new Range(2, 1_000_000, false),
            new Range(2, 10_000_000, false),
            new Range(2, 100_000_000, false),
            new Range(2, 1_000_000_000, false)
        );
        for (Range rg : rgs) {
            if (rg.start == 2) {
                System.out.printf("eban numbers up to and including %d\n", rg.end);
            } else {
                System.out.printf("eban numbers between %d and %d\n", rg.start, rg.end);
            }
            int count = 0;
            for (int i = rg.start; i <= rg.end; ++i) {
                int b = i / 1_000_000_000;
                int r = i % 1_000_000_000;
                int m = r / 1_000_000;
                r = i % 1_000_000;
                int t = r / 1_000;
                r %= 1_000;
                if (m >= 30 && m <= 66) m %= 10;
                if (t >= 30 && t <= 66) t %= 10;
                if (r >= 30 && r <= 66) r %= 10;
                if (b == 0 || b == 2 || b == 4 || b == 6) {
                    if (m == 0 || m == 2 || m == 4 || m == 6) {
                        if (t == 0 || t == 2 || t == 4 || t == 6) {
                            if (r == 0 || r == 2 || r == 4 || r == 6) {
                                if (rg.print) System.out.printf("%d ", i);
                                count++;
                            }
                        }
                    }
                }
            }
            if (rg.print) {
                System.out.println();
            }
            System.out.printf("count = %d\n\n", count);
        }
    }
}


# quotient and remainder
def quotient($a; $b; f; g): f = (($a/$b)|floor) | g = $a % $b;

def tasks:
    [2, 1000, true],
    [1000, 4000, true],
    (1e4, 1e5, 1e6, 1e7, 1e8 | [2, ., false]) ;

def task:
  def update(f): if (f >= 30 and f <= 66) then f %= 10 else . end;

  tasks as $rg
  | if $rg[0] == 2
    then "eban numbers up to and including \($rg[1]):"
    else "eban numbers between \($rg[0]) and \($rg[1]) (inclusive):"
    end,
    ( foreach (range( $rg[0]; 1 + $rg[1]; 2), null) as $i ( { count: 0 };
        .emit = false
        | if $i == null then .total = .count
          else quotient($i; 1e9; .b; .r)
          |    quotient(.r; 1e6; .m; .r)
          |    quotient(.r; 1e3; .t; .r)
          | update(.m) | update(.t) | update(.r)
          | if all(.b, .m, .t, .r; IN(0, 2, 4, 6))
            then .count += 1
            | if ($rg[2]) then .emit=$i else . end
            else .
  	    end
  	  end;
  	  if .emit then .emit else empty end,
  	  if .total then "count = \(.count)\n" else empty end) );

task


function iseban(n::Integer)
    b, r = divrem(n, oftype(n, 10 ^ 9))
    m, r = divrem(r, oftype(n, 10 ^ 6))
    t, r = divrem(r, oftype(n, 10 ^ 3))
    m, t, r = (30 <= x <= 66 ? x % 10 : x for x in (m, t, r))
    return all(in((0, 2, 4, 6)), (b, m, t, r))
end

println("eban numbers up to and including 1000:")
println(join(filter(iseban, 1:100), ", "))

println("eban numbers between 1000 and 4000 (inclusive):")
println(join(filter(iseban, 1000:4000), ", "))

println("eban numbers up to and including 10000: ", count(iseban, 1:10000))
println("eban numbers up to and including 100000: ", count(iseban, 1:100000))
println("eban numbers up to and including 1000000: ", count(iseban, 1:1000000))
println("eban numbers up to and including 10000000: ", count(iseban, 1:10000000))
println("eban numbers up to and including 100000000: ", count(iseban, 1:100000000))
println("eban numbers up to and including 1000000000: ", count(iseban, 1:1000000000))


function makeInterval(s,e,p)
    return {start=s, end_=e, print_=p}
end

function main()
    local intervals = {
        makeInterval(   2,       1000, true),
        makeInterval(1000,       4000, true),
        makeInterval(   2,      10000, false),
        makeInterval(   2,    1000000, false),
        makeInterval(   2,   10000000, false),
        makeInterval(   2,  100000000, false),
        makeInterval(   2, 1000000000, false)
    }
    for _,intv in pairs(intervals) do
        if intv.start == 2 then
            print("eban numbers up to and including " .. intv.end_ .. ":")
        else
            print("eban numbers between " .. intv.start .. " and " .. intv.end_ .. " (inclusive)")
        end

        local count = 0
        for i=intv.start,intv.end_,2 do
            local b = math.floor(i / 1000000000)
            local r = i % 1000000000
            local m = math.floor(r / 1000000)
            r = i % 1000000
            local t = math.floor(r / 1000)
            r = r % 1000
            if m >= 30 and m <= 66 then m = m % 10 end
            if t >= 30 and t <= 66 then t = t % 10 end
            if r >= 30 and r <= 66 then r = r % 10 end
            if b == 0 or b == 2 or b == 4 or b == 6 then
                if m == 0 or m == 2 or m == 4 or m == 6 then
                    if t == 0 or t == 2 or t == 4 or t == 6 then
                        if r == 0 or r == 2 or r == 4 or r == 6 then
                            if intv.print_ then io.write(i .. " ") end
                            count = count + 1
                        end
                    end
                end
            end
        end

        if intv.print_ then
            print()
        end
        print("count = " .. count)
        print()
    end
end

main()


import strformat

proc iseban(n: int): bool =
  if n == 0:
    return false
  var b = n div 1_000_000_000
  var r = n mod 1_000_000_000
  var m = r div 1_000_000
  r = r mod 1_000_000
  var t = r div 1_000
  r = r mod 1_000
  m = if m in 30..66: m mod 10 else: m
  t = if t in 30..66: t mod 10 else: t
  r = if r in 30..66: r mod 10 else: r
  return {b, m, t, r} <= {0, 2, 4, 6}

echo "eban numbers up to and including 1000:"
for i in 0..100:
  if iseban(i):
    stdout.write(&"{i} ")

echo "\n\neban numbers between 1000 and 4000 (inclusive):"
for i in 1_000..4_000:
  if iseban(i):
    stdout.write(&"{i} ")

var count = 0
for i in 0..10_000:
  if iseban(i):
    inc count
echo &"\n\nNumber of eban numbers up to and including {10000:8}: {count:4}"

count = 0
for i in 0..100_000:
  if iseban(i):
    inc count
echo &"\nNumber of eban numbers up to and including {100000:8}: {count:4}"

count = 0
for i in 0..1_000_000:
  if iseban(i):
    inc count
echo &"\nNumber of eban numbers up to and including {1000000:8}: {count:4}"

count = 0
for i in 0..10_000_000:
  if iseban(i):
    inc count
echo &"\nNumber of eban numbers up to and including {10000000:8}: {count:4}"

count = 0
for i in 0..100_000_000:
  if iseban(i):
    inc count
echo &"\nNumber of eban numbers up to and including {100000000:8}: {count:4}"


use strict;
use warnings;
use feature 'say';
use Lingua::EN::Numbers qw(num2en);

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

sub e_ban {
    my($power) = @_;
    my @n;
    for (1..10**$power) {
        next unless 0 == $_%2;
        next if $_ =~ /[789]/ or /[12].$/ or /[135]..$/ or /[135]...$/ or /[135].....$/;
        push @n, $_ unless num2en($_) =~ /e/;
    }
    @n;
}

my @OK = e_ban(my $max = 7);

my @a = grep { $_ <= 1000 } @OK;
say "Number of eban numbers up to and including 1000: @{[1+$#a]}";
say join(', ',@a);
say '';

my @b = grep { $_ >= 1000 && $_ <= 4000 } @OK;
say "Number of eban numbers between 1000 and 4000 (inclusive): @{[1+$#b]}";
say join(', ',@b);
say '';

for my $exp (4..$max) {
    my $n = + grep { $_ <= 10**$exp } @OK;
    printf "Number of eban numbers and %10s: %d\n", comma(10**$exp), $n;
}


with javascript_semantics
function count_eban(integer p10)
-- returns the count of eban numbers 1..power(10,p10)
    integer n = p10-floor(p10/3),
            p5 = floor(n/2),
            p4 = floor((n+1)/2)
    return power(5,p5)*power(4,p4)-1
end function

function eban(integer n)
-- returns true if n is an eban number (only fully tested to 10e9)
    if n=0 then return false end if
    while n do
        integer thou = remainder(n,1000)
        if floor(thou/100)!=0 then return false end if
        if not find(floor(thou/10),{0,3,4,5,6}) then return false end if
        if not find(remainder(thou,10),{0,2,4,6}) then return false end if
        n = floor(n/1000)
    end while
    return true
end function

sequence s = {}
for i=0 to 1000 do
    if eban(i) then s = append(s,sprint(i)) end if
end for
printf(1,"eban to 1000 : %s\n\n",{join(shorten(s,"items",8))})
s = {}
for i=1000 to 4000 do
    if eban(i) then s = append(s,sprint(i)) end if
end for
printf(1,"eban 1000..4000 : %s\n\n",{join(shorten(s,"items",4))})

atom t0 = time()
for i=0 to 21 do
    printf(1,"count_eban(10^%d) : %,d\n",{i,count_eban(i)})
end for
?elapsed(time()-t0)


(de _eban? (N)
   (let
      (B (/ N 1000000000)
         R (% N 1000000000)
         M (/ R 1000000)
         R (% N 1000000)
         Z (/ R 1000)
         R (% R 1000) )
      (and
         (>= M 30)
         (<= M 66)
         (setq M (% M 10)) )
      (and
         (>= Z 30)
         (<= Z 66)
         (setq Z (% Z 10)) )
      (and
         (>= R 30)
         (<= R 66)
         (setq R (% R 10)) )
      (fully
         '((S)
            (unless (bit? 1 (val S))
               (>= 6 (val S)) ) )
         '(B M Z R) ) ) )
(de eban (B A)
   (default A 2)
   (let R (cons 0 (cons))
      (for (N A (>= B N) (+ N 2))
         (and
            (_eban? N)
            (inc R)
            (push (cdr R) N) ) )
      (con R (flip (cadr R)))
      R ) )
(off R)
(prinl "eban numbers up to an including 1000:")
(setq R (eban 1000))
(println (cdr R))
(prinl "count: " (car R))
(prinl)
(prinl "eban numbers between 1000 and 4000")
(setq R (eban 4000 1000))
(println (cdr R))
(prinl "count: " (car R))
(prinl)
(prinl "eban numbers up to an including 10000:")
(prinl "count: " (car (eban 10000)))
(prinl)
(prinl "eban numbers up to an including 100000:")
(prinl "count: " (car (eban 100000)))
(prinl)
(prinl "eban numbers up to an including 1000000:")
(prinl "count: " (car (eban 1000000)))
(prinl)
(prinl "eban numbers up to an including 10000000:")
(prinl "count: " (car (eban 10000000)))


# Use inflect

"""

  show all eban numbers <= 1,000 (in a horizontal format), and a count
  show all eban numbers between 1,000 and 4,000 (inclusive), and a count
  show a count of all eban numbers up and including 10,000
  show a count of all eban numbers up and including 100,000
  show a count of all eban numbers up and including 1,000,000
  show a count of all eban numbers up and including 10,000,000

"""

import inflect
import time

before = time.perf_counter()

p = inflect.engine()

# eban numbers <= 1000

print(' ')
print('eban numbers up to and including 1000:')
print(' ')

count = 0

for i in range(1,1001):
    if not 'e' in p.number_to_words(i):
        print(str(i)+' ',end='')
        count += 1

print(' ')
print(' ')
print('count = '+str(count))
print(' ')

# eban numbers 1000 to 4000

print(' ')
print('eban numbers between 1000 and 4000 (inclusive):')
print(' ')

count = 0

for i in range(1000,4001):
    if not 'e' in p.number_to_words(i):
        print(str(i)+' ',end='')
        count += 1

print(' ')
print(' ')
print('count = '+str(count))
print(' ')

# eban numbers up to 10000

print(' ')
print('eban numbers up to and including 10000:')
print(' ')

count = 0

for i in range(1,10001):
    if not 'e' in p.number_to_words(i):
        count += 1

print(' ')
print('count = '+str(count))
print(' ')

# eban numbers up to 100000

print(' ')
print('eban numbers up to and including 100000:')
print(' ')

count = 0

for i in range(1,100001):
    if not 'e' in p.number_to_words(i):
        count += 1

print(' ')
print('count = '+str(count))
print(' ')

# eban numbers up to 1000000

print(' ')
print('eban numbers up to and including 1000000:')
print(' ')

count = 0

for i in range(1,1000001):
    if not 'e' in p.number_to_words(i):
        count += 1

print(' ')
print('count = '+str(count))
print(' ')

# eban numbers up to 10000000

print(' ')
print('eban numbers up to and including 10000000:')
print(' ')

count = 0

for i in range(1,10000001):
    if not 'e' in p.number_to_words(i):
        count += 1

print(' ')
print('count = '+str(count))
print(' ')

after = time.perf_counter()

print(" ")
print("Run time in seconds: "+str(after - before))


use Lingua::EN::Numbers;

sub nban ($seq, $n = 'e') { ($seq).map: { next if .&cardinal.contains(any($n.lc.comb)); $_ } }

sub enumerate ($n, $upto) {
    my @ban = [nban(1 .. 99, $n)],;
    my @orders;
    (2 .. $upto).map: -> $o {
        given $o % 3 { # Compensate for irregulars: 11 - 19
            when 1  { @orders.push: [flat (10**($o - 1) X* 10 .. 19).map(*.&nban($n)), |(10**$o X* 2 .. 9).map: *.&nban($n)] }
            default { @orders.push: [flat (10**$o X* 1 .. 9).map: *.&nban($n)] }
        }
    }
    ^@orders .map: -> $o {
        @ban.push: [] and next unless +@orders[$o];
        my @these;
        @orders[$o].map: -> $m {
            @these.push: $m;
            for ^@ban -> $b {
                next unless +@ban[$b];
                @these.push: $_ for (flat @ban[$b]) »+» $m ;
            }
        }
        @ban.push: @these;
    }
    @ban.unshift(0) if nban(0, $n);
    flat @ban.map: *.flat;
}

sub count ($n, $upto) {
    my @orders;
    (2 .. $upto).map: -> $o {
        given $o % 3 { # Compensate for irregulars: 11 - 19
            when 1  { @orders.push: [flat (10**($o - 1) X* 10 .. 19).map(*.&nban($n)), |(10**$o X* 2 .. 9).map: *.&nban($n)] }
            default { @orders.push: [flat (10**$o X* 1 .. 9).map: *.&nban($n)] }
        }
    }
    my @count  = +nban(1 .. 99, $n);
    ^@orders .map: -> $o {
        @count.push: 0 and next unless +@orders[$o];
        my $prev = so (@orders[$o].first( { $_ ~~ /^ '1' '0'+ $/ } ) // 0 );
        my $sum = @count.sum;
        my $these = +@orders[$o] * $sum + @orders[$o];
        $these-- if $prev;
        @count[1 + $o] += $these;
        ++@count[$o]  if $prev;
    }
    ++@count[0] if nban(0, $n);
    [\+] @count;
}

#for < e o t tali subur tur ur cali i u > -> $n { # All of them
for < e t subur > -> $n { # An assortment for demonstration
    my $upto   = 21; # 1e21
    my @bans   = enumerate($n, 4);
    my @counts = count($n, $upto);

    # DISPLAY
    my @k = @bans.grep: * < 1000;
    my @j = @bans.grep: 1000 <= * <= 4000;
    put "\n============= {$n}-ban: =============\n" ~
        "{$n}-ban numbers up to 1000: {[email protected]}\n[{@k».&comma}]\n\n" ~
        "{$n}-ban numbers between 1,000 & 4,000: {[email protected]}\n[{@j».&comma}]\n" ~
        "\nCounts of {$n}-ban numbers up to {cardinal 10**$upto}"
        ;

    my $s = max (1..$upto).map: { (10**$_).&cardinal.chars };
    @counts.unshift: @bans.first: * > 10, :k;
    for ^$upto -> $c {
        printf "Up to and including %{$s}s: %s\n", cardinal(10**($c+1)), comma(@counts[$c]);
    }
}


/*REXX program to display eban numbers (those that don't have an "e" their English name)*/
numeric digits 20                                /*support some gihugic numbers for pgm.*/
parse arg $                                      /*obtain optional arguments from the cL*/
if $=''  then $= '1 1000   1000 4000   1 -10000   1 -100000   1 -1000000   1 -10000000'

      do k=1  by 2  to words($)                  /*step through the list of numbers.    */
      call banE  word($, k),  word($, k+1)       /*process the numbers, from low──►high.*/
      end   /*k*/
exit                                             /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
banE: procedure; parse arg x,y,_;  z= reverse(x) /*obtain the number to be examined.    */
      tell= y>=0                                 /*Is HI non-negative?  Display eban #s.*/
      #= 0                                       /*the count of  eban  numbers (so far).*/
           do j=x  to abs(y)                     /*probably process a range of numbers. */
           if hasE(j)  then iterate              /*determine if the number has an  "e". */
           #= # + 1                              /*bump the counter of  eban  numbers.  */
           if tell  then _= _  j                 /*maybe add to a list of eban numbers. */
           end   /*j*/
      if _\==''  then say strip(_)               /*display the list  (if there is one). */
      say;     say #   ' eban numbers found for: '   x   " "   y;     say copies('═', 105)
      return
/*──────────────────────────────────────────────────────────────────────────────────────*/
hasE: procedure; parse arg x;  z= reverse(x)     /*obtain the number to be examined.    */
        do k=1  by 3                             /*while there're dec. digit to examine.*/
        @= reverse( substr(z, k, 3) )            /*obtain 3 dec. digs (a period) from Z.*/
        if @=='   '           then return 0      /*we have reached the "end" of the num.*/
        uni= right(@, 1)                         /*get units dec. digit of this period. */
        if uni//2==1          then return 1      /*if an odd digit, then not an eban #. */
        if uni==8             then return 1      /*if an  eight,      "   "   "   "  "  */
        tens=substr(@, 2, 1)                     /*get tens  dec. digit of this period. */
        if tens==1            then return 1      /*if teens,        then not an eban #. */
        if tens==2            then return 1      /*if twenties,       "   "   "   "  "  */
        if tens>6             then return 1      /*if 70s, 80s, 90s,  "   "   "   "  "  */
        hun= left(@, 1)                          /*get hundreds dec. dig of this period.*/
        if hun==0             then iterate       /*if zero, then there is more of number*/
        if hun\==' '          then return 1      /*any hundrEd (not zero) has an  "e".  */
        end   /*k*/                              /*A "period" is a group of 3 dec. digs */
     return 0                                    /*in the number, grouped from the right*/


V colours_in_order = ‘Red White Blue’.split(‘ ’)

F dutch_flag_sort3(items)
   [String] r
   L(colour) :colours_in_order
      r.extend([colour] * items.count(colour))
   R r

V balls = [‘Red’, ‘Red’, ‘Blue’, ‘Blue’, ‘Blue’, ‘Red’, ‘Red’, ‘Red’, ‘White’, ‘Blue’]
print(‘Original Ball order: ’balls)
V sorted_balls = dutch_flag_sort3(balls)
print(‘Sorted Ball Order: ’sorted_balls)


def main
    intervals = [
        [2, 1000, true],
        [1000, 4000, true],
        [2, 10000, false],
        [2, 100000, false],
        [2, 1000000, false],
        [2, 10000000, false],
        [2, 100000000, false],
        [2, 1000000000, false]
    ]
    for intv in intervals
        (start, ending, display) = intv
        if start == 2 then
            print "eban numbers up to and including %d:\n" % [ending]
        else
            print "eban numbers between %d and %d (inclusive):\n" % [start, ending]
        end

        count = 0
        for i in (start .. ending).step(2)
            b = (i / 1000000000).floor
            r = (i % 1000000000)
            m = (r / 1000000).floor
            r = (r % 1000000)
            t = (r / 1000).floor
            r = (r % 1000)
            if m >= 30 and m <= 66 then
                m = m % 10
            end
            if t >= 30 and t <= 66 then
                t = t % 10
            end
            if r >= 30 and r <= 66 then
                r = r % 10
            end
            if b == 0 or b == 2 or b == 4 or b == 6 then
                if m == 0 or m == 2 or m == 4 or m == 6 then
                    if t == 0 or t == 2 or t == 4 or t == 6 then
                        if r == 0 or r == 2 or r == 4 or r == 6 then
                            if display then
                                print ' ', i
                            end
                            count = count + 1
                        end
                    end
                end
            end
        end
        if display then
            print "\n"
        end
        print "count = %d\n\n" % [count]
    end
end

main()