import java.util.*;

public class PrimeGenerator {
    private int limit_;
    private int index_ = 0;
    private int increment_;
    private int count_ = 0;
    private List<Integer> primes_ = new ArrayList<>();
    private BitSet sieve_ = new BitSet();
    private int sieveLimit_ = 0;

    public PrimeGenerator(int initialLimit, int increment) {
        limit_ = nextOddNumber(initialLimit);
        increment_ = increment;
        primes_.add(2);
        findPrimes(3);
    }

    public int nextPrime() {
        if (index_ == primes_.size()) {
            if (Integer.MAX_VALUE - increment_ < limit_)
                return 0;
            int start = limit_ + 2;
            limit_ = nextOddNumber(limit_ + increment_);
            primes_.clear();
            findPrimes(start);
        }
        ++count_;
        return primes_.get(index_++);
    }

    public int count() {
        return count_;
    }

    private void findPrimes(int start) {
        index_ = 0;
        int newLimit = sqrt(limit_);
        for (int p = 3; p * p <= newLimit; p += 2) {
            if (sieve_.get(p/2 - 1))
                continue;
            int q = p * Math.max(p, nextOddNumber((sieveLimit_ + p - 1)/p));
            for (; q <= newLimit; q += 2*p)
                sieve_.set(q/2 - 1, true);
        }
        sieveLimit_ = newLimit;
        int count = (limit_ - start)/2 + 1;
        BitSet composite = new BitSet(count);
        for (int p = 3; p <= newLimit; p += 2) {
            if (sieve_.get(p/2 - 1))
                continue;
            int q = p * Math.max(p, nextOddNumber((start + p - 1)/p)) - start;
            q /= 2;
            for (; q >= 0 && q < count; q += p)
                composite.set(q, true);
        }
        for (int p = 0; p < count; ++p) {
            if (!composite.get(p))
                primes_.add(p * 2 + start);
        }
    }

    private static int sqrt(int n) {
        return nextOddNumber((int)Math.sqrt(n));
    }

    private static int nextOddNumber(int n) {
        return 1 + 2 * (n/2);
    }

    public static void main(String[] args) {
        PrimeGenerator pgen = new PrimeGenerator(20, 200000);
        System.out.println("First 20 primes:");
        for (int i = 0; i < 20; ++i) {
            if (i > 0)
                System.out.print(", ");
            System.out.print(pgen.nextPrime());
        }
        System.out.println();
        System.out.println("Primes between 100 and 150:");
        for (int i = 0; ; ) {
            int prime = pgen.nextPrime();
            if (prime > 150)
                break;
            if (prime >= 100) {
                if (i++ != 0)
                    System.out.print(", ");
                System.out.print(prime);
            }
        }
        System.out.println();
        int count = 0;
        for (;;) {
            int prime = pgen.nextPrime();
            if (prime > 8000)
                break;
            if (prime >= 7700)
                ++count;
        }
        System.out.println("Number of primes between 7700 and 8000: " + count);
        int n = 10000;
        for (;;) {
            int prime = pgen.nextPrime();
            if (prime == 0) {
                System.out.println("Can't generate any more primes.");
                break;
            }
            if (pgen.count() == n) {
                System.out.println(n + "th prime: " + prime);
                n *= 10;
            }
        }
    }
}


DEFINE fib == [small] [] [pred dup pred] [+] binrec.


public class Exp{
   public static void main(String[] args){
      System.out.println(pow(2,30));
      System.out.println(pow(2.0,30)); //tests
      System.out.println(pow(2.0,-2));
   }

   public static double pow(double base, int exp){
      if(exp < 0) return 1 / pow(base, -exp);
      double ans = 1.0;
      for(;exp > 0;--exp) ans *= base;
      return ans;
   }
}


function pow(base, exp) {
    if (exp != Math.floor(exp))
        throw "exponent must be an integer";
    if (exp < 0)
        return 1 / pow(base, -exp);
    var ans = 1;
    while (exp > 0) {
        ans *= base;
        exp--;
    }
    return ans;
}


on factorial(x)
    if x < 0 then return 0
    set R to 1
    repeat while x > 1
        set {R, x} to {R * x, x - 1}
    end repeat
    return R
end factorial


function primeGenerator(num, showPrimes) {
  var i,
      arr = [];

  function isPrime(num) {
    // try primes <= 16
    if (num <= 16) return (
      num == 2 || num == 3 || num == 5 || num == 7 || num == 11 || num == 13
    );
    // cull multiples of 2, 3, 5 or 7
    if (num % 2 == 0 || num % 3 == 0 || num % 5 == 0 || num % 7 == 0)
      return false;
    // cull square numbers ending in 1, 3, 7 or 9
    for (var i = 10; i * i <= num; i += 10) {
      if (num % (i + 1) == 0) return false;
      if (num % (i + 3) == 0) return false;
      if (num % (i + 7) == 0) return false;
      if (num % (i + 9) == 0) return false;
    }
    return true;
  }

  if (typeof num == "number") {
    for (i = 0; arr.length < num; i++) if (isPrime(i)) arr.push(i);
    // first x primes
    if (showPrimes) return arr;
    // xth prime
    else return arr.pop();
  }

  if (Array.isArray(num)) {
    for (i = num[0]; i <= num[1]; i++) if (isPrime(i)) arr.push(i);
    // primes between x .. y
    if (showPrimes) return arr;
    // number of primes between x .. y
    else return arr.length;
  }
  // throw a default error if nothing returned yet
  // (surrogate for a quite long and detailed try-catch-block anywhere before)
  throw("Invalid arguments for primeGenerator()");
}


# 0^0 => 1
# NOTE: jq converts very large integers to floats.
# This implementation uses reduce to avoid deep recursion
def power_int(n):
  if n == 0 then 1
  elif . == 0 then 0
  elif n < 0 then 1/power_int(-n)
  elif ((n | floor) == n) then
       ( (n % 2) | if . == 0 then 1 else -1 end ) as $sign
       | if (. == -1) then $sign
         elif . < 0 then (( -(.) | power_int(n) ) * $sign)
         else . as $in | reduce range(1;n) as $i ($in; . * $in)
         end
  else error("This is a toy implementation that requires n be integral")
  end ;


function pow(base::Number, exp::Integer)
  r = one(base)
  for i = 1:exp
    r *= base
  end
  return r
end


// version 1.0.6

infix fun Int.ipow(exp: Int): Int =
    when {
        this ==  1 -> 1
        this == -1 -> if (exp and 1 == 0) 1 else -1
        exp <  0   -> throw IllegalArgumentException("invalid exponent")
        exp == 0   -> 1
        else       -> {
            var ans = 1
            var base = this
            var e = exp
            while (e > 1) {
                if (e and 1 == 1) ans *= base
                e = e shr 1
                base *= base
            }
            ans * base
        }
    }

infix fun Double.dpow(exp: Int): Double {
    var ans = 1.0
    var e   = exp
    var base = if (e < 0) 1.0 / this else this
    if (e < 0) e = -e
    while (e > 0) {
        if (e and 1 == 1) ans *= base
        e = e shr 1
        base *= base
    }
    return ans
}

fun main(args: Array<String>) {
    println("2  ^ 3   = ${2 ipow 3}")
    println("1  ^ -10 = ${1 ipow -10}")
    println("-1 ^ -3  = ${-1 ipow -3}")
    println()
    println("2.0 ^ -3 = ${2.0 dpow -3}")
    println("1.5 ^ 0  = ${1.5 dpow 0}")
    println("4.5 ^ 2  = ${4.5 dpow 2}")
}


100 N = 4 : GOSUB 200"FACTORIAL
110 PRINT N
120 END

200 N = INT(N)
210 IF N > 1 THEN FOR I = N - 1 TO 2 STEP -1 : N = N * I : NEXT I
220 RETURN


# Recent versions of jq include the following definition:
# until/2 loops until cond is satisfied,
# and emits the value satisfying the condition:
def until(cond; next):
  def _until:
    if cond then . else (next|_until) end;
  _until;

def count(cond): reduce .[] as $x (0; if $x|cond then .+1 else . end);


using Primes

sum = 2
currentprime = 2
for i in 2:100000
    currentprime = nextprime(currentprime + 1)
    sum += currentprime
end
println("The sum of the first 100,000 primes is $sum")

curprime = 1
arr = zeros(Int, 20)
for i in 1:20
    curprime = nextprime(curprime + 1)
    arr[i] = curprime
end
println("The first 20 primes are ", arr)

println("the primes between 100 and 150 are ", primes(100,150))
println("The number of primes between 7,700 and 8,000 is ", length(primes(7700, 8000)))
println("The 10,000th prime is ", prime(10000))


fib(n) = n < 2 ? n : fib(n-1) + fib(n-2)


{def ^
 {def *^
  {lambda {:base :exponent :acc}
   {if {= :exponent 0}
    then :acc
    else {*^ :base {- :exponent 1} {* :acc :base}}}}}
 {lambda {:base :exponent}
  {*^ :base :exponent 1}}}
-> ^

{^ 2 3}
-> 8
{^ {/ 1 2} 3}
-> 0.125       // No rational type as primitives
{^ 0.5 3}
-> 0.125


  print " 11^5     = ", floatPow(  11,       5  )
  print " (-11)^5  = ", floatPow( -11,       5  )
  print " 11^( -5) = ", floatPow(  11,      -5  )
  print " 3.1416^3 = ", floatPow(   3.1416,  3  )
  print " 0^2      = ", floatPow(   0,       2  )
  print "  2^0     = ", floatPow(   2,       0  )
  print " -2^0     = ", floatPow(  -2,       0  )

  end

  function floatPow( a, b)
      if a <>0 then
          m =1
          if b =abs( b) then
              for n =1 to b
                  m =m *a
              next n
          else
              m =1 /floatPow( a, 0 - b)  ' LB has no unitary minus operator.
          end if
      else
          m =0
      end if
      floatPow =m
  end function


< n >

{ @n = 0 ,
   ( return , 1 )
,
   ( return ,
       @n * !factorial( @n - ! )
   )
}


/* ARM assembly Raspberry PI  */
/*  program factorial.s   */

/* Constantes    */
.equ STDOUT, 1     @ Linux output console
.equ EXIT,   1     @ Linux syscall
.equ WRITE,  4     @ Linux syscall

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

szMessResult:  .ascii "Resultat = "      @ message result
sMessValeur:   .fill 12, 1, ' '
                   .asciz "\n"
/*********************************/
/* UnInitialized data            */
/*********************************/
.bss
/*********************************/
/*  code section                 */
/*********************************/
.text
.global main
main:                @ entry of program
    push {fp,lr}      @ saves 2 registers

    mov r0,#-5
    bl factorial
    mov r0,#10
    bl factorial
    mov r0,#20
    bl factorial

100:   @ standard end of the program
    mov r0, #0                  @ return code
    pop {fp,lr}                 @restaur 2 registers
    mov r7, #EXIT              @ request to exit program
    swi 0                       @ perform the system call

/********************************************/
/*     calculation                         */
/********************************************/
/* r0 contains number N */
factorial:
    push {r1,r2,lr}    	@ save  registres
    cmp r0,#0
    blt 99f
    beq 100f
    cmp r0,#1
    beq 100f
    bl calFactorial
    cmp r0,#-1          @ overflow ?
    beq 98f
    ldr r1,iAdrsMessValeur
    bl conversion10       @ call function with 2 parameter (r0,r1)
    ldr r0,iAdrszMessResult
    bl affichageMess            @ display message
    b 100f

98:   @ display error message
    ldr r0,iAdrszMessLargeNumber
    bl affichageMess
    b 100f
99:  @ display error message
    ldr r0,iAdrszMessNegNumber
    bl affichageMess

100:
    pop {r1,r2,lr}    			@ restaur registers
    bx lr	        			@ return
iAdrszMessNegNumber:       .int szMessNegNumber
iAdrszMessLargeNumber:	    .int szMessLargeNumber
iAdrsMessValeur:            .int sMessValeur
iAdrszMessResult:          .int szMessResult
/******************************************************************/
/*     calculation                         */
/******************************************************************/
/* r0 contains the number N */
calFactorial:
    cmp r0,#1          @ N = 1 ?
    bxeq lr           @ yes -> return
    push {fp,lr}    		@ save  registers
    sub sp,#4           @ 4 byte on the stack
    mov fp,sp           @ fp <- start address stack
    str r0,[fp]                    @ fp contains  N
    sub r0,#1          @ call function with N - 1
    bl calFactorial
    cmp r0,#-1         @ error overflow ?
    beq 100f         @ yes -> return
    ldr r1,[fp]       @ load N
    umull r0,r2,r1,r0   @ multiply result by N
    cmp r2,#0           @ r2 is the hi rd  if <> 0 overflow
    movne r0,#-1      @ if overflow  -1 -> r0

100:
    add sp,#4            @ free 4 bytes on stack
    pop {fp,lr}    			@ restau2 registers
    bx lr	        		@ return

/******************************************************************/
/*     display text with size calculation                         */
/******************************************************************/
/* r0 contains the address of the message */
affichageMess:
    push {fp,lr}    			/* save  registres */
    push {r0,r1,r2,r7}    		/* save others registers */
    mov r2,#0   				/* counter length */
1:      	/* loop length calculation */
    ldrb r1,[r0,r2]  			/* read octet start position + index */
    cmp r1,#0       			/* if 0 its over */
    addne r2,r2,#1   			/* else add 1 in the length */
    bne 1b          			/* and loop */
                                /* so here r2 contains the length of the message */
    mov r1,r0        			/* address message in r1 */
    mov r0,#STDOUT      		/* code to write to the standard output Linux */
    mov r7, #WRITE             /* code call system "write" */
    swi #0                      /* call systeme */
    pop {r0,r1,r2,r7}     		/* restaur others registers */
    pop {fp,lr}    				/* restaur des  2 registres */
    bx lr	        			/* return  */
