with Ada.Text_IO, Miller_Rabin;

procedure Prime_Gen is

   type Num is range 0 .. 2**63-1; -- maximum for the gnat Ada compiler

   MR_Iterations: constant Positive := 25;
     -- the probability Pr[Is_Prime(N, MR_Iterations) = Probably_Prime]
     -- is 1 for prime N and < 4**(-MR_Iterations) for composed N

   function Next(P: Num) return Num is
      N: Num := P+1;
      package MR is new Miller_Rabin(Num); use MR;
   begin
      while not (Is_Prime(N, MR_Iterations) = Probably_Prime) loop
	 N := N + 1;
      end loop;
      return N;
   end Next;

   Current: Num;
   Count: Num := 0;

begin
   -- show the first twenty primes
   Ada.Text_IO.Put("First 20 primes:");
   Current := 1;
   for I in 1 .. 20 loop
      Current := Next(Current);
      Ada.Text_IO.Put(Num'Image(Current));
   end loop;
   Ada.Text_IO.New_Line;

   -- show the primes between 100 and 150
   Ada.Text_IO.Put("Primes between 100 and 150:");
   Current := 99;
   loop
      Current := Next(Current);
      exit when Current > 150;
      Ada.Text_IO.Put(Num'Image(Current));
   end loop;
   Ada.Text_IO.New_Line;

   -- count primes between 7700 and 8000
   Ada.Text_IO.Put("Number of primes between 7700 and 8000:");
   Current := 7699;
   loop
      Current := Next(Current);
      exit when Current > 8000;
      Count := Count + 1;
   end loop;
   Ada.Text_IO.Put_Line(Num'Image(Count));

   Count := 10;
   Ada.Text_IO.Put_Line("Print the K_i'th prime, for $K=10**i:");
   begin
      loop
	 Current := 1;
	 for I in 1 .. Count loop
	    Current := Next(Current);
	 end loop;
	 Ada.Text_IO.Put(Num'Image(Count) & "th prime:" &
			Num'Image(Current));
	 Count := Count * 10;
      end loop;
   exception
      when Constraint_Error =>
	 Ada.Text_IO.Put_Line(" can't compute the" & Num'Image(Count) &
				"th prime:");
   end;
end;


import "io" for Stdin

// 'raw' is a multi-line string
var snusp = Fn.new { |dlen, raw|
    var ds = List.filled(dlen, 0) // data store
    var dp = 0 // data pointer

    // remove leading \n if it's there
    if (raw[0] == "\n") raw = raw[1..-1]

    // make 2 dimensional instruction store & declare instruction pointers
    var s = raw.split("\n")
    var ipr = 0
    var ipc = 0

    // look for starting instruction
    for (r in 0...s.count) {
        var row = s[r]
        var outer = false
        for (c in 0...row.count) {
            var i = row[c]
            if (i == "$") {
                ipr = r
                ipc = c
                outer = true
                break
            }
        }
        if (outer) break
    }

    var id = 0
    var step = Fn.new {
        if (id&1 == 0) {
            ipc = ipc + 1 - (id&2)
        } else {
            ipr = ipr + 1 - (id&2)
        }
    }

    // execute
    while (ipr >= 0 && ipr < s.count && ipc >= 0 && ipc < s[ipr].count) {
        var c = s[ipr][ipc]
        if (c == ">") {
            dp = dp + 1
        } else if (c == "<") {
            dp = dp - 1
        } else if (c == "+") {
            ds[dp] = ds[dp] + 1
        } else if (c == "-") {
            ds[dp] = ds[dp] - 1
        } else if (c == ".") {
            System.write(String.fromByte(ds[dp]))
        } else if (c == ",") {
            ds[dp] = Stdin.readByte()
        } else if (c == "/") {
            id = ~id
        } else if (c == "\\") {
            id = id ^ 1
        } else if (c == "!") {
            step.call()
        } else if (c == "?") {
            if (ds[dp] == 0) step.call()
        }
        step.call()
    }
}

var hw =
    "/++++!/===========?\\>++.>+.+++++++..+++\\\n" +
    "\\+++\\ | /+>+++++++>/ /++++++++++<<.++>./\n" +
    "$+++/ | \\+++++++++>\\ \\+++++.>.+++.-----\\\n" +
    "      \\==-<<<<+>+++/ /=.>.+>.--------.-/"
snusp.call(5, hw)


switch {condition1,condition2} do
    case {true,true}:
    case {true,false}:
    case {false,true}:
    case {false,false}:
end switch


module stmts;

import phl::lang::io;

/* LinkedList --> Each element contains a condition */
struct @ConditionalChain {
	field @Boolean cond;
	field @ConditionalChain next;

	@ConditionalChain init(@Boolean cond, @ConditionalChain next) [
		this::cond = cond;
		this::next = next;

		return this;
	]

	/*
	 *	If the condition is true executes the closure and returns a false element, otherwise returns the next condition
	 *
	 *	Execution starts from the first element, and iterates until the right element is found.
	 */
	@ConditionalChain then(@Closure<@Void> closure) [
		if (isNull(next())) return new @ConditionalChain.init(false, null);
		if (cond()) {
			closure();
			return new @ConditionalChain.init(false, null);
		}
		else return next();
	]

	/* Operators create a cool look */
	@ConditionalChain operator then(@Closure<@Void> closure) alias @ConditionalChain.then;
	@ConditionalChain operator else1(@Closure<@Void> closure) alias @ConditionalChain.then;
	@ConditionalChain operator else2(@Closure<@Void> closure) alias @ConditionalChain.then;
	@ConditionalChain operator orElse(@Closure<@Void> closure) alias @ConditionalChain.then;
};

/* Returns linked list [a && b, a, b, true] */
@ConditionalChain if2(@Boolean a, @Boolean b) [
	return new @ConditionalChain.init(a && b, new @ConditionalChain.init(a, new @ConditionalChain.init(b, new @ConditionalChain.init(true, null))));
]

@Void main [
	if2(false, true) then [
		println("Not this!");
	] else1 [
		println("Not this!");
	] else2 [
		println("This!");
	] orElse [
		println("Not this!");
	];
]


(undef 'if2)  # Undefine the built-in 'if2'

(de if2 "P"
   (if (eval (pop '"P"))
      (eval ((if (eval (car "P")) cadr caddr) "P"))
      (if (eval (car "P"))
         (eval (cadddr "P"))
         (run (cddddr "P")) ) ) )


0 1 dup wover + dup wover + dup wover + dup wover +


SetBatchLines, -1
p := 1	;p functions as the counter
Loop, 10000 {
	p := NextPrime(p)
	if (A_Index < 21)
		a .= p ", "
	if (p < 151 && p > 99)
		b .= p ", "
	if (p < 8001 && p > 7699)
		c++
}
MsgBox, % "First twenty primes: " RTrim(a, ", ")
	. "`nPrimes between 100 and 150: " RTrim(b, ", ")
	. "`nNumber of primes between 7,700 and 8,000: " RTrim(c, ", ")
	. "`nThe 10,000th prime: " p

NextPrime(n) {
	Loop
		if (IsPrime(++n))
			return n
}

IsPrime(n) {
	if (n < 2)
		return, 0
	else if (n < 4)
		return, 1
	else if (!Mod(n, 2))
		return, 0
	else if (n < 9)
		return 1
	else if (!Mod(n, 3))
		return, 0
	else {
		r := Floor(Sqrt(n))
		f := 5
		while (f <= r) {
			if (!Mod(n, f))
				return, 0
			if (!Mod(n, (f + 2)))
				return, 0
			f += 6
		}
		return, 1
	}
}


function When-Condition
{
    [CmdletBinding()]
    Param
    (
        [Parameter(Mandatory=$true, Position=0)]
        [bool]
        $Test1,

        [Parameter(Mandatory=$true, Position=1)]
        [bool]
        $Test2,

        [Parameter(Mandatory=$true, Position=2)]
        [scriptblock]
        $Both,

        [Parameter(Mandatory=$true, Position=3)]
        [scriptblock]
        $First,

        [Parameter(Mandatory=$true, Position=4)]
        [scriptblock]
        $Second,

        [Parameter(Mandatory=$true, Position=5)]
        [scriptblock]
        $Neither
    )

    if ($Test1 -and $Test2)
    {
        return (&$Both)
    }
    elseif ($Test1 -and -not $Test2)
    {
        return (&$First)
    }
    elseif (-not $Test1 -and $Test2)
    {
        return (&$Second)
    }
    else
    {
        return (&$Neither)
    }
}


'
' Compute nth Fibonacci number
'
' open a window for display
OPENW 1
CLEARW 1
' Display some fibonacci numbers
' Fib(46) is the largest number GFA Basic can reach
' (long integers are 4 bytes)
FOR i%=0 TO 46
  PRINT "fib(";i%;")=";@fib(i%)
NEXT i%
' wait for a key press and tidy up
~INP(2)
CLOSEW 1
'
' Function to compute nth fibonacci number
' n must be in range 0 to 46, inclusive
'
FUNCTION fib(n%)
  LOCAL n0%,n1%,nn%,i%
  n0%=0
  n1%=1
  SELECT n%
  CASE 0
    RETURN n0%
  CASE 1
    RETURN n1%
  DEFAULT
    FOR i%=2 TO n%
      nn%=n0%+n1%
      n0%=n1%
      n1%=nn%
    NEXT i%
    RETURN nn%
  ENDSELECT
ENDFUNC


}:r:        Start reader loop.
  |~  	    Read n,
  #:end:    if n is 0 terminates
  >=        enqueue it as the initial product, reposition.
  }:f:      Start factorial loop.
    x<:1:x- Decrement n.
    {=*>    Dequeue product, position n, multiply, update product.
  ^:f:
  {+%       Dequeue incidental 0, add to get Y into Z, output fac(n).
  <:a:~$    Output a newline.
^:r:


BEGIN # execute some ComputerZero programs                                 #
    # instructions                                                         #
    INT nop = 0, lda = 1, sta = 2, add = 3, sub = 4, brz = 5, jmp = 6, stp = 7;
    PROC instr   = ( INT op, v )INT: ( 32 * op ) + v;
    OP NOP       = ( INT v     )INT: instr( nop, v );
    OP LDA       = ( INT v     )INT: instr( lda, v );
    OP STA       = ( INT v     )INT: instr( sta, v );
    OP ADD       = ( INT v     )INT: instr( add, v );
    OP SUB       = ( INT v     )INT: instr( sub, v );
    OP BRZ       = ( INT v     )INT: instr( brz, v );
    OP JMP       = ( INT v     )INT: instr( jmp, v );
    OP STP       = ( INT v     )INT: instr( stp, v );
    # executes the program named name                                      #
    PROC execute = ( STRING name, []INT program )VOID:
         BEGIN
            [ 0 : 31 ]INT m; # the computer 32 has bytes of memory         #
            FOR i FROM LWB m TO UPB m DO m[ i ] := 0 OD;
            # "assemble" the program                                       #
            INT m pos := -1;
            FOR i FROM LWB program TO UPB program DO
                m[ m pos +:= 1 ] := program[ i ]
            OD;
            # execute the program #
            BOOL running := TRUE;
            INT  pc      := 0;
            INT  a       := 0;
            WHILE running DO
                INT op      := m[ pc ] OVER 32;
                INT operand := m[ pc ] MOD  32;
                pc +:= 1 MODAB 32;
                IF   op = nop THEN SKIP
                ELIF op = lda THEN a  := m[ operand ]
                ELIF op = sta THEN m[ operand ] := a
                ELIF op = add THEN a +:= m[ operand ] MODAB 256
                ELIF op = sub THEN a -:= m[ operand ] MODAB 256
                ELIF op = brz THEN IF a = 0 THEN pc := operand FI
                ELIF op = jmp THEN pc := operand
                ELSE #    stp #
                    running := FALSE;
                    print( ( " " * ( 12 - ( ( UPB name - LWB name ) + 1 ) ) ) );
                    print( ( name, ": ", whole( a, -3 ), newline ) )
                FI
            OD
         END # execute # ;
    # task test programs (from the Computer Zero website)                  #
    # the unary NOP, LDA, STA, etc. operators are used to construct the    #
    # instructions; as parameterless operators aren't allowed, NOP and STP #
    # must have a dummy parameter                                          #
    execute( "2+2",  ( LDA  3, ADD  4, STP  0,      2,      2 )
           );
    execute( "7*8"
           , ( LDA 12, ADD 10, STA 12, LDA 11, SUB 13, STA 11, BRZ  8, JMP  0
             , LDA 12, STP  0,      8,      7,      0,      1
             )
           );
    execute( "fibonacci"
           , ( LDA 14, STA 15, ADD 13, STA 14, LDA 15, STA 13, LDA 16, SUB 17
             , BRZ 11, STA 16, JMP  0, LDA 14, STP  0,      1,      1,      0
             ,      8,      1
             )
           );
    execute( "linkedList"
           , ( LDA 13, ADD 15, STA  5, ADD 16, STA  7, NOP  0, STA 14, NOP  0
             , BRZ 11, STA 15, JMP  0, LDA 14, STP  0, LDA  0,      0,     28
             ,      1,      0,      0,      0,      6,      0,      2,     26
             ,      5,     20,      3,     30,      1,     22,      4,     24
             )
           );
    execute( "prisoner"
           , ( NOP  0, NOP  0, STP  0,      0, LDA  3, SUB 29, BRZ 18, LDA  3
             , STA 29, BRZ 14, LDA  1, ADD 31, STA  1, JMP  2, LDA  0, ADD 31
             , STA  0, JMP  2, LDA  3, STA 29, LDA  1, ADD 30, ADD  3, STA  1
             , LDA  0, ADD 30, ADD  3, STA  0, JMP  2,      0,      1,      3
             )
           );
    # subtractions yielding negative results                               #
    execute( "0-255", ( LDA  3, SUB  4, STP  0,      0,    255 ) );
    execute( "0-1",   ( LDA  3, SUB  4, STP  0,      0,      1 ) );
    # overflow on addition                                                 #
    execute( "1+255", ( LDA  3, ADD  4, STP  0,      1,    255 ) )
END


# Function that returns a new prime generator
PrimeGen ← {𝕤
  i ← 0  # Counter: index of next prime to be output
  primes ← ↕0
  next ← 2
  Sieve ← { p 𝕊 i‿n:
    E ← {↕∘⌈⌾(((𝕩|-i)+𝕩×⊢)⁼)n-i}       # Indices of multiples of 𝕩
    i + / (1⥊˜n-i) E⊸{0¨⌾(𝕨⊸⊏)𝕩}´ p    # Primes in segment [i,n)
  }
  {𝕤
    { i=≠primes ?                      # Extend if required
      next ↩ ((2⋆24)⊸+ ⌊ ×˜) old←next  # Sieve at most 16M new entries
      primes ∾↩ (primes(⍋↑⊣)√next) Sieve old‿next
    ;@}
    (i+↩1) ⊢ i⊑primes
  }
}
_w_←{𝔽⍟𝔾∘𝔽_𝕣_𝔾∘𝔽⍟𝔾𝕩}  # Looping utility for the session below


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

#define CHUNK_BYTES (32 << 8)
#define CHUNK_SIZE (CHUNK_BYTES << 6)

int field[CHUNK_BYTES];
#define GET(x) (field[(x)>>6] &  1<<((x)>>1&31))
#define SET(x) (field[(x)>>6] |= 1<<((x)>>1&31))

typedef unsigned uint;
typedef struct {
        uint *e;
        uint cap, len;
} uarray;
uarray primes, offset;

void push(uarray *a, uint n)
{
        if (a->len >= a->cap) {
                if (!(a->cap *= 2)) a->cap = 16;
                a->e = realloc(a->e, sizeof(uint) * a->cap);
        }
        a->e[a->len++] = n;
}

uint low;
void init(void)
{
        uint p, q;

        unsigned char f[1<<16];
        memset(f, 0, sizeof(f));
        push(&primes, 2);
        push(&offset, 0);
        for (p = 3; p < 1<<16; p += 2) {
                if (f[p]) continue;
                for (q = p*p; q < 1<<16; q += 2*p) f[q] = 1;
                push(&primes, p);
                push(&offset, q);
        }
        low = 1<<16;
}

void sieve(void)
{
        uint i, p, q, hi, ptop;
        if (!low) init();

        memset(field, 0, sizeof(field));

        hi = low + CHUNK_SIZE;
        ptop = sqrt(hi) * 2 + 1;

        for (i = 1; (p = primes.e[i]*2) < ptop; i++) {
                for (q = offset.e[i] - low; q < CHUNK_SIZE; q += p)
                        SET(q);
                offset.e[i] = q + low;
        }

        for (p = 1; p < CHUNK_SIZE; p += 2)
                if (!GET(p)) push(&primes, low + p);

        low = hi;
}

int main(void)
{
        uint i, p, c;

        while (primes.len < 20) sieve();
        printf("First 20:");
        for (i = 0; i < 20; i++)
                printf(" %u", primes.e[i]);
        putchar('\n');

        while (primes.e[primes.len-1] < 150) sieve();
        printf("Between 100 and 150:");
        for (i = 0; i < primes.len; i++) {
                if ((p = primes.e[i]) >= 100 && p < 150)
                        printf(" %u", primes.e[i]);
        }
        putchar('\n');

        while (primes.e[primes.len-1] < 8000) sieve();
        for (i = c = 0; i < primes.len; i++)
                if ((p = primes.e[i]) >= 7700 && p < 8000) c++;
        printf("%u primes between 7700 and 8000\n", c);

        for (c = 10; c <= 100000000; c *= 10) {
                while (primes.len < c) sieve();
                printf("%uth prime: %u\n", c, primes.e[c-1]);
        }

        return 0;
}


a, b = 1, 0

if (c1 := a == 1) and (c2 := b == 3):
  print('a = 1 and b = 3')
elif c1:
  print('a = 1 and b <> 3')
elif c2:
  print('a <> 1 and b = 3')
else:
  print('a <> 1 and b <> 3')


( --------------------- version #1 --------------------- )

  [  not swap not 1 << |
     ]'[ swap peek do ]              is if2.1  ( b b --> )

  [ if2.1
      [ [ say "true and true"   ]
        [ say "true and false"  ]
        [ say "false and true"  ]
        [ say "false and false" ] ]
    cr ]                             is task.1 ( b b --> )

( --------------------- version #2 --------------------- )

   [ not swap not 1 << |
         dup 0 > iff ]else[ ]else[
     1 - dup 0 > iff ]else[ ]else[
     1 -     0 > iff ]else[ ]else[ ] is if2.2  ( b b --> )

   [ if2.2 [ say "true and true"   ]
      else [ say "true and false"  ]
      else [ say "false and true"  ]
      else [ say "false and false" ]
    cr ]                             is task.2 ( b b --> )

( ------------------------ demo ------------------------ )

true  true  task.1
true  false task.1
false true  task.1
false false task.1
cr
true  true  task.2
true  false task.2
false true  task.2
false false task.2


if2 <- function(condition1, condition2, both_true, first_true, second_true, both_false)
{
  expr <- if(condition1)
  {
    if(condition2) both_true else first_true
  } else if(condition2) second_true else both_false
  eval(expr)
}


///fibonacci(n)
//Returns the nth fibonacci number

var n, numb;
n = argument0;

if (n == 0)
    {
    numb = 0;
    }
else
    {
    var fm2, fm1;
    fm2 = 0;
    fm1 = 1;
    numb = 1;
    repeat(n-1)
        {
        numb = fm2+fm1;
        fm2 = fm1;
        fm1 = numb;
        }
    }

return numb;


F factorial(n)
   V result = 1
   L(i) 2..n
      result *= i
   R result

L(n) 0..5
   print(n‘ ’factorial(n))


OPS=: 'nop lda sta add sub brz jmp stp'

assemble1=: {{
  y=. tolower y
  ins=. {.;:y-.":i.10
  cod=. 8|(;:OPS) i. ins
  val=. {.0".y-.OPS
  if. *cod do.
    assert. 32>val
    val+32*cod
  else.
    assert. 256>val
    val
  end.
}}

assemble=: {{
  if. 0=L. y do.
    delim=. {.((tolower y)-.(":i.10),;OPS),LF
    y=. delim cut y
  end.
  code=. [email protected]> y
  mem=: code (i.#code)} 32#0
}}

exec1=: {{
  'cod val'=. 0 32#:pc{mem
  pc=: 32|pc+1
  select. cod
    case. 0 do.
    case. 1 do. acc=: val{mem
    case. 2 do. mem=: acc val} mem
    case. 3 do. acc=: 256|acc+val{mem
    case. 4 do. acc=: 256|acc-val{mem
    case. 5 do. pc=: 32|pc[^:(*acc) val
    case. 6 do. pc=: 32|val
    case. 7 do. pc=: __
  end.
}}

exec=: {{
  pc=: acc=: 0
  while. 0<:pc do. exec1'' end.
  acc
}}


mutable struct ComputerZero
    ip::Int
    ram::Vector{UInt8}
    accum::UInt8
    isready::Bool
end
function ComputerZero(program)
    memory = zeros(UInt8, 32)
    for i in 1:min(32, length(program))
        memory[i] = program[i]
    end
    return ComputerZero(1, memory, 0, true)
end

NOP(c) = (c.ip = mod1(c.ip + 1, 32))
LDA(c) = (c.accum = c.ram[c.ram[c.ip] & 0b00011111 + 1]; c.ip = mod1(c.ip + 1, 32))
STA(c) = (c.ram[c.ram[c.ip] & 0b00011111 + 1] = c.accum; c.ip = mod1(c.ip + 1, 32))
ADD(c) = (c.accum += c.ram[c.ram[c.ip] & 0b00011111 + 1]; c.ip = mod1(c.ip + 1, 32))
SUB(c) = (c.accum -= c.ram[c.ram[c.ip] & 0b00011111 + 1]; c.ip = mod1(c.ip + 1, 32))
BRZ(c) = (c.ip = (c.accum == 0) ? c.ram[c.ip] & 0b00011111 + 1 : mod1(c.ip + 1, 32))
JMP(c) = (c.ip = c.ram[c.ip] & 0b00011111 + 1)
STP(c) = (println("Program completed with accumulator value $(c.accum).\n"); c.isready = false)

const step = [NOP, LDA, STA, ADD, SUB, BRZ, JMP, STP]
const instructions = ["NOP", "LDA", "STA", "ADD", "SUB", "BRZ", "JMP", "STP"]
const assemblywords = Dict(s => i - 1 for (i, s) in pairs(instructions))

function run(compzero::ComputerZero, debug = false)
    while compzero.isready
        instruction = compzero.ram[compzero.ip]
        opcode, operand =  instruction >> 5 + 1, instruction & 0b00011111
        debug && println("op $(instructions[opcode]), operand $operand")
        step[opcode](compzero)
    end
    return compzero.accum
end
run(program::Vector, debug = false) = run(ComputerZero(program), debug)

function compile(text::String)
    bin, lines = UInt8[], 0
    for line in strip.(split(text, "\n"))
        lines += 1
        if isempty(line)
           push!(bin, 0)
        elseif (m = match(r"(\w\w\w)\s+(\d\d?)", line)) != nothing
            push!(bin, UInt8((assemblywords[m.captures[1]] << 5) | parse(UInt8, m.captures[2])))
        elseif (m = match(r"(\w\w\w)", line)) != nothing
            push!(bin, UInt8(assemblywords[m.match] << 5))
        elseif (m = match(r"\d\d?", line)) != nothing
                push!(bin, parse(UInt8, m.match))
        else
            error("Compilation error at line $lines: error parsing <$line>")
        end
    end
    println("Compiled $lines lines.")
    return bin
end

const testprograms = [
    """
        LDA 3
        ADD 4
        STP
        2
        2
    """,
    """
        LDA 12
        ADD 10
        STA 12
        LDA 11
        SUB 13
        STA 11
        BRZ 8
        JMP 0
        LDA 12
        STP
        8
        7
        0
        1
    """,
    """
        LDA 14
        STA 15
        ADD 13
        STA 14
        LDA 15
        STA 13
        LDA 16
        SUB 17
        BRZ 11
        STA 16
        JMP 0
        LDA 14
        STP
        1
        1
        0
        8
        1
    """,
    """
        LDA 13
        ADD 15
        STA 5
        ADD 16
        STA 7
        NOP
        STA 14
        NOP
        BRZ 11
        STA 15
        JMP 0
        LDA 14
        STP
        LDA 0
        0
        28
        1

        6
        0
        2
        26
        5
        20
        3
        30
        1
        22
        4
        24
    """,
    """
        0
        0
        STP
        NOP
        LDA 3
        SUB 29
        BRZ 18
        LDA 3
        STA 29
        BRZ 14
        LDA 1
        ADD 31
        STA 1
        JMP 2
        LDA 0
        ADD 31
        STA 0
        JMP 2
        LDA 3
        STA 29
        LDA 0
        ADD 30
        ADD 3
        STA 0
        LDA 1
        ADD 30
        ADD 3
        STA 1
        JMP 2
        0
        1
        3
    """
]

for t in testprograms
    run(compile(t))
end


#include <iostream>
#include <cstdint>
#include <queue>
#include <utility>
#include <vector>
#include <limits>

template<typename integer>
class prime_generator {
public:
    integer next_prime();
    integer count() const {
        return count_;
    }
private:
    struct queue_item {
        queue_item(integer prime, integer multiple, unsigned int wheel_index) :
            prime_(prime), multiple_(multiple), wheel_index_(wheel_index) {}
        integer prime_;
        integer multiple_;
        unsigned int wheel_index_;
    };
    struct cmp {
        bool operator()(const queue_item& a, const queue_item& b) const {
            return a.multiple_ > b.multiple_;
        }
    };
    static integer wheel_next(unsigned int& index) {
        integer offset = wheel_[index];
        ++index;
        if (index == std::size(wheel_))
            index = 0;
        return offset;
    }
    typedef std::priority_queue<queue_item, std::vector<queue_item>, cmp> queue;
    integer next_ = 11;
    integer count_ = 0;
    queue queue_;
    unsigned int wheel_index_ = 0;
    static const unsigned int wheel_[];
    static const integer primes_[];
};

template<typename integer>
const unsigned int prime_generator<integer>::wheel_[] = {
    2, 4, 2, 4, 6, 2, 6, 4, 2, 4, 6, 6, 2, 6, 4, 2,
    6, 4, 6, 8, 4, 2, 4, 2, 4, 8, 6, 4, 6, 2, 4, 6,
    2, 6, 6, 4, 2, 4, 6, 2, 6, 4, 2, 4, 2, 10, 2, 10
};

template<typename integer>
const integer prime_generator<integer>::primes_[] = {
    2, 3, 5, 7
};

template<typename integer>
integer prime_generator<integer>::next_prime() {
    if (count_ < std::size(primes_))
        return primes_[count_++];
    integer n = next_;
    integer prev = 0;
    while (!queue_.empty()) {
        queue_item item = queue_.top();
        if (prev != 0 && prev != item.multiple_)
            n += wheel_next(wheel_index_);
        if (item.multiple_ > n)
            break;
        else if (item.multiple_ == n) {
            queue_.pop();
            queue_item new_item(item);
            new_item.multiple_ += new_item.prime_ * wheel_next(new_item.wheel_index_);
            queue_.push(new_item);
        }
        else
            throw std::overflow_error("prime_generator: overflow!");
        prev = item.multiple_;
    }
    if (std::numeric_limits<integer>::max()/n > n)
        queue_.emplace(n, n * n, wheel_index_);
    next_ = n + wheel_next(wheel_index_);
    ++count_;
    return n;
}

int main() {
    typedef uint32_t integer;
    prime_generator<integer> pgen;
    std::cout << "First 20 primes:\n";
    for (int i = 0; i < 20; ++i) {
        integer p = pgen.next_prime();
        if (i != 0)
            std::cout << ", ";
        std::cout << p;
    }
    std::cout << "\nPrimes between 100 and 150:\n";
    for (int n = 0; ; ) {
        integer p = pgen.next_prime();
        if (p > 150)
            break;
        if (p >= 100) {
            if (n != 0)
                std::cout << ", ";
            std::cout << p;
            ++n;
        }
    }
    int count = 0;
    for (;;) {
        integer p = pgen.next_prime();
        if (p > 8000)
            break;
        if (p >= 7700)
            ++count;
    }
    std::cout << "\nNumber of primes between 7700 and 8000: " << count << '\n';

    for (integer n = 10000; n <= 10000000; n *= 10) {
        integer prime;
        while (pgen.count() != n)
            prime = pgen.next_prime();
        std::cout << n << "th prime: " << prime << '\n';
    }
    return 0;
}


#lang racket
;; define a new syntax
(define-syntax-rule
  ;; this is the new syntax we want, in sexpr syntax:
  (if2 condition1isTrue condition2isTrue
       bothConditionsAreTrue
       firstConditionIsTrue
       secondConditionIsTrue
       noConditionIsTrue)
  ;; and this is the syntax that implements it:
  (if condition1isTrue
    (if condition2isTrue
      bothConditionsAreTrue
      firstConditionIsTrue)
    (if condition2isTrue
      secondConditionIsTrue
      noConditionIsTrue)))
;; ... and that's all you need -- it now works:
(define (try x y)
  (displayln (if2 (< x 10) (< y 10)
                  "Both small"
                  "First is small"
                  "Second is small"
                  "Neither is small")))
(try 1 1)   ; Both small
(try 1 10)  ; First is small
(try 10 1)  ; Second is small
(try 10 10) ; Neither is small


my &if2  = -> \a, \b, &x { my @*IF2 = ?a,?b; x }

my &if-both    = -> &x { x if @*IF2 eq (True,True)  }
my &if-first   = -> &x { x if @*IF2 eq (True,False) }
my &if-second  = -> &x { x if @*IF2 eq (False,True) }
my &if-neither = -> &x { x if @*IF2 eq (False,False)}

sub test ($a,$b) {
    $_ = "G";          # Demo correct scoping of topic.
    my $got = "o";     # Demo correct scoping of lexicals.
    my $*got = "t";    # Demo correct scoping of dynamics.

    if2 $a, $b, {
        if-both { say "$_$got$*got both" }
        if-first { say "$_$got$*got first" }
        if-second { say "$_$got$*got second" }
        if-neither { say "$_$got$*got neither" }
    }
}

say test |$_ for 1,0 X 1,0;


func fib(a int) int {
  if a < 2 {
    return a
  }
  return fib(a - 1) + fib(a - 2)
}


F my_pow(base, exp) -> Float
   I exp < 0
      R 1 / my_pow(base, -exp)
   I exp == 0
      R 1
   V ans = base
   L 0 .< exp - 1
      ans *= base
   R ans

print(‘2  ^ 3   = ’my_pow(2, 3))
print(‘1  ^ -10 = ’my_pow(1, -10))
print(‘-1 ^ -3  = ’my_pow(-1, -3))
print()
print(‘2.0 ^ -3 = ’my_pow(2.0, -3))
print(‘1.5 ^ 0  = ’my_pow(1.5, 0))
print(‘4.5 ^ 2  = ’my_pow(4.5, 2))


FACTO    CSECT
         USING  FACTO,R13
SAVEAREA B      STM-SAVEAREA(R15)
         DC     17F'0'
         DC     CL8'FACTO'
STM      STM    R14,R12,12(R13)
         ST     R13,4(R15)
         ST     R15,8(R13)
         LR     R13,R15         base register and savearea pointer
         ZAP    N,=P'1'         n=1
LOOPN    CP     N,NN            if n>nn
         BH     ENDLOOPN        then goto endloop
         LA     R1,PARMLIST
         L      R15,=A(FACT)
         BALR   R14,R15         call fact(n)
	 ZAP    F,0(L'R,R1)     f=fact(n)
DUMP     EQU    *
	 MVC    S,MASK
	 ED     S,N
         MVC    WTOBUF+5(2),S+30
	 MVC    S,MASK
	 ED     S,F
         MVC    WTOBUF+9(32),S
         WTO    MF=(E,WTOMSG)
	 AP     N,=P'1'         n=n+1
	 B      LOOPN
ENDLOOPN EQU    *
RETURN   EQU    *
         L      R13,4(0,R13)
         LM     R14,R12,12(R13)
         XR     R15,R15
         BR     R14
FACT     EQU    *               function FACT(l)
         L      R2,0(R1)
         L      R3,12(R2)
         ZAP    L,0(L'N,R2)     l=n
         ZAP    R,=P'1'         r=1
         ZAP    I,=P'2'         i=2
LOOP     CP     I,L             if i>l
         BH     ENDLOOP         then goto endloop
	 MP     R,I             r=r*i
	 AP     I,=P'1'         i=i+1
	 B      LOOP
ENDLOOP  EQU    *
         LA     R1,R            return r
         BR     R14             end function FACT
         DS     0D
NN       DC     PL16'29'
N        DS     PL16
F        DS     PL16
C        DS     CL16
II       DS     PL16
PARMLIST DC     A(N)
S        DS     CL33
MASK     DC     X'40',29X'20',X'212060'  CL33
WTOMSG   DS     0F
         DC     H'80',XL2'0000'
WTOBUF   DC     CL80'FACT(..)=................................ '
L        DS     PL16
R        DS     PL16
I        DS     PL16
         LTORG
         YREGS
         END    FACTO


with javascript_semantics
constant NOP = 0b000_00000, -- no operation
         LDA = 0b001_00000, -- load accumulator, a := memory [xxxxx]
         STA = 0b010_00000, -- store accumulator, memory [xxxxx] := a
         ADD = 0b011_00000, -- add, a := a + memory [xxxxx]
         SUB = 0b100_00000, -- subtract, a := a – memory [xxxxx]
         BRZ = 0b101_00000, -- branch on zero, if a = 0 then goto xxxxx
         JMP = 0b110_00000, -- jump, goto xxxxx
         STP = 0b111_00000, -- stop
         OP  = 0b111_00000, -- operator mask
         ARG = 0b000_11111  -- memory location (0 based)

procedure execute(string name, sequence program)
    sequence memory = deep_copy(program)
    integer pc = 1, a = 0
    while true do
        integer ppc = memory[pc],
                op = and_bitsu(ppc,OP),
                arg = and_bits(ppc,ARG)+1
        pc += 1
        switch op do
            case NOP:   break
            case LDA:   a = memory[arg]
            case STA:   memory[arg] = a
            case ADD:   a = and_bitsu(a+memory[arg],#FF)
            case SUB:   a = and_bitsu(a-memory[arg],#FF)
            case BRZ:   if a=0 then pc = arg end if
            case JMP:   pc = arg
            case STP:   printf(1,"%12s: %3d\n",{name,a})
                        return
        end switch
    end while
end procedure

execute("2+2",{LDA+3, ADD+4, STP, 2,2})
execute("7*8",{LDA+12, ADD+10, STA+12, LDA+11, SUB+13, STA+11, BRZ+8, JMP+0,
               LDA+12, STP, 8,7,0,1})
execute("fibonacci",{LDA+14, STA+15, ADD+13, STA+14, LDA+15, STA+13, LDA+16,
                     SUB+17, BRZ+11, STA+16, JMP+0,  LDA+14, STP, 1,1,0,8,1})
execute("linkedList",{LDA+13, ADD+15, STA+5, ADD+16, STA+7, NOP, STA+14, NOP,
                      BRZ+11, STA+15, JMP+0, LDA+14, STP, LDA+0, 0,28,1,0,0,
                      0,6,0,2,26,5,20,3,30,1,22,4,24})
execute("prisoner",{NOP, NOP, STP, 0, LDA+3, SUB+29, BRZ+18, LDA+3, STA+29,
                    BRZ+14, LDA+1, ADD+31, STA+1, JMP+2, LDA+0, ADD+31, STA+0,
                    JMP+2, LDA+3, STA+29, LDA+1, ADD+30, ADD+3, STA+1, LDA+0,
                    ADD+30, ADD+3, STA+0, JMP+2, 0, 1, 3})
-- subtractions yielding negative results
execute("0-255",{LDA+3,SUB+4,STP, 0,255})
execute("0-1",{LDA+3, SUB+4, STP, 0,1})
-- overflow on addition
execute("1+255",{LDA+3, ADD+4, STP, 1, 255})


ns test-project-intellij.core
  (:gen-class)
  (:require [clojure.string :as string]))

(def primes
" The following routine produces a infinite sequence of primes
  (i.e. can be infinite since the evaluation is lazy in that it
  only produces values as needed).  The method is from clojure primes.clj library
  which produces primes based upon O'Neill's paper:
  'The Genuine Sieve of Eratosthenes'.

   Produces primes based upon trial division on previously found primes up to
   (sqrt number), and uses 'wheel' to avoid
   testing numbers which are divisors of 2, 3, 5, or 7.
   A full explanation of the method is available at:
   [https://github.com/stuarthalloway/programming-clojure/pull/12] "

  (concat
    [2 3 5 7]
    (lazy-seq
      (let [primes-from   ; generates primes by only checking if primes
                          ; numbers which are not divisible by 2, 3, 5, or 7
            (fn primes-from [n [f & r]]
              (if (some #(zero? (rem n %))
                        (take-while #(<= (* % %) n) primes))
                (recur (+ n f) r)
                (lazy-seq (cons n (primes-from (+ n f) r)))))

            ; wheel provides offsets from previous number to insure we are not landing on a divisor of 2, 3, 5, 7
            wheel (cycle [2 4 2 4 6 2 6 4 2 4 6 6 2 6  4  2
                          6 4 6 8 4 2 4 2 4 8 6 4 6 2  4  6
                          2 6 6 4 2 4 6 2 6 4 2 4 2 10 2 10])]
        (primes-from 11 wheel)))))

(defn between [lo hi]
  "Primes between lo and hi value "
  (->> (take-while #(<= % hi) primes)
       (filter #(>= % lo))
       ))

(println "First twenty:" (take 20 primes))

(println "Between 100 and 150:" (between 100 150))

(println "Number between 7,7700 and 8,000:" (count (between 7700 8000)))

(println "10,000th prime:" (nth primes (dec 10000)))    ; decrement by one since nth starts counting from 0

}


if2(  some-expression-that-results-in-a-boolean-value,   some-other-expression-that-results-in-a-boolean-value)

                /*this part is a REXX comment*/         /*could be a DO structure.*/
    select      /*↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓*/         /*↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓*/

    when if.11  /*{condition 1 & 2  are true}*/   then    perform-a-REXX-statement
    when if.10  /*{condition 1       is true}*/   then       "    "   "      "
    when if.01  /*{condition 2       is true}*/   then       "    "   "      "
    when if.00  /*{no condition      is true}*/   then       "    "   "      "

    end

/*an example of a  DO  structure for the first clause: */

    when if.11  /*{condition 1 & 2  are true}*/   then do;  x=12;  y=length(y);  end


# Project : Extend your language

see "a = 1, b = 1 => "
test(1, 1)
see "a = 1, b = 0 => "
test(1, 0)
see "a = 0, b = 1 => "
test(0, 1)
see "a = 0, b = 0 => "
test(0, 0)
see nl

func test(a,b)
       if a > 0 and b > 0
          see "both positive"
       but a > 0
           see "first positive"
       but b > 0
           see "second positive"
       but a < 1 and b < 1
           see "neither positive"
       ok
       see nl


# Define a class which always returns itself for everything
class HopelesslyEgocentric
  def method_missing(what, *args) self end
end

def if2(cond1, cond2)
  if cond1 and cond2
    yield
    HopelesslyEgocentric.new
  elsif cond1
    Class.new(HopelesslyEgocentric) do
      def else1; yield; HopelesslyEgocentric.new end
    end.new
  elsif cond2
    Class.new(HopelesslyEgocentric) do
      def else2; yield; HopelesslyEgocentric.new end
    end.new
  else
    Class.new(HopelesslyEgocentric) do
      def neither; yield end
    end.new
  end
end


def rFib
rFib = {
    it == 0   ? 0
    : it == 1 ? 1
    : it > 1  ? rFib(it-1) + rFib(it-2)
    /*it < 0*/: rFib(it+2) - rFib(it+1)

}


ExponentUnsigned:
	;input: D0.W = BASE
	;	D1.W = EXPONENT
	;	OUTPUTS TO D0
	;	NO OVERFLOW PROTECTION - USE AT YOUR OWN RISK!
	;HIGH WORDS OF D0 AND D1 ARE CLEARED.
	;clobbers D1

	MOVE.L D2,-(SP)

		;using DBRAs lets us simultaneously subtract and compare
		DBRA D1,.test_if_one
		MOVEQ.L #1,D0		;executes only if D1 was 0 to start with
.test_if_one:
		DBRA D1,.go
		bra .done		;executes only if D1 was 1 to start with
.go:
		;else, multiply D0 by its ORIGINAL self repeatedly.
		MOVE.L D0,D2
.loop:
		MULU D0,D2
		DBRA D1,.loop

		MOVE.L D2,D0
.done:
	MOVE.L (SP)+,D2
	RTS


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

INT FUNC PowerI(INT base,exp)
  INT res,i

  IF exp<0 THEN Break() FI

  res=1
  FOR i=1 TO exp
  DO
    res==*base
  OD
RETURN (res)

PROC PowerR(REAL POINTER base INT exp
            REAL POINTER res)
  INT i
  REAL tmp

  IF exp<0 THEN Break() FI

  IntToReal(1,res)
  FOR i=1 TO exp
  DO
    RealMult(res,base,tmp)
    RealAssign(tmp,res)
  OD
RETURN

PROC TestI(INT base,exp)
  INT res

  res=PowerI(base,exp)
  PrintF("%I^%I=%I%E",base,exp,res)
RETURN

PROC TestR(REAL POINTER base INT exp)
  REAL res

  PowerR(base,exp,res)
  PrintR(base) PrintF("^%I=",exp)
  PrintRE(res)
RETURN

PROC Main()
  REAL base

  Put(125) PutE() ;clear screen

  TestI(27,3)
  TestI(2,12)
  TestI(-3,9)
  TestI(1,1000)
  TestI(20000,0)

  ValR("3.141592654",base)
  TestR(base,10)
  ValR("-1.11",base)
  TestR(base,99)
  ValR("0.123456789",base)
  TestR(base,1)
  ValR("987654.321",base)
  TestR(base,0)
RETURN


package Integer_Exponentiation is
   --  int^int
   procedure Exponentiate (Argument : in     Integer;
                           Exponent : in     Natural;
                           Result   :    out Integer);
   function "**" (Left  : Integer;
                  Right : Natural) return Integer;

   --  real^int
   procedure Exponentiate (Argument : in     Float;
                           Exponent : in     Integer;
                           Result   :    out Float);
   function "**" (Left  : Float;
                  Right : Integer) return Float;
end Integer_Exponentiation;


Factorial:
;input: D0.W: number you wish to get the factorial of.
;output: D0.L
	CMP.W #0,D0
	BEQ .isZero
	CMP.W #1,D0
	BEQ .isOne
	MOVEM.L D4-D5,-(SP)
		MOVE.W D0,D4
		MOVE.W D0,D5
		SUBQ.W #2,D5		;D2 = LOOP COUNTER.
		;Since DBRA stops at FFFF we can't use it as our multiplier.
		;If we did, we'd always return 0!
.loop:
		SUBQ.L #1,D4
                      MOVE.L D1,-(SP)
		      MOVE.L D4,D1
		      JSR MULU_48		;multiplies D0.L by D1.W
		      EXG D0,D1                 ;output is in D1 so we need to put it in D0
                MOVE.L (SP)+,D1
		DBRA D5,.loop
	MOVEM.L (SP)+,D4-D5
	RTS
.isZero:
.isOne:
	MOVEQ #1,D0
	RTS
MULU_48:
        ;"48-BIT" MULTIPLICATION.
	;OUTPUTS HIGH LONG IN D0, LOW LONG IN D1
	;INPUT: D0.L, D1.W = FACTORS
	MOVEM.L D2-D7,-(SP)
	SWAP D1
	CLR.W D1
	SWAP D1				;CLEAR THE TOP WORD OF D1.

	MOVE.L D1,D2
	EXG D0,D1			;D1 IS OUR BASE VALUE, WE'LL USE BIT SHIFTS TO REPEATEDLY MULTIPLY.
	MOVEQ #0,D0			;CLEAR UPPER LONG OF PRODUCT
	MOVE.L D1,D3		;BACKUP OF "D1" (WHICH USED TO BE D0)

	;EXAMPLE: $40000000*$225 = ($40000000 << 9) + ($40000000 << 5) + ($40000000 << 2) + $40000000
	;FACTOR OUT AS MANY POWERS OF 2 AS POSSIBLE.

	MOVEQ #0,D0
	LSR.L #1,D2
	BCS .wasOdd			;if odd, leave D1 alone. Otherwise, clear it. This is our +1 for an odd second operand.
		MOVEQ #0,D1
.wasOdd:
		MOVEQ #31-1,D6		;30 BITS TO CHECK
		MOVEQ #1-1,D7		;START AT BIT 1, MINUS 1 IS FOR DBRA CORRECTION FACTOR
.shiftloop:
		LSR.L #1,D2
		BCC .noShift
		MOVE.W D7,-(SP)
			MOVEQ #0,D4
			MOVE.L D3,D5
.innershiftloop:
			ANDI #%00001111,CCR       ;clear extend flag
			ROXL.L D5
			ROXL.L D4
			DBRA D7,.innershiftloop
			ANDI #%00001111,CCR
			ADDX.L D5,D1
			ADDX.L D4,D0
		MOVE.W (SP)+,D7
.noShift:
	addq.l #1,d7
	dbra d6,.shiftloop
	MOVEM.L (SP)+,D2-D7
	RTS


"""Computer/zero Assembly emulator. Requires Python >= 3.7"""
from typing import Dict
from typing import Iterable
from typing import List
from typing import NamedTuple
from typing import Optional
from typing import Tuple
from typing import Union

NOP = 0b000
LDA = 0b001
STA = 0b010
ADD = 0b011
SUB = 0b100
BRZ = 0b101
JMP = 0b110
STP = 0b111

OPCODES = {
    "NOP": NOP,
    "LDA": LDA,
    "STA": STA,
    "ADD": ADD,
    "SUB": SUB,
    "BRZ": BRZ,
    "JMP": JMP,
    "STP": STP,
}

class Instruction(NamedTuple):
    opcode: Optional[str]
    argument: Union[str, int, None]

Bytecode = Iterable[int]
Instructions = List[Instruction]
Labels = Dict[str, int]

def parse(assembly: str) -> Tuple[Instructions, Labels]:
    instructions: Instructions = []
    labels: Dict[str, int] = {}
    linenum: int = 0
    lines = [line.strip() for line in assembly.split("\n")]

    for line in lines:
        # Discard comments
        if ";" in line:
            line = line.split(";", 1)[0]

        # Parse label
        if ":" in line:
            label, line = line.split(":", 1)
            labels[label] = linenum

        # Parse opcode and argument
        instruction = line.strip().split()
        if len(instruction) == 1:
            if instruction[0] in OPCODES:
                # Opcode without argument
                opcode: Optional[str] = instruction[0]
                argument: Union[str, int, None] = None
            elif instruction[0].isnumeric():
                # Data, without opcode
                opcode = None
                argument = int(instruction[0])
            else:
                # Unexpected
                raise Exception(f"unknown instruction '{line}', {linenum}")
        elif len(instruction) == 2:
            # Opcode and argument
            opcode, argument = instruction

            if opcode not in OPCODES:
                raise Exception(f"unknown instruction '{line}', {linenum}")

            if argument.isnumeric():
                argument = int(argument)
            else:
                # Argument is a label
                argument = argument
        elif not instruction:
            # blank line
            opcode = "NOP"
            argument = None
        else:
            raise Exception(f"unknown instruction '{line}', {linenum}")

        instructions.append(Instruction(opcode, argument))
        linenum += 1

    return instructions, labels

def compile(instructions: Instructions, labels: Labels) -> Bytecode:
    for instruction in instructions:
        if isinstance(instruction.argument, str):
            argument = labels[instruction.argument]
        elif isinstance(instruction.argument, int):
            argument = instruction.argument
        else:
            argument = 0

        if instruction.opcode:
            yield OPCODES[instruction.opcode] << 5 | argument
        else:
            yield argument

def run(bytecode: bytes) -> int:
    accumulator = 0
    program_counter = 0
    memory = list(bytecode)[:32] + [0 for _ in range(32 - len(bytecode))]

    while program_counter < 32:
        operation = memory[program_counter] >> 5
        argument = memory[program_counter] & 0b11111
        program_counter += 1

        if operation == NOP:
            continue
        elif operation == LDA:
            accumulator = memory[argument]
        elif operation == STA:
            memory[argument] = accumulator
        elif operation == ADD:
            accumulator = (accumulator + memory[argument]) % 256
        elif operation == SUB:
            accumulator = (accumulator - memory[argument]) % 256
        elif operation == BRZ:
            if accumulator == 0:
                program_counter = argument
        elif operation == JMP:
            program_counter = argument
        elif operation == STP:
            break
        else:
            raise Exception(":( " + str(operation))

    return accumulator

SAMPLES = [
    """\
            LDA   x
            ADD   y       ; accumulator = x + y
            STP
    x:            2
    y:            2
    """,
    """\
    loop:   LDA   prodt
            ADD   x
            STA   prodt
            LDA   y
            SUB   one
            STA   y
            BRZ   done
            JMP   loop
    done:   LDA   prodt   ; to display it
            STP
    x:            8
    y:            7
    prodt:        0
    one:          1
    """,
    """\
    loop:   LDA   n
            STA   temp
            ADD   m
            STA   n
            LDA   temp
            STA   m
            LDA   count
            SUB   one
            BRZ   done
            STA   count
            JMP   loop
    done:   LDA   n       ; to display it
            STP
    m:            1
    n:            1
    temp:         0
    count:        8       ; valid range: 1-11
    one:          1
    """,
    """\
    start:  LDA   load
            ADD   car     ; head of list
            STA   ldcar
            ADD   one
            STA   ldcdr   ; next CONS cell
    ldcar:  NOP
            STA   value
    ldcdr:  NOP
            BRZ   done    ; 0 stands for NIL
            STA   car
            JMP   start
    done:   LDA   value   ; CAR of last CONS
            STP
    load:   LDA   0
    value:        0
    car:          28
    one:          1
                        ; order of CONS cells
                        ; in memory
                        ; does not matter
                6
                0       ; 0 stands for NIL
                2       ; (CADR ls)
                26      ; (CDDR ls) -- etc.
                5
                20
                3
                30
                1       ; value of (CAR ls)
                22      ; points to (CDR ls)
                4
                24
    """,
    """\
    p:            0       ; NOP in first round
    c:            0
    start:  STP           ; wait for p's move
    pmove:  NOP
            LDA   pmove
            SUB   cmove
            BRZ   same
            LDA   pmove
            STA   cmove   ; tit for tat
            BRZ   cdeft
            LDA   c       ; p defected, c did not
            ADD   three
            STA   c
            JMP   start
    cdeft:  LDA   p
            ADD   three
            STA   p
            JMP   start
    same:   LDA   pmove
            STA   cmove   ; tit for tat
            LDA   p
            ADD   one
            ADD   pmove
            STA   p
            LDA   c
            ADD   one
            ADD   pmove
            STA   c
            JMP   start
    cmove:        0       ; co-operate initially
    one:          1
    three:        3
    """,
    """\
    LDA  3
    SUB  4
    STP  0
         0
         255
    """,
    """\
    LDA  3
    SUB  4
    STP  0
         0
         1
    """,
    """\
    LDA  3
    ADD  4
    STP  0
         1
         255
    """,
]

def main() -> None:
    for sample in SAMPLES:
        instructions, labels = parse(sample.strip())
        bytecode = bytes(compile(instructions, labels))
        # print(bytecode)
        print(run(bytecode))

if __name__ == "__main__":
    main()


primes = () ->
    yield 2
    yield 3

    sieve = ([] for i in [1..3])
    sieve[0].push 3
    [r, s] = [3, 9]
    pos = 1
    n = 5
    loop
        isPrime = true
        if sieve[pos].length > 0  # this entry has a list of factors
            isPrime = false
            sieve[(pos + m) % sieve.length].push m for m in sieve[pos]
            sieve[pos] = []

        if n is s  # n is the next square
            if isPrime
                isPrime = false  # r divides n, so not actually prime
                sieve[(pos + r) % sieve.length].push r  # however, r is prime
            r += 2
            s = r*r

        yield n if isPrime
        n += 2
        pos += 1
        if pos is sieve.length
            sieve.push []  # array size must exceed largest prime found
            sieve.push []  # adding two entries keeps size = O(sqrt n)
            pos = 0

    undefined  # prevent CoffeeScript from aggregating values

module.exports = {
    primes
}


#![allow(unused_variables)]
macro_rules! if2 {
    ($cond1: expr, $cond2: expr
        => $both:expr
        => $first: expr
        => $second:expr
        => $none:expr)
    => {
        match ($cond1, $cond2) {
            (true, true) => $both,
            (true, _   ) => $first,
            (_   , true) => $second,
            _            => $none
        }
    }
}

fn main() {
    let i = 1;
    let j = 2;
    if2!(i > j, i + j >= 3
        => {
            // code blocks and statements can go here also
            let k = i + j;
            println!("both were true")
        }
        => println!("the first was true")
        => println!("the second was true")
        => println!("neither were true")
    )
}


scala> def if2[A](x: => Boolean)(y: => Boolean)(xyt: => A) = new {
     |   def else1(xt: => A) = new {
     |     def else2(yt: => A) = new {
     |       def orElse(nt: => A) = {
     |         if(x) {
     |           if(y) xyt else xt
     |         } else if(y) {
     |           yt
     |         } else {
     |           nt
     |         }
     |       }
     |     }
     |   }
     | }
if2: [A](x: => Boolean)(y: => Boolean)(xyt: => A)java.lang.Object{def else1(xt: => A): java.lang.Object{def else2(yt: =>
 A): java.lang.Object{def orElse(nt: => A): A}}}


#include "harbour.ch"
Function fibb(a,b,n)
return(if(--n>0,fibb(b,a+b,n),a))


main:(
  INT two=2, thirty=30; # test constants #
  PROC VOID undefined;

# First implement exponentiation using a rather slow but sure FOR loop #
  PROC int pow = (INT base, exponent)INT: ( # PROC cannot be over loaded #
    IF exponent<0 THEN undefined FI;
    INT out:=( exponent=0 | 1 | base );
    FROM 2 TO exponent DO out*:=base OD;
    out
  );

  printf(($" One Gibi-unit is: int pow("g(0)","g(0)")="g(0)" - (cost: "g(0)
           " INT multiplications)"l$,two, thirty, int pow(two,thirty),thirty-1));

# implement exponentiation using a faster binary technique and WHILE LOOP #
  OP ** = (INT base, exponent)INT: (
    BITS binary exponent:=BIN exponent ; # do exponent arithmetic in binary #
    INT out := IF bits width ELEM binary exponent THEN base ELSE 1 FI;
    INT sq := IF exponent < 0 THEN undefined; ~ ELSE base FI;

    WHILE
      binary exponent := binary exponent SHR 1;
      binary exponent /= BIN 0
    DO
      sq *:= sq;
      IF bits width ELEM binary exponent THEN out *:= sq FI
    OD;
    out
  );

  printf(($" One Gibi-unit is: "g(0)"**"g(0)"="g(0)" - (cost: "g(0)
           " INT multiplications)"l$,two, thirty, two ** thirty,8));

  OP ** = (REAL in base, INT in exponent)REAL: ( # ** INT Operator can be overloaded #
    REAL base := ( in exponent<0 | 1/in base | in base);
    INT exponent := ABS in exponent;
    BITS binary exponent:=BIN exponent ; # do exponent arithmetic in binary #
    REAL out := IF bits width ELEM binary exponent THEN base ELSE 1 FI;
    REAL sq := base;

    WHILE
      binary exponent := binary exponent SHR 1;
      binary exponent /= BIN 0
    DO
      sq *:= sq;
      IF bits width ELEM binary exponent THEN out *:= sq FI
    OD;
    out
  );

  printf(($" One Gibi-unit is: "g(0,1)"**"g(0)"="g(0,1)" - (cost: "g(0)
           " REAL multiplications)"l$, 2.0, thirty, 2.0 ** thirty,8));

  OP ** = (REAL base, REAL exponent)REAL: ( # ** REAL Operator can be overloaded #
    exp(ln(base)*exponent)
  );

  printf(($" One Gibi-unit is: "g(0,1)"**"g(0,1)"="g(0,1)" - (cost: "
           "depends on precision)"l$, 2.0, 30.0, 2.0 ** 30.0))
)


/* ARM assembly AARCH64 Raspberry PI 3B */
/*  program factorial64.s   */

/*******************************************/
/* Constantes file                         */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"

/*********************************/
/* Initialized data              */
/*********************************/
.data
szMessLargeNumber:   .asciz "Number N to large. \n"
szMessNegNumber:     .asciz "Number N is negative. \n"

szMessResult:        .asciz "Resultat =  @ \n"      // message result

/*********************************/
/* UnInitialized data            */
/*********************************/
.bss
sZoneConv:         .skip 24
/*********************************/
/*  code section                 */
/*********************************/
.text
.global main
main:                      // entry of program

    mov x0,#-5
    bl factorial
    mov x0,#10
    bl factorial
    mov x0,#20
    bl factorial
    mov x0,#30
    bl factorial

100:                      // standard end of the program
    mov x0,0              // return code
    mov x8,EXIT           // request to exit program
    svc 0                 // perform the system call

/********************************************/
/*     calculation                         */
/********************************************/
/* x0 contains number N */
factorial:
    stp x1,lr,[sp,-16]!            // save  registers
    cmp x0,#0
    blt 99f
    beq 100f
    cmp x0,#1
    beq 100f
    bl calFactorial
    cmp x0,#-1                      // overflow ?
    beq 98f
    ldr x1,qAdrsZoneConv
    bl conversion10
    ldr x0,qAdrszMessResult
    ldr x1,qAdrsZoneConv
    bl strInsertAtCharInc          // insert result at @ character
    bl affichageMess               // display message
    b 100f

98:                               // display error message
    ldr x0,qAdrszMessLargeNumber
    bl affichageMess
    b 100f
99:                               // display error message
    ldr x0,qAdrszMessNegNumber
    bl affichageMess

100:
    ldp x1,lr,[sp],16             // restaur  2 registers
    ret                           // return to address lr x30

qAdrszMessNegNumber:       .quad szMessNegNumber
qAdrszMessLargeNumber:     .quad szMessLargeNumber
qAdrsZoneConv:             .quad sZoneConv
qAdrszMessResult:          .quad szMessResult
/******************************************************************/
/*     calculation                         */
/******************************************************************/
/* x0 contains the number N */
calFactorial:
    cmp x0,1                // N = 1 ?
    beq 100f                // yes -> return
    stp x20,lr,[sp,-16]!    // save  registers
    mov x20,x0              // save N in x20
    sub x0,x0,1             // call function with N - 1
    bl calFactorial
    cmp x0,-1               // error overflow ?
    beq 99f                 // yes -> return
    mul x10,x20,x0          // multiply result by N
    umulh x11,x20,x0        // x11 is the hi rd  if <> 0 overflow
    cmp x11,0
    mov x11,-1              // if overflow  -1 -> x0
    csel x0,x10,x11,eq      // else x0 = x10

99:
    ldp x20,lr,[sp],16      // restaur  2 registers
100:
    ret                     // return to address lr x30
/********************************************************/
/*        File Include fonctions                        */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"


var NOP = 0
var LDA = 1
var STA = 2
var ADD = 3
var SUB = 4
var BRZ = 5
var JMP = 6
var STP = 7

var ops = {"NOP": NOP, "LDA": LDA, "STA": STA, "ADD": ADD,
           "SUB": SUB, "BRZ": BRZ, "JMP": JMP, "STP": STP}

var load = Fn.new { |prog|
    var mem = List.filled(32, 0)
    var lines = prog.trimEnd().split("\n")
    for (i in 0...lines.count) {
        var line = lines[i].trim()
        var split = line.split(" ")
        var instr = split[0]
        var addr = 0
        if (split.count == 2) addr = Num.fromString(split[1])
        if (ops[instr]) {
            mem[i] = ops[instr] * 32 + addr
        } else {
            var v = Num.fromString(instr)
            if (v) mem[i] = v
        }
    }
    return mem
}

var output = Fn.new { |acc|
    System.print(acc)
}

var interp = Fn.new { |prog|
    var acc = 0
    var pc = 0
    var mem = load.call(prog)
    while (true) {
        var instr = mem[pc] >> 5
        var addr  = mem[pc] % 32
        pc = pc + 1
        if (instr == LDA) {
            acc = mem[addr]
        } else if (instr == STA) {
            mem[addr] = acc
        } else if (instr == ADD) {
            acc = acc + mem[addr]
            if (acc > 255) acc = acc - 256
        } else if (instr == SUB) {
            acc = acc - mem[addr]
            if (acc < 0) acc = acc + 256
        } else if (instr == BRZ) {
            if (acc == 0) pc = addr
        } else if (instr == JMP) {
            pc = addr
        }
        if (instr == STP || pc > 31) break
    }
    output.call(acc)
}

var progs = [
    """
        LDA 3
        ADD 4
        STP
        2
        2
    """,
    """
        LDA 12
        ADD 10
        STA 12
        LDA 11
        SUB 13
        STA 11
        BRZ 8
        JMP 0
        LDA 12
        STP
        8
        7
        0
        1
    """,
    """
        LDA 14
        STA 15
        ADD 13
        STA 14
        LDA 15
        STA 13
        LDA 16
        SUB 17
        BRZ 11
        STA 16
        JMP 0
        LDA 14
        STP
        1
        1
        0
        8
        1
    """,
    """
        LDA 13
        ADD 15
        STA 5
        ADD 16
        STA 7
        NOP
        STA 14
        NOP
        BRZ 11
        STA 15
        JMP 0
        LDA 14
        STP
        LDA 0
        0
        28
        1

        6
        0
        2
        26
        5
        20
        3
        30
        1
        22
        4
        24
    """,
    """
        0
        0
        STP
        NOP
        LDA 3
        SUB 29
        BRZ 18
        LDA 3
        STA 29
        BRZ 14
        LDA 1
        ADD 31
        STA 1
        JMP 2
        LDA 0
        ADD 31
        STA 0
        JMP 2
        LDA 3
        STA 29
        LDA 0
        ADD 30
        ADD 3
        STA 0
        LDA 1
        ADD 30
        ADD 3
        STA 1
        JMP 2
        0
        1
        3
    """
]
for (prog in progs) interp.call(prog)


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

    Prime prime;
    writeln("First twenty primes:\n", 20.iota.map!prime);
    writeln("Primes primes between 100 and 150:\n",
            uint.max.iota.map!prime.until!q{a > 150}.filter!q{a > 99});
    writeln("Number of primes between 7,700 and 8,000: ",
            uint.max.iota.map!prime.until!q{a > 8_000}
            .filter!q{a > 7_699}.walkLength);
    writeln("10,000th prime: ", prime(9_999));
}


(define-syntax if2
  (syntax-rules ()
    ((if2 cond1 cond2 both-true first-true second-true none-true)
     (let ((c2 cond2))
       (if cond1
           (if c2 both-true first-true)
           (if c2 second-true none-true))))))


$ include "seed7_05.s7i";

$ syntax expr: .if.().().then.().else1.().else2.().else3.().end.if is -> 25;

const proc: if (in boolean: cond1) (in boolean: cond2) then
              (in proc: statements1)
            else1
              (in proc: statements2)
            else2
              (in proc: statements3)
            else3
              (in proc: statements4)
            end if                     is func
  begin
    if cond1 then
      if cond2 then
        statements1;
      else
        statements2;
      end if;
    elsif cond2 then
      statements3;
    else
      statements4;
    end if;
  end func;

const proc: main is func
  begin
    if TRUE FALSE then
      writeln("error TRUE TRUE");
    else1
      writeln("TRUE FALSE");
    else2
      writeln("error FALSE TRUE");
    else3
      writeln("error FALSE FALSE");
    end if;
  end func;


(defmacro branch-if-macro
  [branch-if Cond1 Cond2 Both Fst Snd None] ->
    [if Cond1
        [if Cond2 Both Fst]
        [if Cond2 Snd None]])


import Data.CReal

phi = (1 + sqrt 5) / 2

fib :: (Integral b) => b -> CReal 0
fib n = (phi^^n - (-phi)^^(-n))/sqrt 5


on exponentiationOperatorTask(n, power)
    set power to power as integer
    set operatorResult to (n ^ power)
    set handlerResult to exponentiate(n, power)

    return {operator:operatorResult, |handler|:handlerResult}
end exponentiationOperatorTask

on exponentiate(n, power)
    -- AppleScript's ^ operator returns a real (ie. float) result. This handler does the same.
    set n to n as real
    set out to 1.0
    if (power < 0) then
        repeat -power times
            set out to out / n
        end repeat
    else
        repeat power times
            set out to out * n
        end repeat
    end if

    return out
end exponentiate

exponentiationOperatorTask(3, 3) --> {operator:27.0, |handler|:27.0}
exponentiationOperatorTask(2, 16) --> {operator:6.5536E+4, |handler|:6.5536E+4}
exponentiationOperatorTask(2.5, 10) --> {operator:9536.7431640625, |handler|:9536.7431640625}
exponentiationOperatorTask(2.5, -10) --> {operator:1.048576E-4, |handler|:1.048576E-4}


MsgBox % Pow(5,3)
MsgBox % Pow(2.5,4)

Pow(x, n){
	r:=1
	loop %n%
		r *= x
	return r
}


$ awk 'function pow(x,n){r=1;for(i=0;i<n;i++)r=r*x;return r}{print pow($1,$2)}'


form factorial using iv_val type i.
  data: lv_res type i value 1.
  do iv_val times.
    multiply lv_res by sy-index.
  enddo.

  iv_val = lv_res.
endform.


org &1000
PrintChar equ &BB5A

;reg usage:
;DE = VM'S Program Counter
;IXL = VM's Accumulator
main:
	ld ixl,0
	ld de,Computer_Zero_RAM_2_plus_2
	call Computer_Zero_VM
	ld a,ixl
	call ShowHex	;output to Amstrad CPC's screen
	call NewLine

	ld ixl,0
	ld de,Computer_Zero_RAM_7x8
	call Computer_Zero_VM
	ld a,ixl
	jp ShowHex	;output and return to basic.

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;these two functions are related to displaying the output
;	and have nothing to do with the virtual machine itself.
ShowHex:
		push af
			and %11110000
			rrca
			rrca
			rrca
			rrca
			call PrintHexChar
		pop af
		and %00001111
		;call PrintHexChar
		;execution flows into it naturally.
PrintHexChar:
		;converts hex to ascii
		or a	;Clear Carry Flag
		daa
		add a,&F0
		adc a,&40
		jp PrintChar

NewLine:
	push af
		ld a,13
		call PrintChar
		ld a,10
		call PrintChar
	pop af
	ret

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

Computer_Zero_VM:
	ld a,(de)			;opcode fetch
	call UnpackOpcode	;stores opcode in B, operand in C
	push de
		ld de,Opcode_Table
		ld a,b
		rlca		;index times 2 for word data

		ld e,a
		ld a,(de)
		ld L,a
		inc de
		ld a,(de)
		ld h,a		;LD HL,(DE)

	pop de
	jp (hl)
;register state after this jump:
;DE = program counter
;HL = address of instruction implementation
;C = operand of the instruction we're about to execute
;IXL = accumulator

	overhead:
	ld a,e
	inc a
	and %00011111
	;ensures we stay within the 32 byte address space.
	ld e,a
	jp Computer_Zero_VM

	UnpackOpcode:
	push af
		and %11100000
		rlca
		rlca
		rlca
		ld b,a		;opcode in B
	pop af
	and %00011111
	ld c,a			;operand in C
	dummy:
	ret

align 256	;ensures the following table is page-aligned
;this lets us index it much faster.
Opcode_Table:
	dw vmNOP
	dw vmLDA
	dw vmSTA
	dw vmADD
	dw vmSUB
	dw vmBRZ
	dw vmJMP
	dw vmSTP

vmNOP:
	jp overhead	;do nothing
vmLDA:
	push de
	ld e,c		;offset DE by the operand
	ld a,(de)	;load from that address
	ld ixl,a	;and store it in the accumulator
	pop de
	jp overhead
vmSTA:
	push de
	ld e,c		;offset DE by the operand
	ld a,ixl	;get the accumulator
	ld (de),a	;store it into (DE)
	pop de
	jp overhead
vmADD:
	push de
	ld e,c		;offset DE by the operand
	ld a,(de)	;load from that address
	add ixl		;and add that value to the accumulator
	ld ixl,a	;then set the new accumulator
	pop de
	jp overhead
vmSUB:
	push de
	ld e,c		;offset DE by the operand
	ld a,(de)
	ld b,a
	ld a,ixl
	sub b
	ld ixl,a
	pop de
	noBRZ:
	jp overhead
vmBRZ:
	ld a,ixl
	or a
	jr nz, noBRZ
vmJMP:
	ld e,c
	jp Computer_Zero_VM
vmSTP:
	ret		;return to main

align 256
Computer_Zero_RAM_2_plus_2:
	db %00100011,%01100100
	db %11100000,%00000010
	db %00000010,%00000000
	db %00000000,%00000000
	db %00000000,%00000000
	db %00000000,%00000000
	db %00000000,%00000000
	db %00000000,%00000000
	db %00000000,%00000000
	db %00000000,%00000000
	db %00000000,%00000000
	db %00000000,%00000000
	db %00000000,%00000000
	db %00000000,%00000000
	db %00000000,%00000000
align 256
Computer_Zero_RAM_7x8:
	db %00101100,%01101010
	db %01001100,%00101011
	db %10001101,%01001011
	db %10101000,%11000000
	db %00101100,%11100000
	db %00001000,%00000111
	db %00000000,%00000001
	db %00000000,%00000000
	db %00000000,%00000000
	db %00000000,%00000000
	db %00000000,%00000000
	db %00000000,%00000000
	db %00000000,%00000000
	db %00000000,%00000000
	db %00000000,%00000000
	db %00000000,%00000000


Iterable<int> primesMap() {
    Iterable<int> oddprms() sync* {
      yield(3); yield(5); // need at least 2 for initialization
      final Map<int, int> bpmap = {9: 6};
      final Iterator<int> bps = oddprms().iterator;
      bps.moveNext(); bps.moveNext(); // skip past 3 to 5
      int bp = bps.current;
      int n = bp;
      int q = bp * bp;
      while (true) {
        n += 2;
        while (n >= q || bpmap.containsKey(n)) {
          if (n >= q) {
            final int inc = bp << 1;
            bpmap[bp * bp + inc] = inc;
            bps.moveNext(); bp = bps.current; q = bp * bp;
          } else {
            final int inc = bpmap.remove(n);
            int next = n + inc;
            while (bpmap.containsKey(next)) {
              next += inc;
            }
            bpmap[next] = inc;
          }
          n += 2;
        }
        yield(n);
      }
    }
    return [2].followedBy(oddprms());
}

void main() {
  print("The first 20 primes:");
  String str = "( ";
  primesMap().take(20).forEach((p)=>str += "$p "); print(str + ")");
  print("Primes between 100 and 150:");
  str = "( ";
  primesMap().skipWhile((p)=>p<100).takeWhile((p)=>p<150)
    .forEach((p)=>str += "$p "); print(str + ")");
  print("Number of primes between 7700 and 8000: ${
    primesMap().skipWhile((p)=>p<7700).takeWhile((p)=>p<8000).length
  }");
  print("The 10,000th prime:  ${
    primesMap().skip(9999).first
  }");
  final start = DateTime.now().millisecondsSinceEpoch;
  final answer = primesMap().takeWhile((p)=>p<2000000).reduce((a,p)=>a+p);
  final elapsed = DateTime.now().millisecondsSinceEpoch - start;
}


; the first twenty primes
(primes 20)
    → { 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 }

; a stream to generate primes from a
(define (primes-from a)
    (let ((p (next-prime a)))
     (stream-cons p (primes-from p))))

; primes between 100,150
(for/list  ((p (primes-from 100)))  #:break  (> p 150) p)
    → (101 103 107 109 113 127 131 137 139 149)

; the built-in function (primes-pi )counts the number of primes < a
; count in [7700 ...  8000]
(- (primes-pi 8000) (primes-pi 7700) → 30

; nth-prime
(nth-prime 10000) → 104729

;; big ones
(lib 'bigint)
(define (p-digits n)
  (printf "(next-prime  %d ! ) has %d digits" n
  (number-length (next-prime (factorial n )))))

(next-prime 0! ) has 1 digits
(next-prime 10! ) has 7 digits
(next-prime 100! ) has 158 digits
(next-prime 200! ) has 375 digits
(next-prime 300! ) has 615 digits
(next-prime 400! ) has 869 digits ;; 9400 msec (FireFox)

; is prime (1 + 116!) ?
(prime? (1+ (factorial 116)))  → #t


class if2(cond1, cond2) {
    method then(block) {    # both true
        if (cond1 && cond2) {
            block.run;
        }
        return self;
    }
    method else1(block) {   # first true
        if (cond1 && !cond2) {
            block.run;
        }
        return self;
    }
    method else2(block) {   # second true
        if (cond2 && !cond1) {
            block.run;
        }
        return self;
    }
    method else(block) {    # none true
        if (!cond1 && !cond2) {
            block.run;
        }
        return self;
    }
}

if2(false, true).then {
    say "if2";
}.else1 {
    say "else1";
}.else2 {
    say "else2";        # <- this gets printed
}.else {
    say "else"
}


or:condition2 ifBoth:bothBlk ifFirst:firstBlk ifSecond:scndBlk ifNone:noneBlk
  "I know for sure, that I am true..."
  ^ condition2 ifTrue:bothBlk ifFalse:firstBlk


static function fib(steps:Int, handler:Int->Void)
{
	var current = 0;
	var next = 1;

	for (i in 1...steps)
	{
		handler(current);

		var temp = current + next;
		current = next;
		next = temp;
	}
	handler(current);
}


DECLARE FUNCTION powL& (x AS INTEGER, y AS INTEGER)
DECLARE FUNCTION powS# (x AS SINGLE, y AS INTEGER)

DIM x AS INTEGER, y AS INTEGER
DIM a AS SINGLE

RANDOMIZE TIMER
a = RND * 10
x = INT(RND * 10)
y = INT(RND * 10)
PRINT x, y, powL&(x, y)
PRINT a, y, powS#(a, y)

FUNCTION powL& (x AS INTEGER, y AS INTEGER)
    DIM n AS INTEGER, m AS LONG
    IF x <> 0 THEN
        m = 1
        IF SGN(y) > 0 THEN
            FOR n = 1 TO y
                m = m * x
            NEXT
        END IF
    END IF
    powL& = m
END FUNCTION

FUNCTION powS# (x AS SINGLE, y AS INTEGER)
    DIM n AS INTEGER, m AS DOUBLE
    IF x <> 0 THEN
        m = 1
        IF y <> 0 THEN
            FOR n = 1 TO y
                m = m * x
            NEXT
            IF y < 0 THEN m = 1# / m
        END IF
    END IF
    powS# = m
END FUNCTION


CARD FUNC Factorial(INT n BYTE POINTER err)
  CARD i,res

  IF n<0 THEN
    err^=1 RETURN (0)
  ELSEIF n>8 THEN
    err^=2 RETURN (0)
  FI

  res=1
  FOR i=2 TO n
  DO
    res=res*i
  OD

  err^=0
RETURN (res)

PROC Main()
  INT i,f
  BYTE err

  FOR i=-2 TO 10
  DO
    f=Factorial(i,@err)

    IF err=0 THEN
      PrintF("%I!=%U%E",i,f)
    ELSEIF err=1 THEN
      PrintF("%I is negative value%E",i)
    ELSE
      PrintF("%I! is to big%E",i)
    FI
  OD
RETURN


public static function factorial(n:int):int
{
    if (n < 0)
        return 0;

    var fact:int = 1;
    for (var i:int = 1; i <= n; i++)
        fact *= i;

    return fact;
}


(* Languages with pattern matching ALREADY HAVE THIS! *)

fun myfunc (pred1, pred2) =
  case (pred1, pred2) of
    (true, true) => print ("(true, true)\n")
  | (true, false) => print ("(true, false)\n")
  | (false, true) => print ("(false, true)\n")
  | (false, false) => print ("(false, false)\n");

myfunc (true, true);
myfunc (true, false);
myfunc (false, true);
myfunc (false, false);


proc if2 {cond1 cond2 bothTrueBody firstTrueBody secondTrueBody bothFalseBody} {
    # Must evaluate both conditions, and should do so in order
    set c1 [uplevel 1 [list expr $cond1]
    set c2 [uplevel 1 [list expr $cond2]
    # Now use that to decide what to do
    if {$c1 && $c2} {
        uplevel 1 $bothTrueBody
    } elseif {$c1 && !$c2} {
        uplevel 1 $firstTrueBody
    } elseif {$c2 && !$c1} {
        uplevel 1 $secondTrueBody
    } else {
        uplevel 1 $bothFalseBody
    }
}


(defmacro if2 (cond1 cond2 both first second . neither)
  (let ((res1 (gensym))
        (res2 (gensym)))
    ^(let ((,res1 ,cond1)
           (,res2 ,cond2))
       (cond ((and ,res1 ,res2) ,both)
             (,res1             ,first)
             (,res2             ,second)
             (t                 ,*neither)))))


REAL :: Fibonacci(10)

Fibonacci = ($==2) + Fibonacci($-1) + Fibonacci($-2)
WRITE(ClipBoard) Fibonacci ! 0 1 1 2 3 5 8 13 21 34


#Procedure
exp = { base, exp |
  1.to(exp).reduce 1, { m, n | m = m * base }
}

#Numbers are weird
1.parent.^ = { rhs |
  num = my
  1.to(rhs).reduce 1 { m, n | m = m * num }
}

p exp 2 5 #Prints 32
p 2 ^ 5   #Prints 32


#include <stdio.h>
#include <assert.h>

int ipow(int base, int exp)
{
   int pow = base;
   int v = 1;
   if (exp < 0) {
      assert (base != 0);  /* divide by zero */
      return (base*base != 1)? 0: (exp&1)? base : 1;
   }

   while(exp > 0 )
   {
      if (exp & 1) v *= pow;
      pow *= pow;
      exp >>= 1;
    }
   return v;
}

double dpow(double base, int exp)
{
   double v=1.0;
   double pow = (exp <0)? 1.0/base : base;
   if (exp < 0) exp = - exp;

   while(exp > 0 )
   {
      if (exp & 1) v *= pow;
      pow *= pow;
      exp >>= 1;
   }
   return v;
}

int main()
{
    printf("2^6 = %d\n", ipow(2,6));
    printf("2^-6 = %d\n", ipow(2,-6));
    printf("2.71^6 = %lf\n", dpow(2.71,6));
    printf("2.71^-6 = %lf\n", dpow(2.71,-6));
}


function Factorial (N : Positive) return Positive is
   Result : Positive := N;
   Counter : Natural := N - 1;
begin
   for I in reverse 1..Counter loop
      Result := Result * I;
   end loop;
   return Result;
end Factorial;


defmodule PrimesSoEMap do
  @typep stt :: {integer, integer, integer, Enumerable.integer, %{integer => integer}}

  @spec advance(stt) :: stt
  defp advance {n, bp, q, bps?, map} do
    bps = if bps? === nil do Stream.drop(oddprms(), 1) else bps? end
    nn = n + 2
    if nn >= q do
      inc = bp + bp
      nbps = bps |> Stream.drop(1)
      [nbp] = nbps |> Enum.take(1)
      advance {nn, nbp, nbp * nbp, nbps, map |> Map.put(nn + inc, inc)}
    else if Map.has_key?(map, nn) do
      {inc, rmap} = Map.pop(map, nn)
      [next] =
        Stream.iterate(nn + inc, &(&1 + inc))
          |> Stream.drop_while(&(Map.has_key?(rmap, &1))) |> Enum.take(1)
      advance {nn, bp, q, bps, Map.put(rmap, next, inc)}
    else
      {nn, bp, q, bps, map}
    end end
  end

  @spec oddprms() :: Enumerable.integer
  defp oddprms do # put first base prime cull seq in Map so never empty
    # advance base odd primes to 5 when initialized
    init = {7, 5, 25, nil, %{9 => 6}}
    [3, 5] # to avoid race, preseed with the first 2 elements...
      |> Stream.concat(
            Stream.iterate(init, &(advance &1))
              |> Stream.map(fn {p,_,_,_,_} -> p end))
  end

  @spec primes() :: Enumerable.integer
  def primes do
    Stream.concat([2], oddprms())
  end

end

IO.write "The first 20 primes are:\n( "
PrimesSoEMap.primes() |> Stream.take(20) |> Enum.each(&(IO.write "#{&1} "))
IO.puts ")"
IO.write "The primes between 100 to 150 are:\n( "
PrimesSoEMap.primes() |> Stream.drop_while(&(&1<100))
  |> Stream.take_while(&(&1<150)) |> Enum.each(&(IO.write "#{&1} "))
IO.puts ")"
IO.write "The number of primes between 7700 and 8000 is:  "
PrimesSoEMap.primes() |> Stream.drop_while(&(&1<7700))
  |> Stream.take_while(&(&1<8000)) |> Enum.count |> IO.puts
IO.write "The 10,000th prime is:  "
PrimesSoEMap.primes() |> Stream.drop(9999)
  |> Enum.take(1) |> List.first |>IO.puts
IO.write "The sum of all the priems to two million is:  "
testfunc =
  fn () ->
    ans =
      PrimesSoEMap.primes() |> Stream.take_while(&(&1<=2000000))
        |> Enum.sum() |> IO.puts
    ans end
:timer.tc(testfunc)
  |> (fn {t,_} ->
    IO.puts "This test bench took #{t} microseconds." end).()


if2() {
	if eval "$1"; then
		if eval "$2"; then eval "$3"; else eval "$4"; fi
	else
		if eval "$2"; then eval "$5"; else eval "$6"; fi
	fi
}


iftwo("p","q") <"both","justp","justq","neither"> =

"p"?(
   "q"?("both","justp"),
   "q"?("justq","neither"))


class IfBoth {
    construct new(cond1, cond2) {
        _cond1 = cond1
        _cond2 = cond2
    }

    elseFirst(func) {
        if (_cond1 && !_cond2) func.call()
        return this
    }

    elseSecond(func) {
        if (_cond2 && !_cond1) func.call()
        return this
    }

    elseNeither(func) {
        if (!_cond1 && !_cond2) func.call()
        return this // in case it's called out of order
    }
}

var ifBoth = Fn.new { |cond1, cond2, func|
    if (cond1 && cond2) func.call()
    return IfBoth.new(cond1, cond2)
}

var a = 0
var b = 1

ifBoth.call(a == 1, b == 3) {
    System.print("a == 1 and b == 3")
}.elseFirst {
    System.print("a == 1 and b <> 3")
}.elseSecond {
    System.print("a <> 1 and b = 3")
}.elseNeither {
    System.print("a <> 1 and b <> 3")
}

// It's also possible to omit any (or all) of the 'else' clauses
// or to call them out of order.
a = 1
b = 0

ifBoth.call (a == 1, b == 3) {
    System.print("a == 1 and b == 3")
}.elseNeither {
    System.print("a <> 1 and b <> 3")
}.elseFirst {
    System.print("a == 1 and b <> 3")
}


|=  [email protected]
=/  [email protected]  0
=/  [email protected]  1
|-
?:  =(n 0)  a
$(a b, b (add a b), n (dec n))


static void Main(string[] args)
{
	Console.WriteLine("5^5 = " + Expon(5, 5));
	Console.WriteLine("5.5^5 = " + Expon(5.5, 5));
	Console.ReadLine();
}

static double Expon(int Val, int Pow)
{
	return Math.Pow(Val, Pow);
}
static double Expon(double Val, int Pow)
{
	return Math.Pow(Val, Pow);
}


template<typename Number>
 Number power(Number base, int exponent)
{
  int zerodir;
  Number factor;
  if (exponent < 0)
  {
    zerodir = 1;
    factor = Number(1)/base;
  }
  else
  {
    zerodir = -1;
    factor = base;
  }

  Number result(1);
  while (exponent != 0)
  {
    if (exponent % 2 != 0)
    {
      result *= factor;
      exponent += zerodir;
    }
    else
    {
      factor *= factor;
      exponent /= 2;
    }
  }
  return result;
}


factorial : ℕ → ℕ
factorial zero = 1
factorial (suc n) = suc n * factorial n


let primeZ fN  =primes()|>Seq.unfold(fun g-> Some(fN(g()), g))
let primesI()  =primeZ bigint
let primes64() =primeZ int64
let primes32() =primeZ int32
let pCache     =Seq.cache(primes32())
let isPrime   g=if g<2  then false else let mx=int(sqrt(float g)) in pCache|>Seq.takeWhile(fun n->n<=mx)|>Seq.forall(fun n->g%n>0)
let isPrime64 g=if g<2L then false else let mx=int(sqrt(float g)) in pCache|>Seq.takeWhile(fun n->n<=mx)|>Seq.forall(fun n->g%(int64 n)>0L)


#>
newsyntax
@in:CH
@token:does
@CH:"function(Stack){
	this.Next(Stack);
	this.ChunkWrite(Stack,this.ParseExpression(Stack));
	this.TestNext(Stack,\"Bracket\",\"TK_BOPEN\");
	this.Move(Stack,2);
	this.CodeBlock(Stack);
	this.JumpBack(Stack);
	this.OpenChunk(Stack);
	while(this.CheckNext(Stack,\"Identifier\",\"otherwise\")||this.CheckNext(Stack,\"Identifier\",\"or\")){
		if(this.CheckNext(Stack,\"Identifier\",\"otherwise\")){
			this.OpenChunk(Stack);
			this.ChunkWrite(Stack,\"else\");
			this.Next(Stack);
			this.TestNext(Stack,\"Bracket\",\"TK_BOPEN\");
			this.Move(Stack,2);
			this.CodeBlock(Stack);
			this.JumpBack(Stack);
			this.CloseChunk(Stack);
			break;
		}else{
			this.OpenChunk(Stack);
			this.ChunkWrite(Stack,\"elif\");
			this.Move(Stack,2);
			this.ChunkWrite(Stack,this.ParseExpression(Stack));
			this.TestNext(Stack,\"Bracket\",\"TK_BOPEN\");
			this.Move(Stack,2);
			this.CodeBlock(Stack);
			this.JumpBack(Stack);
			this.CloseChunk(Stack);
		}
	}
	this.CloseChunk(Stack);
}"
@Interpret:"function(AST,Token){
	let Condition = this.Parse(AST,Token[3]);
	if(Condition){
		this.CondState(AST,Token[4]);
	} else {
		let Conds = Token[5];
		if(Conds.length<1){return}
		let DidCond = false;
		let ElseCond = undefined;
		for(let v of Conds){
			if(DidCond){break}
			if(v[0]==\"else\"){
				ElseCond=v;
				break;
			}else if(v[0]==\"elif\"){
				let Exp = this.Parse(AST,v[1]);
				if(Exp){
					DidCond=true;
					this.CondState(AST,v[2]);
					break;
				}
			}
		}
		if(!DidCond&&ElseCond){
			this.CondState(AST,ElseCond[1]);
		}
	}
}"
<#

func equalsOneOrTwo(a){
	does a == 1 {
		log(`Yep! {a} == 1`);
	} or a == 2 {
		log(`Yes, {a} == 2`);
	} otherwise {
		does a <= 0 {
			log(`Sorry, your number {a} must be greater than 0!`);
		} otherwise {
			log(`Nope. {a} != 1 or 2`);
		}
	}
}

equalsOneOrTwo(1);
equalsOneOrTwo(2);
equalsOneOrTwo(3);
equalsOneOrTwo(0);


cp b
jr nz,B_False
   cp c
   jr z,doubleTrue
   ;B true, C false

   ;your code goes here

   jp done
B_False:
   cp c
   jr nz,doubleFalse
   ;B false, C true

   ;your code goes here

   jp done

doubleTrue:
   ;your code goes here
   jp done
doubleFalse:
  ;your code goes here
  jp done

done:
  ;rest of program


10 DEF FN i()=((NOT (a OR b))+2*(a AND NOT b)+3*(b AND NOT a)+4*(a AND b)): REM the function can be placed anywhere in the program, but it gets executed faster if it's at the top
20 FOR x=1 TO 20
30 LET a=(x/2)=INT (x/2): REM comparison 1
40 LET b=(x/3)=INT (x/3): REM comparison 2
50 GO TO 50+10*FN i(): REM cases
60 PRINT x;" is not divisible by 2 or 3": GO TO 100
70 PRINT x;" is divisible by 2": GO TO 100
80 PRINT x;" is divisible by 3": GO TO 100
90 PRINT x;" is divisible by 2 and 3"
100 NEXT x


import std.stdio, std.conv;

struct Number(T) {
    T x; // base
    alias x this;
    string toString() const { return text(x); }

    Number opBinary(string op)(in int exponent)
    const pure nothrow @nogc if (op == "^^") in {
        if (exponent < 0)
            assert (x != 0, "Division by zero");
    } body {
        debug puts("opBinary ^^");

        int zerodir;
        T factor;
        if (exponent < 0) {
            zerodir = +1;
            factor = T(1) / x;
        } else {
            zerodir = -1;
            factor = x;
        }

        T result = 1;
        int e = exponent;
        while (e != 0)
            if (e % 2 != 0) {
                result *= factor;
                e += zerodir;
            } else {
                factor *= factor;
                e /= 2;
            }

        return Number(result);
    }
}

void main() {
    alias Double = Number!double;
    writeln(Double(2.5) ^^ 5);

    alias Int = Number!int;
    writeln(Int(3) ^^ 3);
    writeln(Int(0) ^^ -2); // Division by zero.
}


integer
factorial(integer n)
{
    integer i, result;

    result = 1;
    i = 1;
    while (i < n) {
        i += 1;
        result *= i;
    }

    return result;
}


USING: io math.primes prettyprint sequences ;

"First 20 primes: " write
20 nprimes .

"Primes between 100 and 150: " write
100 150 primes-between .

"Number of primes between 7,700 and 8,000: " write
7,700 8,000 primes-between length .

"10,000th prime: " write
10,000 nprimes last .


program Exponentiation_operator;

{$APPTYPE CONSOLE}

uses
  System.SysUtils;

type
  TDouble = record
    Value: Double;
    class operator Implicit(a: TDouble): Double;
    class operator Implicit(a: Double): TDouble;
    class operator Implicit(a: TDouble): string;
    class operator LogicalXor(a: TDouble; b: Integer): TDouble;
  end;

  TInteger = record
    Value: Integer;
    class operator Implicit(a: TInteger): Integer;
    class operator Implicit(a: Integer): TInteger;
    class operator Implicit(a: TInteger): string;
    class operator LogicalXor(a: TInteger; b: Integer): TInteger;
  end;

{ TDouble }

class operator TDouble.Implicit(a: TDouble): Double;
begin
  Result := a.Value;
end;

class operator TDouble.Implicit(a: Double): TDouble;
begin
  Result.Value := a;
end;

class operator TDouble.Implicit(a: TDouble): string;
begin
  Result := a.Value.ToString;
end;

class operator TDouble.LogicalXor(a: TDouble; b: Integer): TDouble;
var
  i: Integer;
  val: Double;
begin
  val := 1;
  for i := 1 to b do
    val := val * a.Value;
  Result.Value := val;
end;

{ TInteger }

class operator TInteger.Implicit(a: TInteger): Integer;
begin
  Result := a.Value;
end;

class operator TInteger.Implicit(a: Integer): TInteger;
begin
  Result.Value := a;
end;

class operator TInteger.Implicit(a: TInteger): string;
begin
  Result := a.Value.ToString;
end;

class operator TInteger.LogicalXor(a: TInteger; b: Integer): TInteger;
var
  val, i: Integer;
begin
  if b < 0 then
    raise Exception.Create('Expoent must be greater or equal zero');

  val := 1;
  for i := 1 to b do
    val := val * a.Value;
  Result.Value := val;
end;

procedure Print(s: string);
begin
  Write(s);
end;

var
  valF: TDouble;
  valI: TInteger;

begin
  valF := 5.5;
  valI := 5;

  // Delphi  don't have "**" or "^" operator for overload,
  // "xor" operator has used instead
  Print('5^5 = ');
  Print(valI xor 5);
  print(#10);

  Print('5.5^5 = ');
  Print(valF xor 5);
  print(#10);

  readln;
end.


begin
	comment factorial - algol 60;
	integer procedure factorial(n); integer n;
	begin
		integer i,fact;
		fact:=1;
		for i:=2 step 1 until n do
			fact:=fact*i;
		factorial:=fact
	end;
	integer i;
	for i:=1 step 1 until 10 do outinteger(1,factorial(i));
	outstring(1,"\n")
end


      DO WHILE(F*F <= LST)         !But, F*F might overflow the integer limit so instead,
      DO WHILE(F <= LST/F)                      !Except, LST might also overflow the integer limit, so
      DO WHILE(F <= (IST + 2*(SBITS - 1))/F)    !Which becomes...
      DO WHILE(F <= IST/F + (MOD(IST,F) + 2*(SBITS - 1))/F) !Preserving the remainder from IST/F.


procedure main(args)
    write(fib(integer(!args) | 1000)
end

procedure fib(n)
    static fCache
    initial {
        fCache := table()
        fCache[0] := 0
        fCache[1] := 1
        }
    /fCache[n] := fib(n-1) + fib(n-2)
    return fCache[n]
end


def power(base, exponent :int) {
    var r := base
    if (exponent < 0) {
        for _ in exponent..0 { r /= base }
    } else if (exponent <=> 0) {
        return 1
    } else {
        for _ in 2..exponent { r *= base }
    }
    return r
}


PROC factorial = (INT upb n)LONG LONG INT:(
  LONG LONG INT z := 1;
  FOR n TO upb n DO z *:= n OD;
  z
); ~


' FB 1.05.0

Enum SieveLimitType
  number
  between
  countBetween
End Enum

Sub printPrimes(low As Integer, high As Integer, slt As SieveLimitType)
  If high < low OrElse low < 1 Then Return               ' too small
  If slt <> number AndAlso slt <> between AndAlso slt <> countBetween Then Return
  If slt <> number AndAlso (low < 2 OrElse high < 2) Then Return
  If slt <> number AndAlso high > 1000000000 Then Return ' too big
  If slt = number  AndAlso high > 50000000 Then Return   ' too big
  Dim As Integer n
  If slt = number Then
    n = 20 * high '' big enough to accomodate 50 million primes to which this procedure is limited
  Else
    n = high
  End If
  Dim a(2 To n) As Boolean '' only uses 1 byte per element
  For i As Integer = 2 To n : a(i) = True : Next '' set all elements to True to start with
  Dim As Integer p = 2, q
  ' mark non-prime numbers by setting the corresponding array element to False

  Do
    For j As Integer = p * p To n Step p
      a(j) = False
    Next j
    ' look for next True element in array after 'p'
    q = 0
    For j As Integer = p + 1 To Sqr(n)
      If a(j) Then
        q = j
        Exit For
      End If
    Next j
    If q = 0 Then Exit Do
    p = q
  Loop

  Select Case As Const slt
     Case number
       Dim count As Integer = 0
       For i As Integer = 2 To n
         If a(i) Then
           count += 1
           If count >= low AndAlso count <= high Then
             Print i; " ";
           End If
           If count = high Then Exit Select
         End If
       Next

    Case between
       For i As Integer = low To high
         If a(i) Then
           Print i; " ";
         End if
       Next

    Case countBetween
       Dim count As Integer = 0
       For i As Integer = low To high
         If a(i) Then count += 1
       Next
       Print count;

  End Select
  Print
End Sub

Print "The first 20 primes are :"
Print
printPrimes(1, 20, number)
Print
Print "The primes between 100 and 150 are :"
Print
printPrimes(100, 150, between)
Print
Print "The number of primes between 7700 and 8000 is :";
printPrimes(7700, 8000, countBetween)
Print
Print "The 10000th prime is :";
Dim t As Double = timer
printPrimes(10000, 10000, number)
Print "Computed in "; CInt((timer - t) * 1000 + 0.5); " ms"
Print
Print "The 1000000th prime is :";
t = timer
printPrimes(1000000, 1000000, number)
Print "Computed in ";CInt((timer - t) * 1000 + 0.5); " ms"
Print
Print "The 50000000th prime is :";
t = timer
printPrimes(50000000, 50000000, number)
Print "Computed in ";CInt((timer - t) * 1000 + 0.5); " ms"
Print
Print "Press any key to quit"
Sleep


function fib,n
   if n lt 3 then return,1L else return, fib(n-1)+fib(n-2)
end


open number

_ ^ 0           =  1
x ^ n | n > 0   =  f x (n - 1) x
      |else = fail "Negative exponent"
  where f _ 0 y = y
        f a d y = g a d
          where g b i | even i  = g (b * b) (i `quot` 2)
                      | else = f b (i - 1) (b * y)

(12 ^ 4, 12 ** 4)


defmodule My do
  def exp(x,y) when is_integer(x) and is_integer(y) and y>=0 do
    IO.write("int>   ")         # debug test
    exp_int(x,y)
  end
  def exp(x,y) when is_integer(y) do
    IO.write("float> ")         # debug test
    exp_float(x,y)
  end
  def exp(x,y), do: (IO.write("       "); :math.pow(x,y))

  defp exp_int(_,0), do: 1
  defp exp_int(x,y), do: Enum.reduce(1..y, 1, fn _,acc -> x * acc end)

  defp exp_float(_,y) when y==0, do: 1.0
  defp exp_float(x,y) when y<0, do: 1/exp_float(x,-y)
  defp exp_float(x,y), do: Enum.reduce(1..y, 1, fn _,acc -> x * acc end)
end

list = [{2,0}, {2,3}, {2,-2},
        {2.0,0}, {2.0,3}, {2.0,-2},
        {0.5,0}, {0.5,3}, {0.5,-2},
        {-2,2}, {-2,3}, {-2.0,2}, {-2.0,3},
        ]
IO.puts "                    ___My.exp___  __:math.pow_"
Enum.each(list, fn {x,y} ->
  sxy = "#{x} ** #{y}"
  sexp = inspect My.exp(x,y)
  spow = inspect :math.pow(x,y)         # For the comparison
  :io.fwrite("~10s = ~12s, ~12s~n", [sxy, sexp, spow])
end)


pow(X, Y) when Y < 0 ->
    1/pow(X, -Y);
pow(X, Y) when is_integer(Y) ->
    pow(X, Y, 1).

pow(_, 0, B) ->
    B;
pow(X, Y, B) ->
    B2 = if Y rem 2 =:= 0 -> B; true -> X * B end,
    pow(X * X, Y div 2, B2).


begin
    % computes factorial n iteratively                                       %
    integer procedure factorial( integer value n ) ;
        if n < 2
        then 1
        else begin
            integer f;
            f := 2;
            for i := 3 until n do f := f * i;
            f
        end factorial ;

    for t := 0 until 10 do write( "factorial: ", t, factorial( t ) );

end.


println["The first 20 primes are: " + first[primes[], 20]]
println["The primes between 100 and 150 are: " + primes[100,150]]
println["The number of primes between 7700 and 8000 are: " + length[primes[7700,8000]]]
println["The 10,000th prime is: " + nth[primes[], 10000-1]]  // nth is zero-based


package main

import (
    "container/heap"
    "fmt"
)

func main() {
    p := newP()
    fmt.Print("First twenty: ")
    for i := 0; i < 20; i++ {
        fmt.Print(p(), " ")
    }
    fmt.Print("\nBetween 100 and 150: ")
    n := p()
    for n <= 100 {
        n = p()
    }
    for ; n < 150; n = p() {
        fmt.Print(n, " ")
    }
    for n <= 7700 {
        n = p()
    }
    c := 0
    for ; n < 8000; n = p() {
        c++
    }
    fmt.Println("\nNumber beween 7,700 and 8,000:", c)
    p = newP()
    for i := 1; i < 10000; i++ {
        p()
    }
    fmt.Println("10,000th prime:", p())
}

func newP() func() int {
    n := 1
    var pq pQueue
    top := &pMult{2, 4, 0}
    return func() int {
        for {
            n++
            if n < top.pMult { // n is a new prime
                heap.Push(&pq, &pMult{prime: n, pMult: n * n})
                top = pq[0]
                return n
            }
            // n was next on the queue, it's a composite
            for top.pMult == n {
                top.pMult += top.prime
                heap.Fix(&pq, 0)
                top = pq[0]
            }
        }
    }
}

type pMult struct {
    prime int
    pMult int
    index int
}

type pQueue []*pMult

func (q pQueue) Len() int           { return len(q) }
func (q pQueue) Less(i, j int) bool { return q[i].pMult < q[j].pMult }
func (q pQueue) Swap(i, j int) {
    q[i], q[j] = q[j], q[i]
    q[i].index = i
    q[j].index = j
}
func (p *pQueue) Push(x interface{}) {
    q := *p
    e := x.(*pMult)
    e.index = len(q)
    *p = append(q, e)
}
func (p *pQueue) Pop() interface{} {
    q := *p
    last := len(q) - 1
    e := q[last]
    *p = q[:last]
    return e
}


fibAnalytic : Nat -> Double
fibAnalytic n =
    floor $ ((pow goldenRatio n) - (pow (-1.0/goldenRatio) n))  / sqrt(5)
  where goldenRatio : Double
        goldenRatio = (1.0 + sqrt(5)) / 2.0


PROGRAM POWER

PROCEDURE POWER(A,B->POW)   ! this routine handles only *INTEGER* powers
  LOCAL FLAG%
  IF B<0 THEN B=-B FLAG%=TRUE
  POW=1
  FOR X=1 TO B DO
    POW=POW*A
  END FOR
  IF FLAG% THEN POW=1/POW
END PROCEDURE

BEGIN
   POWER(11,-2->POW) PRINT(POW)
   POWER(π,3->POW) PRINT(POW)
END PROGRAM


//Integer Exponentiation, more interesting anyway than repeated multiplication. Nigel Galloway, October 12th., 2018
let rec myExp n g=match g with
                  |0            ->1
                  |g when g%2=1 ->n*(myExp n (g-1))
                  |_            ->let p=myExp n (g/2) in p*p

printfn "%d" (myExp 3 15)


: pow ( f n -- f' )
    dup 0 < [ abs pow recip ]
    [ [ 1 ] 2dip swap [ * ] curry times ] if ;


: ** ( n m -- n^m )
  1 swap  0 ?do over * loop  nip ;


INTEGER FUNCTION FACTORIAL( N ); INTEGER N;
BEGIN
    INTEGER I, FACT;
    FACT := 1;
    FOR I := 2 STEP 1 UNTIL N DO
        FACT := FACT * I;
    FACTORIAL := FACT;
END;


PROC fact(x) IS IF x>=2 THEN x*fact(x-1) ELSE 1

PROC main()
  WriteF('5! = \d\n', fact(5))
ENDPROC


#!/usr/bin/env runghc

import Data.List
import Data.Numbers.Primes
import System.IO

firstNPrimes :: Integer -> [Integer]
firstNPrimes n = genericTake n primes

primesBetweenInclusive :: Integer -> Integer -> [Integer]
primesBetweenInclusive lo hi =
  dropWhile (< lo) $ takeWhile (<= hi) primes

nthPrime :: Integer -> Integer
nthPrime n = genericIndex primes (n - 1) -- beware 0-based indexing

main = do
  hSetBuffering stdout NoBuffering
  putStr "First 20 primes: "
  print $ firstNPrimes 20
  putStr "Primes between 100 and 150: "
  print $ primesBetweenInclusive 100 150
  putStr "Number of primes between 7700 and 8000: "
  print $ genericLength $ primesBetweenInclusive 7700 8000
  putStr "The 10000th prime: "
  print $ nthPrime 10000


MODULE Exp_Mod
IMPLICIT NONE

INTERFACE OPERATOR (.pow.)    ! Using ** instead would overload the standard exponentiation operator
  MODULE PROCEDURE Intexp, Realexp
END INTERFACE

CONTAINS

  FUNCTION Intexp (base, exponent)
    INTEGER :: Intexp
    INTEGER, INTENT(IN) :: base, exponent
    INTEGER :: i

    IF (exponent < 0) THEN
       IF (base == 1) THEN
          Intexp = 1
       ELSE
          Intexp = 0
       END IF
       RETURN
    END IF
    Intexp = 1
    DO i = 1, exponent
      Intexp = Intexp * base
    END DO
  END FUNCTION IntExp

  FUNCTION Realexp (base, exponent)
    REAL :: Realexp
    REAL, INTENT(IN) :: base
    INTEGER, INTENT(IN) :: exponent
    INTEGER :: i

    Realexp = 1.0
    IF (exponent < 0) THEN
       DO i = exponent, -1
          Realexp = Realexp / base
       END DO
    ELSE
       DO i = 1, exponent
          Realexp = Realexp * base
       END DO
    END IF
  END FUNCTION RealExp
END MODULE Exp_Mod

PROGRAM EXAMPLE
USE Exp_Mod
  WRITE(*,*) 2.pow.30, 2.0.pow.30
END PROGRAM EXAMPLE


' FB 1.05.0

' Note that 'base' is a keyword in FB, so we use 'base_' instead as a parameter

Function Pow Overload (base_ As Double, exponent As Integer) As Double
  If exponent = 0.0 Then Return 1.0
  If exponent = 1.0 Then Return base_
  If exponent < 0.0 Then Return 1.0 / Pow(base_, -exponent)
  Dim power As Double = base_
  For i As Integer = 2 To exponent
     power *= base_
  Next
  Return power
End Function

Function Pow Overload(base_ As Integer, exponent As Integer) As Double
   Return Pow(CDbl(base_), exponent)
End Function

' check results of these functions using FB's built in '^' operator
Print "Pow(2, 2)       = "; Pow(2, 2)
Print "Pow(2.5, 2)     = "; Pow(2.5, 2)
Print "Pow(2, -3)      = "; Pow(2, -3)
Print "Pow(1.78, 3)    = "; Pow(1.78, 3)
Print
Print "2 ^ 2           = "; 2 ^ 2
Print "2.5 ^ 2         = "; 2.5 ^ 2
Print "2 ^ -3          = "; 2 ^ -3
Print "1.78 ^ 3        = "; 1.78 ^ 3
Print
Print "Press any key to quit"
Sleep


factorial:{1 */ 1+range[x]} /Call: factorial[1000]


public static long itFibN(int n)
{
 if (n < 2)
  return n;
 long ans = 0;
 long n1 = 0;
 long n2 = 1;
 for(n--; n > 0; n--)
 {
  ans = n1 + n2;
  n1 = n2;
  n2 = ans;
 }
 return ans;
}


package main

import (
    "errors"
    "fmt"
)

func expI(b, p int) (int, error) {
    if p < 0 {
        return 0, errors.New("negative power not allowed")
    }
    r := 1
    for i := 1; i <= p; i++ {
        r *= b
    }
    return r, nil
}

func expF(b float32, p int) float32 {
    var neg bool
    if p < 0 {
        neg = true
        p = -p
    }
    r := float32(1)
    for pow := b; p > 0; pow *= pow {
        if p&1 == 1 {
            r *= pow
        }
        p >>= 1
    }
    if neg {
        r = 1 / r
    }
    return r
}

func main() {
    ti := func(b, p int) {
        fmt.Printf("%d^%d: ", b, p)
        e, err := expI(b, p)
        if err != nil {
            fmt.Println(err)
        } else {
            fmt.Println(e)
        }
    }

    fmt.Println("expI tests")
    ti(2, 10)
    ti(2, -10)
    ti(-2, 10)
    ti(-2, 11)
    ti(11, 0)

    fmt.Println("overflow undetected")
    ti(10, 10)

    tf := func(b float32, p int) {
        fmt.Printf("%g^%d: %g\n", b, p, expF(b, p))
    }

    fmt.Println("\nexpF tests:")
    tf(2, 10)
    tf(2, -10)
    tf(-2, 10)
    tf(-2, 11)
    tf(11, 0)

    fmt.Println("disallowed in expI, allowed here")
    tf(0, -1)

    fmt.Println("other interesting cases for 32 bit float type")
    tf(10, 39)
    tf(10, -39)
    tf(-10, 39)
}


public static long fact(final Integer n) {
    if (n < 0) {
        System.debug('No negative numbers');
        return 0;
    }
    long ans = 1;
    for (Integer i = 1; i <= n; i++) {
        ans *= i;
    }
    return ans;
}


function fib(n) {
  return n<2?n:fib(n-1)+fib(n-2);
}


(^) :: (Num a, Integral b) => a -> b -> a
_ ^ 0           =  1
x ^ n | n > 0   =  f x (n-1) x where
  f _ 0 y = y
  f a d y = g a d  where
    g b i | even i  = g (b*b) (i `quot` 2)
          | otherwise = f b (i-1) (b*y)
_ ^ _           = error "Prelude.^: negative exponent"


WRITE(Clipboard) pow(5,   3)  ! 125
WRITE(ClipBoard) pow(5.5, 7)  ! 152243.5234

FUNCTION pow(x, n)
   pow = 1
   DO i = 1, n
      pow = pow * x
   ENDDO
END


procedure main()
bases := [5,5.]
numbers := [0,2,2.,-1,3]
every  write("expon(",b := !bases,", ",x := !numbers,")=",(expon(b,x) | "failed") \ 1)
end

procedure expon(base,power)
local op,res

base := numeric(base)            | runerror(102,base)
power := power = integer(power)  | runerr(101,power)

if power = 0 then return 1
else op := if power < 1 then
              (base := real(base)) & "/"   # force real base
              else "*"

res := 1
every 1 to abs(power) do
   res := op(res,base)
return res
end