/******************************************************************/
/*     Converting a register to a decimal                                 */
/******************************************************************/
/* r0 contains value and r1 address area   */
conversion10:
    push {r1-r4,lr}    /* save registers */
    mov r3,r1
    mov r2,#10

1:	   @ start loop
    bl divisionpar10 @ r0 <- dividende. quotient ->r0 reste -> r1
    add r1,#48        @ digit
    strb r1,[r3,r2]  @ store digit on area
    sub r2,#1         @ previous position
    cmp r0,#0         @ stop if quotient = 0 */
    bne 1b	          @ else loop
    @ and move spaves in first on area
    mov r1,#' '   @ space
2:
    strb r1,[r3,r2]  @ store space in area
    subs r2,#1       @ @ previous position
    bge 2b           @ loop if r2 >= zéro

100:
    pop {r1-r4,lr}    @ restaur registres
    bx lr	          @return
/***************************************************/
/*   division par 10   signé                       */
/* Thanks to http://thinkingeek.com/arm-assembler-raspberry-pi/*
/* and   http://www.hackersdelight.org/            */
/***************************************************/
/* r0 dividende   */
/* r0 quotient */
/* r1 remainder  */
divisionpar10:
  /* r0 contains the argument to be divided by 10 */
   push {r2-r4}   /* save registers  */
   mov r4,r0
   ldr r3, .Ls_magic_number_10 /* r1 <- magic_number */
   smull r1, r2, r3, r0   /* r1 <- Lower32Bits(r1*r0). r2 <- Upper32Bits(r1*r0) */
   mov r2, r2, ASR #2     /* r2 <- r2 >> 2 */
   mov r1, r0, LSR #31    /* r1 <- r0 >> 31 */
   add r0, r2, r1         /* r0 <- r2 + r1 */
   add r2,r0,r0, lsl #2   /* r2 <- r0 * 5 */
   sub r1,r4,r2, lsl #1   /* r1 <- r4 - (r2 * 2)  = r4 - (r0 * 10) */
   pop {r2-r4}
   bx lr                  /* leave function */
   .align 4
.Ls_magic_number_10: .word 0x66666667


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

fun generatePrimes() = sequence {
        yield(2)
        var p = 3
        while (p <= Int.MAX_VALUE) {
           if (isPrime(p)) yield(p)
           p += 2
        }
    }

fun main(args: Array<String>) {
    val primes = generatePrimes().take(10000) // generate first 10,000 primes
    println("First 20 primes : ${primes.take(20).toList()}")
    println("Primes between 100 and 150 : ${primes.filter { it in 100..150 }.toList()}")
    println("Number of primes between 7700 and 8000 = ${primes.filter { it in 7700..8000 }.count()}")
    println("10,000th prime = ${primes.last()}")
}


-- As for built-in power() function:
-- base can be either integer or float; returns float.
on pow (base, exp)
  if exp=0 then return 1.0
  else if exp<0 then
    exp = -exp
    base = 1.0/base
  end if
  res = float(base)
  repeat with i = 2 to exp
    res = res*base
  end repeat
  return res
end


to int_power :n :m
  if equal? 0 :m [output 1]
  if equal? 0 modulo :m 2 [output int_power :n*:n :m/2]
  output :n * int_power :n :m-1
end


number = {}

function number.pow( a, b )
    local ret = 1
    if b >= 0 then
        for i = 1, b do
            ret = ret * a.val
        end
    else
        for i = b, -1 do
            ret = ret / a.val
        end
    end
    return ret
end

function number.New( v )
    local num = { val = v }
    local mt = { __pow = number.pow }
    setmetatable( num, mt )
    return num
end

x = number.New( 5 )
print( x^2 )                   --> 25
print( number.pow( x, -4 ) )   --> 0.016


LISTEN TO ME VERY CAREFULLY factorial
I NEED YOUR CLOTHES YOUR BOOTS AND YOUR MOTORCYCLE n
GIVE THESE PEOPLE AIR
BECAUSE I'M GOING TO SAY PLEASE n
BULLS***
I'LL BE BACK 1
YOU HAVE NO RESPECT FOR LOGIC
HEY CHRISTMAS TREE product
YOU SET US UP @NO PROBLEMO
STICK AROUND n
GET TO THE CHOPPER product
HERE IS MY INVITATION product
YOU'RE FIRED n
ENOUGH TALK
GET TO THE CHOPPER n
HERE IS MY INVITATION n
GET DOWN @NO PROBLEMO
ENOUGH TALK
CHILL
I'LL BE BACK product
HASTA LA VISTA, BABY


factorial: $[n][
	if? n>0 [n * factorial n-1]
	else [1]
]


local primegen = {
  count_limit = 2,
  value_limit = 3,
  primelist = { 2, 3 },
  nextgenvalue = 5,
  nextgendelta = 2,
  tbd = function(n)
    if n < 2 then return false end
    if n % 2 == 0 then return n==2 end
    if n % 3 == 0 then return n==3 end
    local limit = math.sqrt(n)
    for f = 5, limit, 6 do
      if n % f == 0 or n % (f+2) == 0 then return false end
    end
    return true
  end,
  needmore = function(self)
    return (self.count_limit ~= nil and #self.primelist < self.count_limit)
        or (self.value_limit ~= nil and self.nextgenvalue < self.value_limit)
  end,
  generate = function(self, count_limit, value_limit)
    self.count_limit = count_limit
    self.value_limit = value_limit
    while self:needmore() do
      if (self.tbd(self.nextgenvalue)) then
        self.primelist[#self.primelist+1] = self.nextgenvalue
      end
      self.nextgenvalue = self.nextgenvalue + self.nextgendelta
      self.nextgendelta = 6 - self.nextgendelta
    end
  end,
  filter = function(self, f)
    local list = {}
    for k,v in ipairs(self.primelist) do
      if (f(v)) then list[#list+1] = v end
    end
    return list
  end,
}

primegen:generate(20, nil)
print("First 20 primes:  " .. table.concat(primegen.primelist, ", "))

primegen:generate(nil, 150)
print("Primes between 100 and 150:  " .. table.concat(primegen:filter(function(v) return v>=100 and v<=150 end), ", "))

primegen:generate(nil, 8000)
print("Number of primes between 7700 and 8000:  " .. #primegen:filter(function(v) return v>=7700 and v<=8000 end))

primegen:generate(10000, nil)
print("The 10,000th prime:  " .. primegen.primelist[#primegen.primelist])

primegen:generate(100000, nil)
print("The 100,000th prime:  " .. primegen.primelist[#primegen.primelist])


// Calculate the $n'th Fibonacci number

// Set this to how many in the sequence to generate
$n = 10;

// These are what hold the current calculation
$a = 0;
$b = 1;

// This holds the complete sequence that is generated
$sequence = "";

// Prepare a loop
$i = 0;
:calcnextnumber;
	$i = $i++;

	// Do the calculation for this loop iteration
	$b = $a + $b;
	$a = $b - $a;

	// Add the result to the sequence
	$sequence = $sequence << $a;

	// Make the loop run a fixed number of times
	if $i < $n; {
		$sequence = $sequence << ", ";
		goto calcnextnumber;
	}

// Use the loop counter as the placeholder
$i--;

// Return the sequence
return = "Fibonacci number " << $i << " is " << $a << " (" << $sequence << ")";


pow(n,x)
   k = n fby k div 2;
   p = x fby p*p;
   y =1 fby if even(k) then y else y*p;
   result y asa k eq 0;
end


Module Exponentiation {
	\\ a variable can be any type except  a string (no $ in name)
	\\ variable b is long type.
	\\ by default we pass by value arguments to a function
	\\ to pass by reference we have to use & before name,
	\\ in the signature and in the call
	function pow(a, b as long) {
		p=a-a  ' make p same type as a
		p++
		if b>0 then for i=1& to b {p*=a}
		=p
	}
	const fst$="{0::-32} {1}"
	Document exp$
	k= pow(11&, 5)
	exp$=format$(fst$, k, type$(k)="Long")+{
	}
	l=pow(11, 5)
	exp$=format$(fst$, l, type$(l)="Double")+{
	}
	m=pow(pi, 3)
	exp$=format$(fst$, m, type$(m)="Decimal")+{
	}
	\\ send to clipboard
	clipboard exp$
	\\ send  monospaced type text to console using cr char to change lines
	Print #-2, exp$
	Rem Report exp$  ' send to console using proportional spacing and justification
}
Exponentiation


-- parent script "sieve"
property _sieve

----------------------------------------
-- @constructor
----------------------------------------
on new (me)
    me._sieve = []
    me._primeSieve(100) -- arbitrary initial size of sieve
    return me
end

----------------------------------------
-- Returns sorted list of first n primes p with p >= a (default: a=1)
----------------------------------------
on getNPrimes (me, n, a)
    if voidP(a) then a = 1
    i = a
    res = []
    repeat while TRUE
        if i>me._sieve.count then me._primeSieve(2*i)
        if me._sieve[i] then res.add(i)
        if res.count=n then return res
        i = i +1
    end repeat
end

----------------------------------------
-- Returns sorted list of primes p with a <= p <= b
----------------------------------------
on getPrimesInRange (me, a, b)
    if me._sieve.count<b then me._primeSieve(b)
    primes = []
    repeat with i = a to b
        if me._sieve[i] then primes.add(i)
    end repeat
    return primes
end

----------------------------------------
-- Returns nth prime
----------------------------------------
on getNthPrime (me, n)
    if me._sieve.count<2*n then me._primeSieve(2*n)
    i = 0
    found = 0
    repeat while TRUE
        i = i +1
        if i>me._sieve.count then me._primeSieve(2*i)
        if me._sieve[i] then found=found+1
        if found=n then return i
    end repeat
end

----------------------------------------
-- Sieve of Eratosthenes
----------------------------------------
on _primeSieve (me, limit)
    if me._sieve.count>=limit then
        return
    else if me._sieve.count>0 then
        return me._complementSieve(limit)
    end if
    me._sieve = [0]
    repeat with i = 2 to limit
        me._sieve[i] = 1
    end repeat
    c = sqrt(limit)
    repeat with i = 2 to c
        if (me._sieve[i]=0) then next repeat
        j = i*i
        repeat while (j<=limit)
            me._sieve[j] = 0
            j = j + i
        end repeat
    end repeat
end

----------------------------------------
-- Expands existing sieve to new limit
----------------------------------------
on _complementSieve (me, n)
    n1 = me._sieve.count
    repeat with i = n1+1 to n
        me._sieve[i] = 1
    end repeat
    c1 = sqrt(n1)
    repeat with i = 2 to c1
        if (me._sieve[i]=0) then next repeat
        j = n1 - (n1 mod i)
        repeat while (j<=n)
            me._sieve[j] = 0
            j = j + i
        end repeat
    end repeat
    c = sqrt(n)
    repeat with i = c1+1 to c
        if (me._sieve[i]=0) then next repeat
        j = i*i
        repeat while (j<=n)
            me._sieve[j] = 0
            j = j + i
        end repeat
    end repeat
end


Module CheckPrimes {
      \\ Inventories are lists, Known and Known1 are pointers to Inventories
      Inventory Known=1:[email protected],2:[email protected],3:[email protected]
      Inventory [email protected], [email protected], [email protected]
      \\ In a lambda all closures are copies
      \\ but Known and Know1 are copies of pointers
      \\ so are closures like by reference
      PrimeNth=lambda  Known, Known1  (n as long) -> {
            if n<1 then Error "Only >=1"
            if exist(known, n) then =eval(known) : exit
            if n>5 then {
                 i=len(known1)
                 x=eval(known1, i-1)+2
            } else  x=5 : i=2
            {
                  if i=n then  =known(n) : exit
                  ok=false
                  if frac(x) then 1000
                  if frac(x/2) else 1000
                  if frac(x/3) else 1000
                  x1=sqrt(x) : [email protected]
                  Repeat
                        if frac(x/d ) else exit
                        d += 2: if d>x1 then ok=true : exit
                        if frac(x/d) else exit
                        d += 4: if d<= x1 else ok=true: exit
                   Always
      1000    If ok then i++:Append Known, i:=x  : if not exist(Known1, x) then Append Known1, x
                   x+=2 : Loop }
      }
      \\ IsPrime has same closure, Known1
      IsPrime=lambda  Known1 (x as decimal) -> {
            if exist(Known1, x) then =true : exit
            if Eval(Known1, len(Known1)-1)>x then exit
            if frac(x/2) else exit
            if frac(x/3) else exit
            x1=sqrt(x):d = [email protected]
            {if frac(x/d ) else exit
                  d += 2: if d>x1 then =true : exit
                  if frac(x/d) else exit
                  d += 4: if d<= x1 else =true: exit
                  loop
             }
      }
      \\ fill Known1, PrimeNth is a closure here
      IsPrime2=lambda  Known1, PrimeNth (x as decimal) -> {
            if exist(Known1, x) then =true : exit
            i=len(Known1)
            if Eval(Known1, i-1)>x then exit
            {
                  z=PrimeNth(i)
                  if z<x then loop else.if z=x then =true :exit
                  i++
            }
      }
      Print "First twenty primes"
      n=PrimeNth(20)
      For i=1 to 20  : Print Known(i),: Next i
      Print
      Print "Primes between 100 and 150:"
      c=0
      For i=100 to 150
            If IsPrime2(i) Then print i, : c++
      Next i
      Print
      Print "Count:", c
      Print "Primes between 7700 and 8000:"
      c=0
      For i=7700  to 8000
            If IsPrime(i) Then print i, : c++
      Next i
      Print
      Print "Count:", c
      Print "200th Prime:"
      Print PrimeNth(200)
      Print "List from 190th to 199th Prime:"
      For i=190 to 199 : Print Known(i), : Next i
      Print
      Print "Wait"
      Refresh  ' because refresh happen on next Print, which take time
      ' using set fast! we get no respond from GUI/M2000 Console
      ' also Esc, Break and Ctrl+C not work
      ' we have to use Refresh each 500 primes to have one Refresh
      Set fast !
      for i=500 to 10000 step 50: m=PrimeNth(i): Print "."; :Refresh:Next i
      Print
      Print "10000th Prime:", PrimeNth(10000)
      ' reset speed to fast (there are three levels: slow/fast/fast!)
      set fast
      Print
      Rem 1 : Print Known
      Rem  2: Print Known1
}
CheckPrimes


:Fibonacci
    dup 0 less
    ( ["Invalid argument"]
      [1 1 rot 2 sub [drop over over add] for]
    ) if
;

30 Fibonacci pstack print nl

msec print nl
"bertlham " input


(* Library Interface *)
DEFINITION MODULE Exponentiation;

PROCEDURE IntExp(base, exp : INTEGER) : INTEGER;
 (* Raises base to the power of exp and returns the result
    both base and exp must be of type INTEGER *)

PROCEDURE RealExp(base : REAL; exp : INTEGER) : REAL;
 (* Raises base to the power of exp and returns the result
    base must be of type REAL, exp of type INTEGER *)

END Exponentiation.

(* Library Implementation *)
IMPLEMENTATION MODULE Exponentiation;

PROCEDURE IntExp(base, exp : INTEGER) : INTEGER;
  VAR
    i, res : INTEGER;
  BEGIN
    res := 1;
    FOR i := 1 TO exp DO
      res := res * base;
    END;
    RETURN res;
  END IntExp;

PROCEDURE RealExp(base: REAL; exp: INTEGER) : REAL;
  VAR
    i : INTEGER;
    res : REAL;
  BEGIN
    res := 1.0;
    IF exp < 0 THEN
      FOR i := exp TO -1 DO
        res := res / base;
      END;
    ELSE (* exp >= 0 *)
      FOR i := 1 TO exp DO
        res := res * base;
      END;
    END;
    RETURN res;
  END RealExp;

END Exponentiation.


MODULE Expt EXPORTS Main;

IMPORT IO, Fmt;

PROCEDURE IntExpt(arg, exp: INTEGER): INTEGER =
  VAR result := 1;
  BEGIN
    FOR i := 1 TO exp DO
      result := result * arg;
    END;
    RETURN result;
  END IntExpt;

PROCEDURE RealExpt(arg: REAL; exp: INTEGER): REAL =
  VAR result := 1.0;
  BEGIN
    IF exp < 0 THEN
      FOR i := exp TO -1 DO
        result := result / arg;
      END;
    ELSE
      FOR i := 1 TO exp DO
        result := result * arg;
      END;
    END;
    RETURN result;
  END RealExpt;

BEGIN
  IO.Put("2 ^ 4 = " & Fmt.Int(IntExpt(2, 4)) & "\n");
  IO.Put("2.5 ^ 4 = " & Fmt.Real(RealExpt(2.5, 4)) & "\n");
END Expt.


fun
fact
(
  n: int
) : int = res where
{
  var n: int = n
  var res: int = 1
  val () = while (n > 0) (res := res * n; n := n - 1)
}


import tables

type PrimeType = int

proc primesHashTable(): iterator(): PrimeType {.closure.} =
  iterator output(): PrimeType {.closure.} =
    # some initial values to avoid race and reduce initializations...
    yield 2.PrimeType; yield 3.PrimeType; yield 5.PrimeType; yield 7.PrimeType
    var h = initTable[PrimeType,PrimeType]()
    var n = 9.PrimeType
    let bps = primesHashTable()
    var bp = bps() # advance past 2
    bp = bps(); var q = bp * bp # to initialize with 3
    while true:
      if n >= q:
        let inc = bp + bp
        h[n + inc] = inc
        bp = bps(); q = bp * bp
      elif h.hasKey(n):
        var inc: PrimeType
        discard h.take(n, inc)
        var nxt = n + inc
        while h.hasKey(nxt): nxt += inc # ensure no duplicates
        h[nxt] = inc
      else: yield n
      n += 2.PrimeType
  output

var num = 0
stdout.write "The first 20 primes are:  "
var iter = primesHashTable()
for p in iter():
  if num >= 20: break else: stdout.write(p, " "); num += 1
echo ""
stdout.write "The primes between 100 and 150 are:  "
iter = primesHashTable()
for p in iter():
  if p >= 150: break
  if p >= 100: stdout.write(p, " ")
echo ""
num = 0
iter = primesHashTable()
for p in iter():
  if p > 8000: break
  if p >= 7700: num += 1
echo "The number of primes between 7700 and 8000 is:  ", num
num = 1
iter = primesHashTable()
for p in iter():
  if num >= 10000:
    echo "The 10,000th prime is:  ", p
    break
  num += 1
var sum = 0
iter = primesHashTable()
for p in iter():
  if p >= 2_000_000:
    echo "The sum of the primes to two million is:  ", sum
    break
  sum += p


enum class Fibonacci {
    ITERATIVE {
        override fun get(n: Int): Long = if (n < 2) {
            n.toLong()
        } else {
            var n1 = 0L
            var n2 = 1L
            repeat(n) {
                val sum = n1 + n2
                n1 = n2
                n2 = sum
            }
            n1
        }
    },
    RECURSIVE {
        override fun get(n: Int): Long = if (n < 2) n.toLong() else this[n - 1] + this[n - 2]
    },
    CACHING {
        val cache: MutableMap<Int, Long> = mutableMapOf(0 to 0L, 1 to 1L)
        override fun get(n: Int): Long = if (n < 2) n.toLong() else impl(n)
        private fun impl(n: Int): Long = cache.computeIfAbsent(n) { impl(it-1) + impl(it-2) }
    },
    ;

    abstract operator fun get(n: Int): Long
}

fun main() {
    val r = 0..30
    for (fib in Fibonacci.values()) {
        print("${fib.name.padEnd(10)}:")
        for (i in r) { print(" " + fib[i]) }
        println()
    }
}


using System;

macro @^ (val, pow : int)
{
    <[ Math.Pow($val, $pow) ]>
}


proc `^`[T: float|int](base: T; exp: int): T =
  var (base, exp) = (base, exp)
  result = 1

  if exp < 0:
    when T is int:
      if base * base != 1: return 0
      elif (exp and 1) == 0: return 1
      else: return base
    else:
      base = 1.0 / base
      exp = -exp

  while exp != 0:
    if (exp and 1) != 0:
      result *= base
    exp = exp shr 1
    base *= base

echo "2^6 = ", 2^6
echo "2^-6 = ", 2 ^ -6
echo "2.71^6 = ", 2.71^6
echo "2.71^-6 = ", 2.71 ^ -6


class Exp {
  function : Main(args : String[]) ~ Nil {
    Pow(2,30)->PrintLine();
    Pow(2.0,30)->PrintLine();
    Pow(2.0,-2)->PrintLine();
   }

  function : native : Pow(base : Float, exp : Int) ~ Float {
    if(exp < 0) {
      return 1 / base->Power(exp * -1.0);
    };

    ans := 1.0;
    while(exp > 0) {
      ans *= base;
      exp -= 1;
    };

    return ans;
  }
}


MsgBox % factorial(4)

factorial(n)
{
  result := 1
  Loop, % n
    result *= A_Index
  Return result
}


void
showprimes(GEN lower, GEN upper)
{
  forprime_t T;
  if (!forprime_init(&T, a,b)) return;
  while(forprime_next(&T))
  {
    pari_printf("%Ps\n", T.pp);
  }
}


(defn int fib (int n) (return (? (< n 2) n (+ (fib (- n 1)) (fib (- n 2))))))
(main (prn (fib 30)))


: powint(r, n)
| i |
   1 n abs loop: i [ r * ]
   n isNegative ifTrue: [ inv ] ;

2 3 powint println
2 powint(3) println
1.2 4 powint println
1.2 powint(4) println


;AutoIt Version: 3.2.10.0
MsgBox (0,"Factorial",factorial(6))
Func factorial($int)
    If $int < 0 Then
      Return 0
   EndIf
   $fact = 1
   For $i = 1 To $int
        $fact = $fact * $i
   Next
   Return $fact
EndFunc


use Math::Prime::Util qw(nth_prime prime_count primes);
# Direct solutions.
# primes([start],end) returns an array reference with all primes in the range
# prime_count([start],end) uses sieving or LMO to return fast prime counts
# nth_prime(n) does just that.  It runs quite fast for native size inputs.
say "First 20: ", join(" ", @{primes(nth_prime(20))});
say "Between 100 and 150: ", join(" ", @{primes(100,150)});
say prime_count(7700,8000), " primes between 7700 and 8000";
say "${_}th prime: ", nth_prime($_) for map { 10**$_ } 1..8;


Program ExponentiationOperator(output);

function intexp (base, exponent: integer): longint;
  var
    i: integer;

  begin
    if (exponent < 0) then
      if (base = 1) then
        intexp := 1
      else
        intexp := 0
    else
    begin
      intexp := 1;
      for i := 1 to exponent do
        intexp := intexp * base;
    end;
  end;

function realexp (base: real; exponent: integer): real;
  var
    i: integer;

  begin
    realexp := 1.0;
    if (exponent < 0) then
      for i := exponent to -1 do
        realexp := realexp / base
    else
      for i := 1 to exponent do
        realexp := realexp * base;
  end;

begin
  writeln('2^30: ', intexp(2, 30));
  writeln('2.0^30: ', realexp(2.0, 30));
end.


#!/usr/bin/perl -w
use strict ;

sub expon {
   my ( $base , $expo ) = @_ ;
   if ( $expo == 0 ) {
      return 1 ;
   }
   elsif ( $expo == 1 ) {
      return $base ;
   }
   elsif ( $expo > 1 ) {
      my $prod = 1 ;
      foreach my $n ( 0..($expo - 1) ) {
	 $prod *= $base ;
      }
      return $prod ;
   }
   elsif ( $expo < 0 ) {
      return 1 / ( expon ( $base , -$expo ) ) ;
   }
}
print "3 to the power of 10 as a function is " . expon( 3 , 10 ) . " !\n" ;
print "3 to the power of 10 as a builtin is " . 3**10 . " !\n" ;
print "5.5 to the power of -3 as a function is " . expon( 5.5 , -3 ) . " !\n" ;
print "5.5 to the power of -3 as a builtin is " . 5.5**-3 . " !\n" ;


function fact_r(n)
{
  if ( n <= 1 ) return 1;
  return n*fact_r(n-1);
}


with javascript_semantics
if platform()!=JS then free_console() end if
sequence primes = {2,3,5,7}
atom sieved = 10

procedure add_block()
integer N = min((sieved-1)*sieved,400000)
sequence sieve = repeat(1,N)    -- sieve[i] is really i+sieved
    for i=2 to length(primes) do -- (evens filtered on output)
        atom p = primes[i], p2 = p*p
        if p2>sieved+N then exit end if
        if p2<sieved+1 then
            p2 += ceil((sieved+1-p2)/p)*p
        end if
        p2 -= sieved
        if and_bits(p2,1)=0 then p2 += p end if
--      if sieve[p2] then           -- dang!
            for k=p2 to N by p*2 do
                sieve[k] = 0
            end for
--      end if
    end for
    for i=1 to N by 2 do
        if sieve[i] then
            primes &= i+sieved
        end if
    end for
    sieved += N
end procedure

function is_prime2(integer n)
    while sieved<n do
        add_block()
    end while
    return binary_search(n,primes)>0
end function

atom t0 = time()
while length(primes)<20 do add_block() end while
printf(1,"The first 20 primes are: ")   ?primes[1..20]
while sieved<150 do add_block() end while
sequence s = {}
for k=abs(binary_search(100,primes)) to length(primes) do
    integer p = primes[k]
    if p>150 then exit end if
    s &= p
end for
printf(1,"The primes between 100 and 150 are: ")    ?s
s = {}
for i=7700 to 8000 do
    if is_prime2(i) then s&=i end if
end for
printf(1,"There are %d primes between 7700 and 8000.\n",length(s))
for i=1 to iff(platform()=JS?7:8) do
    integer k = power(10,i)
    while length(primes)<k do
        add_block()
    end while
    printf(1,"The %,dth prime is : %d\n",{k,primes[k]})
end for
?time()-t0
if platform()!=JS then {} = wait_key() end if


F hello()
   print(‘Hello, world!’)

String src
F quine()
   print(:src)

F bottles()
   L(i) (99.<2).step(-1)
      print(‘#. bottles of beer on the wall’.format(i))
      print(‘#. bottles of beer’.format(i))
      print(‘Take one down, pass it around’)
      print(‘#. bottles of beer on the wall’.format(i - 1))
      print()

   print(‘2 bottles of beer on the wall’)
   print(‘2 bottles of beer’)
   print(‘Take one down, pass it around’)
   print(‘1 bottle of beer on the wall’)
   print()

   print(‘1 bottle of beer on the wall’)
   print(‘1 bottle of beer’)
   print(‘Take one down, pass it around’)
   print(‘No more bottles of beer on the wall’)
   print()

   print(‘No more bottles of beer on the wall’)
   print(‘No more bottles of beer on the wall’)
   print(‘Go to the store and buy some more’)
   print(‘99 bottles of beer on the wall.’)
   print()

V acc = 0
F incr()
   :acc++

:start:
src = File(:argv[1]).read()

[Char = (() -> N)] dispatch
dispatch[Char(‘h’)] = hello
dispatch[Char(‘q’)] = quine
dispatch[Char(‘9’)] = bottles
dispatch[Char(‘+’)] = incr

L(i) src.lowercase()
   I i C dispatch
      dispatch[i]()


with javascript_semantics
function powir(atom b, integer i)
    atom res = 1
    if i<0 then {b,i} = {1/b,abs(i)} end if
    while i do
        if and_bits(i,1) then res *= b end if
        b *= b
        i = floor(i/2)
    end while
    return res
end function
?powir(-3,-5)
?power(-3,-5)


(de ** (X N)  # N th power of X
   (if (ge0 N)
      (let Y 1
         (loop
            (when (bit? 1 N)
               (setq Y (* Y X)) )
            (T (=0 (setq N (>> 1 N)))
               Y )
            (setq X (* X X)) ) )
      0 ) )


declare exp generic
  (iexp when (fixed, fixed),
   fexp when (float, fixed) );
iexp: procedure (m, n) returns (fixed binary (31));
   declare (m, n) fixed binary (31) nonassignable;
   declare exp fixed binary (31) initial (m), i fixed binary;
   if m = 0 & n = 0 then signal error;
   if n = 0 then return (1);
   do i = 2 to n;
      exp = exp * m;
   end;
   return (exp);
end iexp;
fexp: procedure (a, n) returns (float (15));
   declare (a float, n fixed binary (31)) nonassignable;
   declare exp float initial (a), i fixed binary;
   if a = 0 & n = 0 then signal error;
   if n = 0 then return (1);
   do i = 2 to n;
      exp = exp * a;
   end;
   return (exp);
end fexp;


Lbl FACT
1→R
For(I,1,r₁)
 R*I→R
End
R
Return


(de prime? (N Lst)
   (let S (sqrt N)
      (for D Lst
         (T (> D S) T)
         (T (=0 (% N D)) NIL) ) ) )
(de primeseq (A B)
   (let (I 1 R)
      (nth
         (make
            (link 2)
            (while (> A (inc 'I 2))
               (and (prime? I (made)) (link I)) )
            (setq R (length (made)))
            (while (> B I)
               (and (prime? I (made)) (link I))
               (inc 'I 2) ) )
         (inc R) ) ) )
(de take (N)
   (let I 1
      (make
         (link 2)
         (do (dec N)
            (until (prime? (inc 'I 2) (made)))
            (link I) ) ) ) )

(prin "First 20 primes: ")
(println (take 20))
(prin "Primes between 100 and 150: ")
(println (primeseq 100 150))
(prinl
   "Number of primes between 7700 and 8000: "
   (length (primeseq 7700 8000)) )
(for N (10 100 1000 10000 100000 1000000)
   (prinl
      N
      "th prime: "
      (last (take N)) ) )


EnableExplicit
DisableDebugger
Define StartTime.i=ElapsedMilliseconds()

Procedure.b IsPrime(n.i)
  Define i.i=5
  If n<2 : ProcedureReturn #False : EndIf
  If n%2=0 : ProcedureReturn Bool(n=2) : EndIf
  If n%3=0 : ProcedureReturn Bool(n=3) : EndIf
  While i*i<=n
    If n%i=0 : ProcedureReturn #False : EndIf
    i+2
    If n%i=0 : ProcedureReturn #False : EndIf
    i+4
  Wend
  ProcedureReturn #True
EndProcedure

If OpenConsole("Extensible prime generator")
  Define c.i=0, n.i=2
  Print("First twenty: ")
  While c<20
    If IsPrime(n)
      Print(Str(n)+" ")
      c+1
    EndIf
    n+1
  Wend

  Print(~"\nBetween 100 and 150: ")
  For n=100 To 150
    If IsPrime(n)
      Print(Str(n)+" ")
    EndIf
  Next

  Print(~"\nNumber beween 7'700 and 8'000: ")
  c=0
  For n=7700 To 8000
    c+IsPrime(n)
  Next
  Print(Str(c))

  Print(~"\n10'000th prime: ")
  c=0 : n=1
  While c<10000
    n+1
    c+IsPrime(n)
  Wend
  Print(Str(n))
EndIf
Print(~"\nRuntime milliseconds: "+
      Str(ElapsedMilliseconds()-StartTime))
Input()


putch:	equ	2	; Write character
puts:	equ	9	; Write string
fopen:	equ	15	; Open file
fread:	equ	20	; Read record
setdma:	equ	26	; Set DMA address
fcb:	equ	5Ch	; FCB for first file on command line
	org	100h
	;;;	Open source file given on command line
	lxi	d,fcb
	mvi	c,fopen
	call	5	; Open file
	inr	a	; A=FF = error
	lxi	d,efile
	jz	s_out	; If error, print error message and stop
	lxi	d,src	; Start reading file at src
	;;;	Load the entire source file into memory
block:	push	d	; Set DMA address to next free location
	mvi	c,setdma
	call	5
	lxi	d,fcb	; Read 128-byte record
	mvi	c,fread
	call	5
	pop	d	; Advance pointer by 128 bytes
	lxi	h,128
	dad	d
	xchg
	dcr	a	; A=1 = end of file
	jz	block	; If not EOF, read next block
	xchg
	mvi	m,26	; Terminate last block with EOF byte to be sure
	lxi	b,src	; BC = source pointer
ins:	ldax	b	; Get current instruction
	cpi	26	; If EOF, stop
	rz
	ori	32	; Make lowercase
	push	b	; Keep source pointer
	cpi	'h'	; H=hello
	cz	hello
	cpi	'q'	; Q=quine
	cz	quine
	cpi	'9'	; 9=bottles
	cz	botls
	cpi	'+'	; +=increment
	cz	incr
	pop	b	; Restore source pointer
	inx	b	; Next instruction
	jmp 	ins
	;;;	Increment accumulator
incr:	lxi	h,accum
	inr	m
	ret
	;;;	Print "Hello, World"
hello:	lxi	d,histr
	jmp	s_out
	;;;	Print the source
quine:	lxi	h,src	; Pointer to source
qloop:	mov	a,m	; Load byte
	cpi	26	; Reached the end?
	rz		; If so, stop
	push	h	; Otherwise, keep pointer
	mov	e,a
	mvi	c,putch	; Print character
	call	5
	pop	h	; Restore pointer
	inx	h	; Next byte
	jmp	qloop
	;;;	99 bottles of beer
botls:	mvi	e,99	; 99 bottles
bverse:	call	nbeer	; _ bottle(s) of beer
	lxi	h,otw	; on the wall
	call	bstr
	call	nbeer	; _ bottle(s) of beer
	lxi	h,nl	; \r\n
	call	bstr
	lxi	h,tod	; Take one down and pass it around
	call	bstr
	dcr	e	; Decrement counter
	push	psw	; Keep status
	call 	nbeer	; _ bottle(s) of beer
	lxi	h,otw
	call	bstr	; on the wall
	lxi	h,nl	; \r\n
	call	bstr
	pop	psw	; restore status
	jnz	bverse	; If not at 0, next verse
	ret
nbeer:	push	d	; keep counter
	call	btlstr	; _ bottle(s)
	lxi	d,ofbeer
	call	s_out	; of beer
	pop 	d
	ret
bstr:	push	d	; keep counter
	xchg		; print string in HL
	call	s_out
	pop	d	; restore counter
	ret
	;;;	Print "N bottle(s)"
btlstr:	push	d	; Keep counter
	mov	a,e	; Print number
	call 	num
	lxi	d,bottle
	call	s_out	; Print " bottle"
	pop 	d	; Restore counter
	dcr	e	; If counter is 1,
	rz		; then stop,
	mvi	e,'s'	; otherwise, print S
	mvi	c,putch
	jmp	5
	;;;	Print number (0-99) in A
num:	ana	a	; If 0, print "no more"
	lxi	d,nomore
	jz	s_out
	mvi	b,'0'-1	; Tens digit
nloop:	inr	b	; Increment tens digit
	sui	10	; Subtract 10
	jnc	nloop
	adi	'0'+10	; Ones digit
	lxi	d,snum-1
	stax	d	; Store ones digit
	mov	a,b	; Tens digit zero?
	cpi	'0'
	jz	s_out	; If so, only print ones digit
	dcx	d	; Otherwise, store tens digit
	stax	d
s_out:	mvi	c,puts	; Print result
	jmp	5
efile:	db	'File error.$'
histr:	db	'Hello, world!',13,10,'$'
	db	'..'
snum:	db	'$'
nomore:	db	'No more$'
bottle:	db	' bottle$'
ofbeer:	db	' of beer$'
otw:	db	' on the wall',13,10,'$'
tod:	db	'Take one down and pass it around'
nl:	db	13,10,'$'
accum:	db	0 	; Accumulator
src:	equ	$	; Program source


PROC Run(CHAR ARRAY code)
  BYTE i,a
  CHAR c

  PrintF("Run ""%S""%E%E",code)
  a=0
  FOR i=1 TO code(0)
  DO
    c=code(i)
    IF c='q OR c='Q THEN
      PrintE(code)
    ELSEIF c='h OR c='H THEN
      PrintE("Hello, world!")
    ELSEIF c='9 THEN
      PrintE("99 bottles here...")
    ELSEIF c='+ THEN
      a==+1
    ELSE
      PrintF("Unrecognized character '%C'%E",c)
      Break()
    FI
  OD
  PrintF("%EAccumulator=%B%E",a)
RETURN

PROC Main()
  Run("9++hQ+q9H+")
RETURN


# HQ9+ interpreter

# execute an HQ9+ program in the code string - code is not case sensitive
hq9 := proc( code :: string ) is
    local hq9Accumulator := 0; # the HQ9+ accumulator
    local hq9Operations  :=    # table of HQ9+ operations and their implemntations
          [ "q" ~ proc() is print( code ) end
          , "h" ~ proc() is print( "Hello, world!" ) end
          , "9" ~ proc() is
                      local writeBottles := proc( bottleCount :: number, message :: string ) is
                                                print( bottleCount
                                                     & " bottle"
                                                     & if bottleCount <> 1 then "s " else " " fi
                                                     & message
                                                     )
                                            end;

                      for bottles from 99 to 1 by -1 do
                          writeBottles( bottles, "of beer on the wall" );
                          writeBottles( bottles, "of beer" );
                          print( "Take one down, pass it around," );
                          if bottles > 1 then
                              writeBottles( bottles - 1, "of beer on the wall." )
                          fi;
                          print()
                      od;
                      print( "No more bottles of beer on the wall." )
                  end
          , "+" ~ proc() is inc hq9Accumulator, 1 end
          ];
    for op in lower( code ) do
        if hq9Operations[ op ] <> null then
            hq9Operations[ op ]()
        else
            print( '"' & op & '" not implemented' )
        fi
    od
end;

# prompt for HQ9+ code and execute it, repeating until an empty code string is entered
scope
    local code;
    do
        write( "HQ9+> " );
        code := io.read();
        hq9( code )
    until code = ""
epocs;


[] '__A set : dip swap __A swap 2 compress collapse '__A set execute
    __A -1 extract nip ;  : nip swap drop ;  : tuck swap over ;
: -rot rot rot ; : 0= 0 == ; : 1+ 1 + ; : 1- 1 - ; : sum '+ reduce ;
: bi 'keep dip execute ;  : keep over 'execute dip ;

: fib dup 1 > if dup 1- fib swap 2 - fib + then ;
: fib  dup 1 > if "1- fib" "2 - fib" bi + then ;


function pow($a, [int]$b) {
    if ($b -eq -1) { return 1/$a }
    if ($b -eq 0)  { return 1 }
    if ($b -eq 1)  { return $a }
    if ($b -lt 0) {
        $rec = $true # reciprocal needed
        $b = -$b
    }

    $result = $a
    2..$b | ForEach-Object {
        $result *= $a
    }

    if ($rec) {
        return 1/$result
    } else {
        return $result
    }
}


:- arithmetic_function((^^)/2).
:- op(200, xfy, user:(^^)).


Procedure powI(base, exponent)
  Protected i, result.d
  If exponent < 0
    If base = 1
      result = 1
    EndIf
    ProcedureReturn result
  EndIf
  result = 1
  For i = 1 To exponent
    result * base
  Next
  ProcedureReturn result
EndProcedure

Procedure.f powF(base.f, exponent)
  Protected i, magExponent = Abs(exponent), result.d
  If base <> 0
    result = 1.0
    If exponent <> 0
      For i = 1 To magExponent
        result * base
      Next
      If exponent < 0
        result = 1.0 / result
      EndIf
    EndIf
  EndIf
  ProcedureReturn result
EndProcedure

If OpenConsole()
  Define x, a.f, exp

  x = Random(10) - 5
  a = Random(10000) / 10000 * 10
  For exp = -3 To 3
    PrintN(Str(x) + " ^ " + Str(exp) + " = " + Str(powI(x, exp)))
    PrintN(StrF(a) + " ^ " + Str(exp) + " = " + StrF(powF(a, exp)))
    PrintN("--------------")
  Next

  Print(#CRLF$ + #CRLF$ + "Press ENTER to exit")
  Input()
  CloseConsole()
EndIf


#lang racket
;; Using the prime functions from:
(require math/number-theory)

(displayln "Show the first twenty primes.")
(next-primes 1 20)

(displayln "Show the primes between 100 and 150.")
;; Note that in each of the in-range filters I "add1" to the stop value, so that (in this case) 150 is
;; considered. I'm pretty sure it's not prime... but technology moves so fast nowadays that things
;; might have changed!
(for/list ((i (sequence-filter prime? (in-range 100 (add1 150))))) i)

(displayln "Show the number of primes between 7,700 and 8,000.")
;; (for/sum (...) 1) counts the values in a sequence
(for/sum ((i (sequence-filter prime? (in-range 7700 (add1 8000))))) 1)

(displayln "Show the 10,000th prime.")
(nth-prime (sub1 10000)) ; (nth-prime 0) => 2

;; If a languages in-built prime generator is extensible or is guaranteed to generate primes up to a
;; system limit, (2^31 or memory overflow for example), then this may be used as long as an
;; explanation of the limits of the prime generator is also given. (Which may include a link
;; to/excerpt from, language documentation).
;;
;; Full details in:
;; [[http://docs.racket-lang.org/math/number-theory.html?q=prime%3F#%28part._primes%29]]
;; When reading the manual, note that "Integer" and "Natural" are unlimited (or bounded by whatever
;; big number representation there is (and the computational complexity of the work being asked).
(define 2^256 (expt 2 256))
2^256
(next-prime 2^256)
;; (Oh, and this is a 64-bit laptop, I left my 256-bit PC in the office.)


# the increment-only accumulator #
INT hq9accumulator := 0;

# interpret a HQ9+ code string #
PROC hq9 = ( STRING code )VOID:
    FOR i TO UPB code
    DO
        CHAR   op = code[ i ];
        IF op = "Q" OR op = "q"
        THEN
            # display the program #
            print( ( code, newline ) )
        ELIF op = "H" OR op = "h"
        THEN
            print( ( "Hello, world!", newline ) )
        ELIF op = "9"
        THEN
            # 99 bottles of beer #
            FOR bottles FROM 99 BY -1 TO 1 DO
                 STRING bottle count = whole( bottles, 0 ) + IF bottles > 1 THEN " bottles" ELSE " bottle" FI;
                 print( ( bottle count, " of beer on the wall", newline ) );
                 print( ( bottle count, " bottles of beer.",    newline ) );
                 print( ( "Take one down, pass it around,",     newline ) );
                 IF bottles > 1
                 THEN
                     print( ( whole( bottles - 1, 0 ), " bottles of beer on the wall.", newline, newline ) )
                 FI
            OD;
            print( ( "No more bottles of beer on the wall.", newline ) )
        ELIF op = "+"
        THEN
            # increment the accumulator #
            hq9accumulator +:= 1
        ELSE
            # unimplemented operation #
            print( ( """", op, """ not implemented", newline ) )
        FI
    OD;

# test the interpreter #
BEGIN
    STRING code;
    print( ( "HQ9+> " ) );
    read( ( code, newline ) );
    hq9( code )
END


begin

    procedure writeBottles( integer value bottleCount ) ;
        begin
            write( bottleCount, " bottle" );
            if bottleCount not = 1 then writeon( "s " ) else writeon( " " );
        end writeBottles ;

    procedure hq9 ( string(32) value code   % code to execute %
                  ; integer    value length % length of code  %
                  ) ;
        for i := 0 until length - 1 do begin
            string(1) op;

            % the increment-only accumulator %
            integer   hq9accumulator;

            hq9accumulator := 0;
            op             := code(i//1);

            if op = "Q" or op = "q" then write( code )
            else if op = "H" OR op = "h" then write( "Hello, World!" )
            else if op = "9" then begin
                % 99 bottles of beer %
                i_w := 1; s_w := 0;
                for bottles := 99 step -1 until 1 do begin
                    writeBottles( bottles ); writeon( "of beer on the wall" );
                    writeBottles( bottles ); writeon( "of beer" );;
                    write( "Take one down, pass it around," );
                    if bottles > 1 then begin
                        writeBottles( bottles - 1 ); writeon( "of beer on the wall." )
                    end;
                    write()
                end;
                write( "No more bottles of beer on the wall." )
                end
            else if op = "+" then hq9accumulator := hq9accumulator + 1
            else write( """", op, """ not implemented" )
        end hq9 ;

    % test the interpreter %
    begin
        string(32) code;
        integer    codeLength;
        write( "HQ9+> " );
        read( code );
        codeLength := 31;
        while codeLength >= 0 and code(codeLength//1) = " " do codeLength := codeLength - 1;
        hq9( code, codeLength + 1 )
    end
end.


val .fibonacci = f if(.x < 2: .x ; self(.x - 1) + self(.x - 2))

writeln map .fibonacci, series 2..20


MULTIPLY = lambda x, y: x*y

class num(float):
    # the following method has complexity O(b)
    # rather than O(log b) via the rapid exponentiation
    def __pow__(self, b):
        return reduce(MULTIPLY, [self]*b, 1)

# works with ints as function or operator
print num(2).__pow__(3)
print num(2) ** 3

# works with floats as function or operator
print num(2.3).__pow__(8)
print num(2.3) ** 8


  [ $ "bigrat.qky" loadfile ] now!

  forward                         is **    (   n n --> n   )

  [ dup 1 < iff
     [ 2drop 1 ] done
    dup 1 & iff
        [ 1 - dip dup ** * ]
    else
      [ 1 >> dip [ dup * ]
        ** ] ]              resolves **    (   n n --> n   )

  forward                         is (v**) ( n/d n --> n/d )

  [ dup 0 = iff
      [ drop 2drop 1 n->v ]
      done
    dup 1 & iff
      [ 1 - dip 2dup (v**)
        v* ]
    else
      [ 1 >>
        dip [ 2dup v* ]
        (v**) ] ]           resolves (v**) ( n/d n --> n/d )

  [ dup 0 < iff
      [ abs (v**) 1/v ]
    else (v**) ]                  is v**   ( n/d n --> n/d )

say "The 10th power of 2 is: "
2 10 ** echo cr cr

say "The -10th power of 2.5 is: "
$ "2.5" $->v drop -10 v** 20 point$ echo$


# Method
pow <- function(x, y)
{
   x <- as.numeric(x)
   y <- as.integer(y)
   prod(rep(x, y))
}
#Operator
"%pow%" <- function(x,y) pow(x,y)

pow(3, 4)    # 81
2.5 %pow% 2  # 6.25


#lang racket
(define (^ base expt)
  (for/fold ((acum 1))
    ((i (in-range expt)))
    (* acum base)))

(^ 5 2) ; 25
(^ 5.0 2) ; 25.0


' Factorial
FUNCTION factorial(NUMBER n) TYPE NUMBER
    IF n <= 1 THEN
        RETURN 1
    ELSE
        RETURN n * factorial(n - 1)
    ENDIF
END FUNCTION

n = VAL(TOKEN$(ARGUMENT$, 2))
PRINT n, factorial(n) FORMAT "%ld! = %ld\n"


my @primes = lazy gather for 1 .. * { .take if .is-prime }

say "The first twenty primes:\n   ", "[{@primes[^20].fmt("%d", ', ')}]";
say "The primes between 100 and 150:\n   ", "[{@primes.&between(100, 150).fmt("%d", ', ')}]";
say "The number of primes between 7,700 and 8,000:\n   ", +@primes.&between(7700, 8000);
say "The 10,000th prime:\n   ", @primes[9999];

sub between (@p, $l, $u) {
    gather for @p { .take if $l < $_ < $u; last if $_ >= $u }
}


100 INPUT "HQ9+ : "; I$
110 LET J$ = I$ + CHR$(13)
120 LET H$ = "HELLO, WORLD!"
130 LET B$ = "BOTTLES OF BEER"
140 LET W$ = " ON THE WALL"
150 LET W$ = W$ + CHR$(13)
160 FOR I = 1 TO LEN(I$)
170     LET C$ = MID$(J$, I, 1)
180     IF C$ = "H" THEN PRINT H$
190     IF C$ = "Q" THEN PRINT I$
200     LET A = A + (C$ = "+")
210     IF C$ <> "9" THEN 280
220     FOR B = 99 TO 1 STEP -1
230         PRINT B " " B$ W$ B " " B$
240         PRINT "TAKE ONE DOWN, ";
250         PRINT "PASS IT AROUND"
260         PRINT B - 1 " " B$ W$
270     NEXT B
280 NEXT I


hq9: function [source][
    acc: 0
    loop split source 'ch [
        case [(lower ch)=]
            when? ["h"]-> print "Hello, world!"
            when? ["q"]-> print source
            when? ["9"]-> print "99 bottles here ..."
            when? ["+"]-> acc: acc+1
            else       []

    ]
    return acc
]

acc: hq9 {+qhp;+9Q}
print ["accumulator:" acc]


; http://www.autohotkey.com/forum/viewtopic.php?p=356268#356268

testCode := "hq9+HqQ+Qq"

MsgBox % RunHQ9Plus(testCode)

;---------------------------------

RunHQ9Plus(input)
{
  Loop, Parse, input
    If ( A_LoopField = "+" )
      acc++
    Else If ( A_LoopField = "H" )
      output .= "Hello, world!`n"
    Else If ( A_LoopField = "Q" )
      output .= input "`n"
    Else If ( A_LoopField = "9" )
      Loop, 99
      {
        ; following 4 lines could be only 1 long line
        output .= (99+1-A_Index) " bottles of beer on the wall`n"
        output .= (99+1-A_Index) " bottles of beer`n"
        output .= "Take one down, pass it around`n"
        output .= (99-A_Index) " bottles of beer on the wall`n`n"
      }
  Return output
}


define fibonacci(n::integer) => {

	#n < 1 ? return false

	local(
		swap	= 0,
		n1		= 0,
		n2		= 1
	)

	loop(#n) => {
        #swap = #n1 + #n2;
        #n2 = #n1;
        #n1 = #swap;
	}
	return #n1

}

fibonacci(0) //->output false
fibonacci(1) //->output 1
fibonacci(2) //->output 1
fibonacci(3) //->output 2


subset Natural of Int where { $^n >= 0 }

multi pow (0,     0)            { fail '0**0 is undefined' }
multi pow ($base, Natural $exp) { [*] $base xx $exp }
multi pow ($base, Int $exp)     { 1 / pow $base, -$exp }

sub infix:<***> ($a, $b) { pow $a, $b }

# Testing

say pow .75, -5;
say .75 *** -5;


: pow  ( bp-n ) 1 swap [ over * ] times nip ;


/*REXX program  computes and displays  various   (integer)   exponentiations.           */
                                                 say center('digits='digits(), 79, "─")
say 'iPow(17, 65)  is:'
say  iPow(17, 65)
say

say 'iPow(0, -3)  is:'
say  iPow(0, -3)
say

say 'iPow(8, 0)  is:'
say  iPow(8, 0)
say

numeric digits 12;                               say center('digits='digits(), 79, "─")
say 'iPow(2, -10)  is:'
say  iPow(2, -10)
say

numeric digits 30;                               say center('digits='digits(), 79, "─")
say 'iPow(-3.1415926535897932384626433, 3)  is:'
say  iPow(-3.1415926535897932384626433, 3)
say

numeric digits 60;                               say center('digits='digits(), 79, "─")
say 'iPow(5, 70)  is:'
say  iPow(5, 70)
say

numeric digits 100;                              say center('digits='digits(), 79, "─")
say 'iPow(17, 65)  is:'
say  iPow(17, 65)
say

numeric digits 1000;                             say center('digits='digits(), 79, "─")
say 'iPow(2, 1000)  is:'
say  iPow(2, 1000)
exit                                             /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
errMsg: say;     say '***error***';     say;     say arg(1);     say;     say;     exit 13
/*──────────────────────────────────────────────────────────────────────────────────────*/
iPow:   procedure;  parse arg x 1 _,p;           #args= arg()  /*_:   is a copy of  X.  */
        if #args<2            then call errMsg  "not enough arguments specified"
        if #args>2            then call errMsg  "too many arguments specified"
        if \datatype(x, 'N')  then call errMsg  "1st arg isn't numeric:"         x
        if \datatype(p, 'W')  then call errMsg  "2nd arg isn't an integer:"      p
        if p=0                then return 1                    /*handle powers of zero. */
        if x=0  |  x=1        then return x                    /*handle special cases.  */
               do abs(p) - 1;      _= _ * x;   end             /*perform exponentiation */
        if p<0                then _= 1 / _                    /*process its reciprocal.*/
        return _


factorial()
{
  if [ $1 -le 1 ]
  then
    echo 1
  else
    result=$(factorial $[$1-1])
    echo $((result*$1))
  fi
}


Red [Description: "Prime checker/generator/counter"]

context [
    poke noprime: make bitset! 3 1 true
    top: 2

    noprimes: function [n [integer!] /extern top][
        either top < n [
            n: n + 100
            r: 2
            while [r * r <= n][
                repeat q n / r - 1 [poke noprime q + 1 * r true]
                until [not pick noprime r: r + 1]
            ]
            self/top: n
        ][top]
    ]

    set 'prime? func [
        "Check whether number is prime or return required prime"
        n [integer!]
        /next "Return next closest prime to given number"
        /last "Return last closest prime to given number, or number itself if prime"
        /Nth  "Return Nth prime"
    ][
        noprimes case [
            Nth [to integer! n * 12 ]
            next [n + 100]
            true [n]
        ]
        case [
            next [until [not noprime/(n: n + 1)] n]
            last [while [noprime/:n][n: n - 1] n]
            Nth  [
                cnt: i: 0
                while [cnt < n][
                    until [not noprime/(i: i + 1)]
                    cnt: cnt + 1
                ]
                i
            ]
            true [not noprime/:n]
        ]
    ]

    set 'primes function [
        "Return (number of) primes in given range"
        n [integer!]
        /from     "Start considering primes from `start`"
            start "Default 1"
        /list     "First argument is interpreted as number of primes to list"
        /count    "Count primes from `start`"
    ][
        start: any [start 1]
        either list [
            noprimes start + (n * 12)
        ][
            set [start n] sort reduce [n start]
            noprimes start + n
        ]
        case [
            list [
                start: start - 1
                collect [
                    loop n [
                        until [not noprime/(start: start + 1)]
                        keep start
                    ]
                ]
            ]
            count [
                cnt: 0
                repeat i n - start + 1 [
                    j: i - 1
                    if not noprime/(j + start) [cnt: cnt + 1]
                ]
                cnt
            ]
            true [
                collect [
                    repeat i n - start + 1 [
                        j: i - 1
                        if not noprime/(j: j + start) [keep j]
                    ]
                ]
            ]
        ]
    ]
]


/*REXX program calculates and displays primes using an extendible prime number generator*/
parse arg f .;    if f==''  then f= 20           /*allow specifying number for  1 ──► F.*/
_i= ' (inclusive) ';  _b= 'between ';  _tnp= 'the number of primes' _b;  _tn= 'the primes'
call primes f;      do j=1  for f;      $= $ @.j;    end  /*j*/
                                        say 'the first '    f    " primes are: "        $
                                        say
call primes -150;   do j=100  to 150;   if !.j==1  then $= $ j;  end  /*j*/
                                        say _tn  _b  '100  to  150'  _i  "are: "        $
                                        say
call primes -8000;  do j=7700  to 8000; if !.j==1  then $= $ j;  end  /*j*/
                                        say _tnp  '7,700  and  8,000'  _i  "is: " words($)
                                        say
call primes 10000
                                        say 'the 10,000th prime is: '    @.10000
exit 0                                           /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
primes: procedure expose !. @. $ #;      parse arg H,,$;           Hneg= H<0;    H= abs(H)
        if symbol('#')=="LIT"  then call .primI  /*1st time here?  Then initialize stuff*/
        if Hneg  then  if  H<[email protected].#  then return   /*do we have a high enough  P  already?*/
                                   else nop      /*this is used to match the above THEN.*/
                 else  if  H<=#    then return   /*are there enough primes currently ?  */
                                                 /* [↓]  gen more primes within range.  */
          do [email protected].#+2   by 2; parse var j '' -1 _ /*find primes until have   H   Primes. */
          if     _==5  then iterate              /*is the right─most digit a 5  (five)? */
          if j// 3==0  then iterate              /*is  J  divisible by  three?  (& etc.)*/
          if j// 7==0  then iterate;  if j//11==0  then iterate; if j//13==0  then iterate
          if j//17==0  then iterate;  if j//19==0  then iterate; if j//23==0  then iterate
          if j//29==0  then iterate;  if j//31==0  then iterate; if j//37==0  then iterate
          if j//41==0  then iterate;  if j//43==0  then iterate; if j//47==0  then iterate
          if j//53==0  then iterate;  if j//59==0  then iterate; if j//61==0  then iterate
          if j//67==0  then iterate;  if j//71==0  then iterate; if j//73==0  then iterate
          if j//79==0  then iterate;  if j//83==0  then iterate; if j//89==0  then iterate
          if j//97==0  then iterate;  if j//101==0 then iterate; if j//103==0 then iterate
          x= j;          r= 0;  q= 1;   do while q<=x;  q= q*4;  end  /*R:  the sqrt(J).*/
                  do while q>1; q=q%4; _=x-r-q; r=r%2; if _>=0 then do;x=_;r=r+q; end; end
                    do [email protected].lowP   while @.k<=r   /*÷ by the known odd primes (hardcoded)*/
                    if j//@.k==0  then iterate j /*J ÷ by a prime?  Then not prime.  ___*/
                    end   /*k*/                  /* [↑]  divide by odd primes up to √ J */
          #= # + 1                               /*bump the number of primes found.     */
          @.#= j;                       !.j= 1   /*assign to sparse array;  prime²;  P#.*/
          if Hneg  then if H<[email protected].#  then leave    /*is this a high enough prime?         */
                                   else nop      /*used to match the above  THEN.       */
                   else if H<=#    then leave    /*have enough primes been generated?   */
          end   /*j*/                            /* [↑]  keep generating until enough.  */
        return                                   /*return to invoker with more primes.  */
/*──────────────────────────────────────────────────────────────────────────────────────*/
.primI: !.=0;   @.=0;                            /*!.x= a prime or not;  @.n= Nth prime.*/
        L= 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 101 103
                do #=1  for words(L);   p= word(L, #);   @.#= p;   !.p=1;    end   /*#*/
        #= # - 1;       @.lowP= #;      return   /*#:   # primes;  @.lowP:   start of ÷ */


# Intérprete de HQ9+

global codigo
codigo = ""

function HQ9plus(codigo)
	acumulador = 0
	HQ9plus1 = ""
	for cont = 1 to length(codigo)
		op =  upper(mid(codigo, cont, 1))
		begin case
			case op = "H"
				HQ9plus1 = HQ9plus1 + "Hello, world!"
			case op = "Q"
				HQ9plus1 = HQ9plus1 + codigo
			case op = "9"
				for botellas = 99 to 1 step -1
					HQ9plus1 = HQ9plus1 + string(botellas) + " bottle"
					if (botellas > 1) then HQ9plus1 = HQ9plus1 + "s"
					HQ9plus1 = HQ9plus1 + " of beer on the wall, " + string(botellas) + " bottle"
					if (botellas > 1) then HQ9plus1 = HQ9plus1 + "s"
					HQ9plus1 = HQ9plus1 + " of beer,"  + chr(13) + chr(10) + "Take one down, pass it around, " + string(botellas - 1) + " bottle"
					if (botellas > 2) then HQ9plus1 = HQ9plus1 + "s"
					HQ9plus1 = HQ9plus1 + " of beer on the wall." + chr(13) + chr(10) + chr(10)
				next botellas
				HQ9plus1 = HQ9plus1 + "No more bottles of beer on the wall, no more bottles of beer." + chr(13) + chr(10) + "Go to the store and buy some more, 99 bottles of beer on the wall."
			case op = "+"
				acumulador = (acumulador + 1)
			case op = "E"
				end
		end case
		if mid(codigo, cont, 1) <> "+" then
			HQ9plus1 = HQ9plus1 + chr(13) + chr(10)
		end if
	next cont
	HQ9plus = left(HQ9plus1, (length(HQ9plus1) - 2))
end function

cls
do
	input codigo
	print HQ9plus(codigo): print
until false
end


      PROChq9plus("hq9+HqQ+Qq")
      END

      DEF PROChq9plus(code$)
      LOCAL accumulator%, i%, bottles%
      FOR i% = 1 TO LEN(code$)
        CASE MID$(code$, i%, 1) OF
          WHEN "h","H": PRINT "Hello, world!"
          WHEN "q","Q": PRINT code$
          WHEN "9":
            bottles% = 99
            WHILE bottles%
              PRINT ;bottles% " bottles of beer on the wall, ";
              PRINT ;bottles% " bottles of beer,"
              bottles% -= 1
              PRINT "Take one down, pass it around, ";
              PRINT ;bottles% " bottles of beer on the wall."
            ENDWHILE
          WHEN "+": accumulator% += 1
        ENDCASE
      NEXT i%
      ENDPROC


Pl ← {(𝕩≠1)/"s"}
Lwr ← +⟜(32×1="A["⊸⍋)
nn ← {(•Fmt 𝕨)∾" "∾𝕩}´¨∾{
  ⟨
    ⟨𝕩,"bottle"∾(Pl 𝕩)∾" of beer on the wall"⟩
    ⟨𝕩,"bottle"∾(Pl 𝕩)∾" of beer"⟩
    ⟨"Take one down, pass it around"⟩
    ⟨𝕩-1,"bottle"∾(Pl 𝕩-1)∾" of beer on the wall"⟩
  ⟩
}¨⌽1+↕99

HQ9 ← {
  out ← ⟨⟨"Hello, World!"⟩, ⟨𝕩⟩, nn⟩
  acc ← +´'+'=𝕩
  ∾out⊏˜3⊸≠⊸/"hq9"⊐Lwr 𝕩
}

•Out¨HQ9 •[email protected]


void runCode(const char *code)
{
    int c_len = strlen(code);
    int i, bottles;
    unsigned accumulator=0;
    for(i=0;i<c_len;i++)
    {
        switch(code[i])
        {
            case 'Q':
                printf("%s\n", code);
                break;

            case 'H':
                printf("Hello, world!\n");
                break;

            case '9':
                //Nice bottles song alg. from RC :)
                bottles = 99;
                do {
                    printf("%d bottles of beer on the wall\n", bottles);
                    printf("%d bottles of beer\n", bottles);
                    printf("Take one down, pass it around\n");
                    printf("%d bottles of beer on the wall\n\n", --bottles);
                } while( bottles > 0 );
                break;

            case '+':
                //Am I the only one finding this one weird? :o
                accumulator++;
                break;
        }
    }
};


fibo := {
  takes '[n].
  if { n <= 1. } then {
    n.
  } else {
    fibo (n - 1) + fibo (n - 2).
  }.
}.


see "11^5 = " + ipow(11, 5) + nl
see "pi^3 = " + fpow(3.14, 3) + nl

func ipow a, b
     p2 = 1
     for i = 1 to 32
         p2 *= p2
         if b < 0  p2 *= a ok
         b = b << 1
     next
     return p2

func fpow a, b
     p = 1
     for i = 1 to 32
         p *= p
         if b < 0  p *= a ok
         b = b << 1
     next
     return p


class Numeric
  def pow(m)
    raise TypeError, "exponent must be an integer: #{m}" unless m.is_a? Integer
    puts "pow!!"
    Array.new(m, self).reduce(1, :*)
  end
end

p 5.pow(3)
p 5.5.pow(3)
p 5.pow(3.1)


extern crate num;
use num::traits::One;
use std::ops::Mul;

fn pow<T>(mut base: T, mut exp: usize) -> T
    where T: Clone + One + Mul<T, Output=T>
{
    if exp == 0 { return T::one() }
    while exp & 1 == 0 {
        base = base.clone() * base;
        exp >>= 1;
    }
    if exp == 1 { return base }
    let mut acc = base.clone();

    while exp > 1 {
        exp >>= 1;
        base = base.clone() * base;
        if exp & 1 == 1 {
            acc = acc * base.clone();
        }
    }
    acc
}


FUNCTION factorial (n AS Integer) AS Integer
    DIM f AS Integer, i AS Integer
    f = 1
    FOR  i = 2 TO n
        f = f*i
    NEXT i
    factorial = f
END FUNCTION


see "first twenty primes : "
i = 1
nr = 0
while i <= 20
      nr += 1
      if isPrime(nr) see " " + nr i += 1 ok
end

see "primes between 100 and 150 : "
for nr = 100 to 150
    if isPrime(nr) see " " + nr ok
next
see nl

see "primes between 7,700 and 8,000 : "
i = 0
for nr = 7700 to 8000
    if isPrime(nr) i += 1 ok
next
see i + nl

see "The 10,000th prime : "
i = 1
nr = 0
while i <= 10000
      nr += 1
      if isPrime(nr) i += 1 ok
end
see nr + nl

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


require "prime"

puts Prime.take(20).join(", ")
puts Prime.each(150).drop_while{|pr| pr < 100}.join(", ")
puts Prime.each(8000).drop_while{|pr| pr < 7700}.count
puts Prime.take(10_000).last


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

class Program
{
    static void RunCode(string code)
    {
        int accumulator = 0;
        var opcodes = new Dictionary<char, Action>
        {
            {'H', () => Console.WriteLine("Hello, World!"))},
            {'Q', () => Console.WriteLine(code) },
            {'9', () => Console.WriteLine(Enumerable.Range(1,100).Reverse().Select(n => string.Format("{0} bottles of beer on the wall\n{0} bottles of beer\nTake one down, pass it around\n{1} bottles of beer on the wall\n", n, n-1)).Aggregate((a,b) => a + "\n" + b))},
            {'+', () => accumulator++ }
        }

        foreach(var c in code)
            opcodes[c]();
    }
}


void runCode(string code)
{
    int c_len = code.length();
    unsigned accumulator=0;
    int bottles;
    for(int i=0;i<c_len;i++)
    {
        switch(code[i])
        {
            case 'Q':
                cout << code << endl;
                break;

            case 'H':
                cout << "Hello, world!" << endl;
                break;

            case '9':
                //Nice bottles song alg. from RC :)
                bottles = 99;
                do {
                    cout << bottles << " bottles of beer on the wall" << endl;
                    cout << bottles << " bottles of beer" << endl;
                    cout << "Take one down, pass it around" << endl;
                    cout << --bottles << " bottles of beer on the wall" << endl << endl;
                } while( bottles > 0 );
                break;

            case '+':
                //Am I the only one finding this one weird? :o
                accumulator++;
                break;
        }
    }
};


-- Our first implementation is the usual recursive definition:
def fib1 : ℕ → ℕ
| 0       := 0
| 1       := 1
| (n + 2) := fib1 n + fib1 (n + 1)

-- We can give a second more efficient implementation using an auxiliary function:
def fib_aux : ℕ → ℕ → ℕ → ℕ
| 0 a b       := b
| (n + 1) a b := fib_aux n (a + b) a

def fib2 : ℕ → ℕ
| n := fib_aux n 1 0

-- Use #eval to check computations:
#eval fib1 20
#eval fib2 20


object Exponentiation {
  import scala.annotation.tailrec

  @tailrec def powI[N](n: N, exponent: Int)(implicit num: Integral[N]): N = {
    import num._
    exponent match {
      case 0 => one
      case _ if exponent % 2 == 0 => powI((n * n), (exponent / 2))
      case _ => powI(n, (exponent - 1)) * n
    }
  }

  @tailrec def powF[N](n: N, exponent: Int)(implicit num: Fractional[N]): N = {
    import num._
    exponent match {
      case 0 => one
      case _ if exponent < 0 => one / powF(n, exponent.abs)
      case _ if exponent % 2 == 0 => powF((n * n), (exponent / 2))
      case _ => powF(n, (exponent - 1)) * n
    }
  }

  class ExponentI[N : Integral](n: N) {
    def \u2191(exponent: Int): N = powI(n, exponent)
  }

  class ExponentF[N : Fractional](n: N) {
    def \u2191(exponent: Int): N = powF(n, exponent)
  }

  object ExponentI {
    implicit def toExponentI[N : Integral](n: N): ExponentI[N] = new ExponentI(n)
  }

  object ExponentF {
    implicit def toExponentF[N : Fractional](n: N): ExponentF[N] = new ExponentF(n)
  }

  object Exponents {
    implicit def toExponent(n: Int): ExponentI[Int] = new ExponentI(n)
    implicit def toExponent(n: Double): ExponentF[Double] = new ExponentF(n)
  }
}


print "enter a number, n = ";
input n
print string(n) + "! = " + string(factorial(n))

function factorial(n)
   factorial = 1
   if n > 0 then
      for p = 1 to n
      factorial *= p
      next p
   end if
end function


mod pagesieve;

use pagesieve::{count_primes_paged, primes_paged};

fn main() {
    println!("First 20 primes:\n {:?}",
             primes_paged().take(20).collect::<Vec<_>>());
    println!("Primes between 100 and 150:\n {:?}",
             primes_paged().skip_while(|&x| x < 100)
                           .take_while(|&x| x < 150)
                           .collect::<Vec<_>>());
    let diff = count_primes_paged(8000) - count_primes_paged(7700);
    println!("There are {} primes between 7,700 and 8,000", diff);
    // rust enumerations are zero base, so need to subtract 1!!!
    println!("The 10,000th prime is {}", primes_paged().nth(10_000 - 1).unwrap());
}


$ include "seed7_05.s7i";

const func boolean: isPrime (in integer: number) is func
  result
    var boolean: prime is FALSE;
  local
    var integer: count is 2;
  begin
    if number = 2 then
      prime := TRUE;
    elsif number > 2 then
      while number rem count <> 0 and count * count <= number do
        incr(count);
      end while;
      prime := number rem count <> 0;
    end if;
  end func;

var integer: currentPrime is 1;
var integer: primeNum is 0;

const func integer: getPrime is func
  result
    var integer: nextPrime is 0;
  begin
    repeat
      incr(currentPrime);
    until isPrime(currentPrime);
    nextPrime := currentPrime;
    incr(primeNum);
  end func;

const proc: main is func
  local
    var integer: aPrime is 0;
    var integer: count is 0;
  begin
    write("First twenty primes:");
    while primeNum < 20 do
      write(" " <& getPrime);
    end while;
    writeln;
    repeat
      aPrime := getPrime;
    until aPrime >= 100;
    write("Primes between 100 and 150:");
    while aPrime <= 150 do
      write(" " <& aPrime);
      aPrime := getPrime;
    end while;
    writeln;
    repeat
      aPrime := getPrime;
    until aPrime >= 7700;
    while aPrime <= 8000 do
      incr(count);
      aPrime := getPrime;
    end while;
    writeln("Number of primes between 7,700 and 8,000: " <& count);
    repeat
      aPrime := getPrime;
    until primeNum = 9999; # discard up to and including the 9,999 prime!
    writeln("The 10,000th prime: " <& getPrime);
  end func;


shared void run() {

	void eval(String code) {

		variable value accumulator = 0;

		for(c in code.trimmed.lowercased) {
			switch(c)
			case('h') {
				print("Hello, world!");
			}
			case('q') {
				print(code);
			}
			case('9') {
				function bottles(Integer i) =>
						switch(i)
						case(0) "No bottles"
						case(1) "One bottle"
						else "``i`` bottles";
				for(i in 99..1) {
					print("``bottles(i)`` of beer on the wall,
					       ``bottles(i)`` of beer,
					       take one down and pass it around,
					       ``bottles(i - 1)`` of beer on the wall!");
				}
			}
			case('+') {
				accumulator++;
			}
			else {
				print("syntax error");
			}
		}
	}

	eval("hq9+");
}


(ns anthony.random.hq9plus
  (:require [clojure.string :as str]))

(defn bottles []
  (loop [bottle 99]
    (if (== bottle 0)
      ()
      (do
        (println (str bottle " bottles of beer on the wall"))
        (println (str bottle " bottles of beer"))
        (println "Take one down, pass it around")
        (println (str bottle " bottles of beer on the wall"))
        (recur (dec bottle))))))

(defn execute-hq9plus [& commands]
  (let [accumulator (atom 0)]
    (loop [pointer 0]
      (condp = (nth commands pointer)
        \H (println "Hello, world!")
        \Q (println (str/join commands))
        \9 (bottles)
        \+ (reset! accumulator (inc @accumulator)))
      (if-not (= (inc pointer) (count commands)) (recur (inc pointer))))))


package Parameter is
   X: Natural := 0;
   Y: Natural;
end Parameter;


(define (^ base exponent)
  (define (*^ exponent acc)
    (if (= exponent 0)
        acc
        (*^ (- exponent 1) (* acc base))))
  (*^ exponent 1))

(display (^ 2 3))
(newline)
(display (^ (/ 1 2) 3))
(newline)
(display (^ 0.5 3))
(newline)
(display (^ 2+i 3))
(newline)


const func integer: intPow (in var integer: base, in var integer: exponent) is func
  result
    var integer: result is 0;
  begin
    if exponent < 0 then
      raise(NUMERIC_ERROR);
    else
      if odd(exponent) then
        result := base;
      else
        result := 1;
      end if;
      exponent := exponent div 2;
      while exponent <> 0 do
        base *:= base;
        if odd(exponent) then
          result *:= base;
        end if;
        exponent := exponent div 2;
      end while;
    end if;
  end func;


func expon(_, {.is_zero}) { 1 }

func expon(base, exp {.is_neg}) {
    expon(1/base, -exp)
}

func expon(base, exp {.is_int}) {

  var c = 1
  while (exp > 1) {
    c *= base if exp.is_odd
    base *= base
    exp >>= 1
  }

  return (base * c)
}

say expon(3, 10)
say expon(5.5, -3)


@echo off
set /p x=
set /a fs=%x%-1
set y=%x%
FOR /L %%a IN (%fs%, -1, 1) DO SET /a y*=%%a
if %x% EQU 0 set y=1
echo %y%
pause
exit


say ("First 20: ", 20.nth_prime.primes.join(' '))
say ("Between 100 and 150: ", primes(100,150).join(' '))
say (prime_count(7700,8000), " primes between 7700 and 8000")
say ("10,000th prime: ", nth_prime(10_000))


% This program uses the "get_argv" function from PCLU's "useful.lib"

hq9plus = cluster is load, run
    rep = string
    own po: stream := stream$primary_output()

    bottles = proc (n: int) returns (string)
        if n=0 then return("No more bottles ")
        elseif n=1 then return("1 bottle ")
        else return(int$unparse(n) || " bottles ")
        end
    end bottles

    beer = proc ()
        for i: int in int$from_to_by(99,1,-1) do
            stream$putl(po, bottles(i) || "of beer on the wall,")
            stream$putl(po, bottles(i) || "of beer,")
            stream$puts(po, "Take ")
            if i=1
                then stream$puts(po, "it")
                else stream$puts(po, "one")
            end
            stream$putl(po, " down and pass it around,")
            stream$putl(po, bottles(i-1) || "of beer on the wall!\n")
        end
    end beer

    quine = proc (c: rep) stream$puts(po, c) end quine
    hello = proc () stream$putl(po, "Hello, world!") end hello

    load = proc (fn: file_name) returns (cvt) signals (not_possible(string))
        prog: array[char] := array[char]$[]
        s: stream := stream$open(fn, "read") resignal not_possible
        while true do
            array[char]$addh(prog, stream$getc(s))
            except when end_of_file: break end
        end
        stream$close(s)
        return(rep$ac2s(prog))
    end load

    run = proc (prog: cvt) returns (int)
        acc: int := 0
        for c: char in rep$chars(prog) do
            if     c='h' | c='H' then hello()
            elseif c='q' | c='Q' then quine(prog)
            elseif c='9'         then beer()
            elseif c='+'         then acc := acc + 1
            end
        end
        return(acc)
    end run
end hq9plus

start_up = proc ()
    fn: file_name := file_name$parse(sequence[string]$bottom(get_argv()))
    hq9plus$run(hq9plus$load(fn))
end start_up


       IDENTIFICATION DIVISION.
       PROGRAM-ID. Exec-Hq9.

       DATA DIVISION.
       LOCAL-STORAGE SECTION.
       78  Code-Length VALUE 256.

       01  i           PIC 999.
       01  accumulator PIC 999.

       01  bottles     PIC 999.

       LINKAGE SECTION.
       01  hq9-code    PIC X(Code-Length).

       PROCEDURE DIVISION USING BY VALUE hq9-code.
           PERFORM VARYING i FROM 1 BY 1 UNTIL Code-Length < i
               EVALUATE hq9-code (i:1)
                   WHEN "Q"
                       DISPLAY FUNCTION TRIM(hq9-code)

                   WHEN "H"
                       DISPLAY "Hello, World!"

                   WHEN "9"
                       MOVE 99 TO bottles
                       PERFORM UNTIL bottles = ZERO
                           DISPLAY
                               bottles " bottles of beer on the wall"
                           DISPLAY bottles " bottles of beer"
                           DISPLAY "Take one down, pass it around"
                           SUBTRACT 1 FROM bottles
                           DISPLAY
                               bottles " bottles of beer on the wall"
                           DISPLAY SPACE
                       END-PERFORM

                   WHEN "+"
                       ADD 1 TO accumulator
               END-EVALUATE
           END-PERFORM

           GOBACK
           .


#NoEnv
SetBatchLines, -1

; Check if we're executed directly:
If (A_LineFile = A_ScriptFullPath){
	h27 := hailstone(27)
	MsgBox % "Length of hailstone 27: " (m := h27.MaxIndex()) "`nStarts with "
		. h27[1] ", " h27[2] ", " h27[3] ", " h27[4]
		. "`nEnds with "
		. h27[m-3] ", " h27[m-2] ", " h27[m-1] ", " h27[m]

	Loop 100000
	{
		h := hailstone(A_Index)
		If (h.MaxIndex() > m)
			m := h.MaxIndex(), longest := A_Index
	}
	MsgBox % "Longest hailstone is that of " longest " with a length of " m "!"
}

hailstone(n){
	out := [n]
	Loop
		n := n & 1 ? n*3+1 : n//2, out.insert(n)
	until n=1
	return out
}


      seqlen% = FNhailstone(27)
      PRINT "Sequence length for 27 is "; seqlen%
      maxlen% = 0
      FOR number% = 2 TO 100000
        seqlen% = FNhailstone(number%)
        IF seqlen% > maxlen% THEN
          maxlen% = seqlen%
          maxnum% = number%
        ENDIF
      NEXT
      PRINT "The number with the longest hailstone sequence is " ; maxnum%
      PRINT "Its sequence length is " ; maxlen%
      END

      DEF FNhailstone(N%)
      LOCAL L%
      WHILE N% <> 1
        IF N% AND 1 THEN N% = 3 * N% + 1 ELSE N% DIV= 2
        L% += 1
      ENDWHILE
      = L% + 1


#ifndef HAILSTONE
#define HAILSTONE

long hailstone(long, long**);
void free_sequence(long *);

#endif/*HAILSTONE*/


for i = 0 to 15
    print fiboR(i),fiboI(i)
next i

function fiboR(n)
    if n <= 1 then
        fiboR = n
    else
        fiboR = fiboR(n-1) + fiboR(n-2)
    end if
end function

function fiboI(n)
    a = 0
    b = 1
    for i = 1 to n
        temp = a + b
        a = b
        b = temp
    next i
    fiboI = a
end function


[email protected](Number traits) raisedTo: [email protected](Integer traits)
[
  y isZero ifTrue: [^ x unit].
  x isZero \/ [y = 1] ifTrue: [^ x].
  y isPositive
    ifTrue:
      "(x * x raisedTo: y // 2) * (x raisedTo: y \\ 2)"
      [| count result |
       count: 1.
       [(count: (count bitShift: 1)) < y] whileTrue.
       result: x unit.
       [count isPositive]
	 whileTrue:
	   [result: result squared.
	    (y bitAnd: count) isZero ifFalse: [result: result * x].
	    count: (count bitShift: -1)].
       result]
    ifFalse: [(x raisedTo: y negated) reciprocal]
].


Number extend [
  ** anInt [
       | r |
       ( anInt isInteger )
            ifFalse:
              [ '** works fine only for integer powers'
	        displayOn: stderr . Character nl displayOn: stderr ].
       r := 1.
       1 to: anInt do: [ :i | r := ( r * self ) ].
       ^r
  ]
].

( 2.5 ** 3 ) displayNl.
( 2 ** 10 ) displayNl.
( 3/7 ** 3 ) displayNl.


fun expt_int (a, b) = let
  fun aux (x, i) =
    if i = b then x
    else aux (x * a, i + 1)
in
  aux (1, 0)
end

fun expt_real (a, b) = let
  fun aux (x, i) =
    if i = b then x
    else aux (x * a, i + 1)
in
  aux (1.0, 0)
end

val op ** = expt_int
infix 6 **
val op *** = expt_real
infix 6 ***


mata
function pow(a, n) {
	x = a
	for(p=1; n>0; n=floor(n/2)) {
		if(mod(n,2)==1) p = p*x
		x = x*x
	}
	return(p)
}
end


      *FLOAT64
      @% = &1010

      PRINT FNfactorial(18)
      END

      DEF FNfactorial(n)
      IF n <= 1 THEN = 1 ELSE = n * FNfactorial(n-1)


#! /usr/bin/bc -q

define f(x) {
  if (x <= 1) return (1); return (f(x-1) * x)
}
f(1000)
quit


import Foundation

func soeDictOdds() -> UnfoldSequence<Int, Int> {
  var bp = 5; var q = 25
  var bps: UnfoldSequence<Int, Int>.Iterator? = nil
  var dict = [9: 6] // Dictionary<Int, Int>(9 => 6)
  return sequence(state: 2, next: { n in
    if n < 9 { if n < 3 { n = 3; return 2 }; defer {n += 2}; return n }
    while n >= q || dict[n] != nil {
      if n >= q {
        let inc = bp + bp
        dict[n + inc] = inc
        if bps == nil {
          bps = soeDictOdds().makeIterator()
          bp = (bps?.next())!; bp = (bps?.next())!; bp = (bps?.next())! // skip 2/3/5...
        }
        bp = (bps?.next())!; q = bp * bp // guaranteed never nil
      } else {
        let inc = dict[n] ?? 0
        dict[n] = nil
        var next = n + inc
        while dict[next] != nil { next += inc }
        dict[next] = inc
      }
      n += 2
    }
    defer { n += 2 }; return n
  })
}

print("The first 20 primes are:  ", terminator: "")
soeDictOdds().lazy.prefix(20).forEach { print($0, "", terminator: "") }
print()

print("The primes between 100 and 150 are:  ", terminator: "")
soeDictOdds().lazy.drop(while: { $0 < Prime(100) }).lazy.prefix(while: { $0 <= 150 })
    .forEach { print($0, "", terminator: "") }
print()

print("The number of primes from 7700 to 8000 is  :", terminator: "")
print(soeDictOdds().lazy.drop(while: { $0 < 7700 }).lazy.prefix(while: { $0 <= 8000 })
        .lazy.reduce(0, { a, _ in a + 1 }))

print("The 10,000th prime is:  ", terminator: "")
print((soeDictOdds().lazy.dropFirst(9999).first { $0 == $0 })!)

print("The sum of primes to 2 million is:  ", terminator: "")

let start = NSDate()
let answr = soeDictOdds().lazy.prefix(while: { $0 <= 2000000 })
              .reduce(0, { a, p in a + Int64(p) })
let elpsd = -start.timeIntervalSinceNow

print(answr)
print(String(format: "This test took %.3f milliseconds.", elpsd * 1000))


package require Tcl 8.6

# An iterative version of the Sieve of Eratosthenes.
# Effective limit is the size of memory.
coroutine primes apply {{} {
    yield
    while 1 {yield [coroutine primes_[incr p] apply {{} {
	yield [info coroutine]
	set plist {}
	for {set n 2} true {incr n} {
	    set found 0
	    foreach p $plist {
		if {$n%$p==0} {
		    set found 1
		    break
		}
	    }
	    if {!$found} {
		lappend plist $n
		yield $n
	    }
	}
    }}]}
}}

set p [primes]
for {set primes {}} {[llength $primes] < 20} {} {
    lappend primes [$p]
}
puts 1st20=[join $primes ,]
rename $p {}

set p [primes]
for {set primes {}} {[set n [$p]] <= 150} {} {
    if {$n >= 100 && $n <= 150} {
	lappend primes $n
    }
}
puts 100-150=[join $primes ,]
rename $p {}

set p [primes]
for {set count 0} {[set n [$p]] <= 8000} {} {
    incr count [expr {$n>=7700 && $n<=8000}]
}
puts count7700-8000=$count
rename $p {}

set p [primes]
for {set count 0} {$count < 10000} {incr count} {
    set prime [$p]
}
puts prime10000=$prime
rename $p {}


import std.stdio, std.string;

void main(in string[] args) {
    if (args.length != 2 ||
        args[1].length != args[1].countchars("hHqQ9+")) {
        writeln("Not valid HQ9+ code.");
        return;
    }

    ulong accumulator;
    foreach (immutable c; args[1]) {
        final switch(c) {
            case 'Q', 'q':
                writeln(args[1]);
                break;
            case 'H', 'h':
                writeln("Hello, world!");
                break;
            case '9':
                int bottles = 99;
                while (bottles > 1) {
                    writeln(bottles, " bottles of beer on the wall,");
                    writeln(bottles, " bottles of beer.");
                    writeln("Take one down, pass it around,");
                    if (--bottles > 1)
                        writeln(bottles,
                                " bottles of beer on the wall.\n");
                }
                writeln("1 bottle of beer on the wall.\n");
                break;
            case '+':
                accumulator++;
                break;
        }
    }
}


.
├── clojure.jar
└── rosetta_code
    ├── frequent_hailstone_lengths.clj
    └── hailstone_sequence.clj


local hailstone:
	swap [ over ]
	while < 1 dup:
		if % over 2:
			#odd
			++ * 3
		else:
			#even
			/ swap 2
		swap push-through rot dup
	drop

if = (name) :(main):
	local :h27 hailstone 27
	!. = 112 len h27
	!. = 27 h27! 0
	!. = 82 h27! 1
	!. = 41 h27! 2
	!. = 124 h27! 3
	!. = 8 h27! 108
	!. = 4 h27! 109
	!. = 2 h27! 110
	!. = 1 h27! 111

	local :max 0
	local :maxlen 0
	for i range 1 99999:
		dup len hailstone i
		if < maxlen:
			set :maxlen
			set :max i
		else:
			drop
	!print( "number: " to-str max ", length: " to-str maxlen )
else:
	@hailstone


! rosetta/hailstone/hailstone.factor
USING: arrays io kernel math math.ranges prettyprint sequences vectors ;
IN: rosetta.hailstone

: hailstone ( n -- seq )
    [ 1vector ] keep
    [ dup 1 number= ]
    [
        dup even? [ 2 / ] [ 3 * 1 + ] if
        2dup swap push
    ] until
    drop ;

<PRIVATE
: main ( -- )
    27 hailstone dup dup
    "The hailstone sequence from 27:" print
    "  has length " write length .
    "  starts with " write 4 head [ unparse ] map ", " join print
    "  ends with " write 4 tail* [ unparse ] map ", " join print

    ! Maps n => { length n }, and reduces to longest Hailstone sequence.
    1 100000 [a,b)
    [ [ hailstone length ] keep 2array ]
    [ [ [ first ] [email protected] > ] most ] map-reduce
    first2
    "The hailstone sequence from " write pprint
    " has length " write pprint "." print ;
PRIVATE>

MAIN: main


// modulino.go
package main

import "fmt"

// Function borrowed from Hailstone sequence task.
// 1st arg is the number to generate the sequence for.
// 2nd arg is a slice to recycle, to reduce garbage.
func hailstone(n int, recycle []int) []int {
    s := append(recycle[:0], n)
    for n > 1 {
        if n&1 == 0 {
            n = n / 2
        } else {
            n = 3*n + 1
        }
        s = append(s, n)
    }
    return s
}

func libMain() {
    seq := hailstone(27, nil)
    fmt.Println("\nHailstone sequence for the number 27:")
    fmt.Println("  has", len(seq), "elements")
    fmt.Println("  starts with", seq[0:4])
    fmt.Println("  ends with", seq[len(seq)-4:])

    var longest, length int
    for i := 1; i < 100000; i++ {
        if le := len(hailstone(i, nil)); le > length {
            longest = i
            length = le
        }
    }
    fmt.Printf("\n%d has the longest Hailstone sequence, its length being %d.\n", longest, length)
}


*&---------------------------------------------------------------------*
*& Report  ZEXEC_SYS_CMD
*&
*&---------------------------------------------------------------------*
*&
*&
*&---------------------------------------------------------------------*

REPORT  zexec_sys_cmd.

DATA: lv_opsys      TYPE          syst-opsys,
      lt_sxpgcotabe TYPE TABLE OF sxpgcotabe,
      ls_sxpgcotabe LIKE LINE OF  lt_sxpgcotabe,
      ls_sxpgcolist TYPE          sxpgcolist,
      lv_name       TYPE          sxpgcotabe-name,
      lv_opcommand  TYPE          sxpgcotabe-opcommand,
      lv_index      TYPE          c,
      lt_btcxpm     TYPE TABLE OF btcxpm,
      ls_btcxpm     LIKE LINE OF  lt_btcxpm
      .

* Initialize
lv_opsys = sy-opsys.
CLEAR lt_sxpgcotabe[].

IF lv_opsys EQ 'Windows NT'.
  lv_opcommand = 'dir'.
ELSE.
  lv_opcommand = 'ls'.
ENDIF.

* Check commands
SELECT * FROM sxpgcotabe INTO TABLE lt_sxpgcotabe
  WHERE opsystem  EQ lv_opsys
    AND opcommand EQ lv_opcommand.

IF lt_sxpgcotabe IS INITIAL.
  CLEAR ls_sxpgcolist.
  CLEAR lv_name.
  WHILE lv_name IS INITIAL.
* Don't mess with other users' commands
    lv_index = sy-index.
    CONCATENATE 'ZLS' lv_index INTO lv_name.
    SELECT * FROM sxpgcostab INTO ls_sxpgcotabe
      WHERE name EQ lv_name.
    ENDSELECT.
    IF sy-subrc = 0.
      CLEAR lv_name.
    ENDIF.
  ENDWHILE.
  ls_sxpgcolist-name      = lv_name.
  ls_sxpgcolist-opsystem  = lv_opsys.
  ls_sxpgcolist-opcommand = lv_opcommand.
* Create own ls command when nothing is declared
  CALL FUNCTION 'SXPG_COMMAND_INSERT'
    EXPORTING
      command                = ls_sxpgcolist
      public                 = 'X'
    EXCEPTIONS
      command_already_exists = 1
      no_permission          = 2
      parameters_wrong       = 3
      foreign_lock           = 4
      system_failure         = 5
      OTHERS                 = 6.
  IF sy-subrc <> 0.
* Implement suitable error handling here
  ELSE.
* Hooray it worked! Let's try to call it
    CALL FUNCTION 'SXPG_COMMAND_EXECUTE_LONG'
      EXPORTING
        commandname                   = lv_name
      TABLES
        exec_protocol                 = lt_btcxpm
      EXCEPTIONS
        no_permission                 = 1
        command_not_found             = 2
        parameters_too_long           = 3
        security_risk                 = 4
        wrong_check_call_interface    = 5
        program_start_error           = 6
        program_termination_error     = 7
        x_error                       = 8
        parameter_expected            = 9
        too_many_parameters           = 10
        illegal_command               = 11
        wrong_asynchronous_parameters = 12
        cant_enq_tbtco_entry          = 13
        jobcount_generation_error     = 14
        OTHERS                        = 15.
    IF sy-subrc <> 0.
* Implement suitable error handling here
      WRITE: 'Cant execute ls - '.
      CASE sy-subrc.
        WHEN 1.
          WRITE: / ' no permission!'.
        WHEN 2.
          WRITE: / ' command could not be created!'.
        WHEN 3.
          WRITE: / ' parameter list too long!'.
        WHEN 4.
          WRITE: / ' security risk!'.
        WHEN 5.
          WRITE: / ' wrong call of SXPG_COMMAND_EXECUTE_LONG!'.
        WHEN 6.
          WRITE: / ' command cant be started!'.
        WHEN 7.
          WRITE: / ' program terminated!'.
        WHEN 8.
          WRITE: / ' x_error!'.
        WHEN 9.
          WRITE: / ' parameter missing!'.
        WHEN 10.
          WRITE: / ' too many parameters!'.
        WHEN 11.
          WRITE: / ' illegal command!'.
        WHEN 12.
          WRITE: / ' wrong asynchronous parameters!'.
        WHEN 13.
          WRITE: / ' cant enqueue job!'.
        WHEN 14.
          WRITE: / ' cant create job!'.
        WHEN 15.
          WRITE: / ' unknown error!'.
        WHEN OTHERS.
          WRITE: / ' unknown error!'.
      ENDCASE.
    ELSE.
      LOOP AT lt_btcxpm INTO ls_btcxpm.
        WRITE: / ls_btcxpm.
      ENDLOOP.
    ENDIF.
  ENDIF.
ENDIF.


on fib (n)
  if n<2 then return n
  return fib(n-1)+fib(n-2)
end


func raise<T: Numeric>(_ base: T, to exponent: Int) -> T {
    precondition(exponent >= 0, "Exponent has to be nonnegative")
    return Array(repeating: base, count: exponent).reduce(1, *)
}

infix operator **: MultiplicationPrecedence

func **<T: Numeric>(lhs: T, rhs: Int) -> T {
    return raise(lhs, to: rhs)
}

let someFloat: Float = 2
let someInt: Int = 10

assert(raise(someFloat, to: someInt) == 1024)
assert(someFloat ** someInt == 1024)
assert(raise(someInt, to: someInt) == 10000000000)
assert(someInt ** someInt == 10000000000)