*        Primality by trial division  26/03/2017
PRIMEDIV CSECT
         USING  PRIMEDIV,R13       base register
         B      72(R15)            skip savearea
         DC     17F'0'             savearea
         STM    R14,R12,12(R13)    save previous context
         ST     R13,4(R15)         link backward
         ST     R15,8(R13)         link forward
         LR     R13,R15            set addressability
         LA     R10,PG             pgi=0
         LA     R6,1               i=1
       DO WHILE=(C,R6,LE,=F'50')   do i=1 to 50
         LR     R1,R6                i
         BAL    R14,ISPRIME          call isprime(i)
       IF C,R0,EQ,=F'1' THEN         if isprime(i) then
         XDECO  R6,XDEC                edit i
         MVC    0(4,R10),XDEC+8        output i
         LA     R10,4(R10)             pgi+=4
       ENDIF    ,                    endif
         LA     R6,1(R6)             i++
       ENDDO    ,                  enddo i
         XPRNT  PG,L'PG            print buffer
         L      R13,4(0,R13)       restore previous savearea pointer
         LM     R14,R12,12(R13)    restore previous context
         XR     R15,R15            rc=0
         BR     R14                exit
*------- ----   ----------------------------------------
ISPRIME  EQU    *                  function isprime(n)
       IF C,R1,LE,=F'1' THEN       if n<=1 then
         LA     R0,0                 return(0)
         BR     R14                  return
       ENDIF    ,                  endif
       IF C,R1,EQ,=F'2' THEN       if n=2 then
         LA     R0,1                 return(1)
         BR     R14                  return
       ENDIF    ,                  endif
         LR     R4,R1              n
         N      R4,=X'00000001'    n and 1
       IF LTR,R4,Z,R4 THEN         if mod(n,2)=0 then
         LA     R0,0                 return(0)
         BR     R14                  return
       ENDIF    ,                  endif
         LA     R7,3               j=3
         LA     R5,9               r5=j*j
       DO WHILE=(CR,R5,LE,R1)      do j=3 by 2 while j*j<=n
         LR     R4,R1                n
         SRDA   R4,32                ~
         DR     R4,R7                /j
       IF LTR,R4,Z,R4 THEN           if mod(n,j)=0 then
         LA     R0,0                   return(0)
         BR     R14                    return
       ENDIF    ,                    endif
         LA     R7,2(R7)             j+=2
         LR     R5,R7                j
         MR     R4,R7                r5=j*j
       ENDDO    ,                  enddo j
         LA     R0,1               return(1)
         BR     R14                return
*------- ----   ----------------------------------------
PG       DC     CL80' '            buffer
XDEC     DS     CL12               temp for xdeco
         YREGS
         END    PRIMEDIV


isPrime:
; REG USAGE:
; D0 = input (unsigned 32-bit integer)
; D1 = temp storage for D0
; D2 = candidates for possible factors
; D3 = temp storage for quotient/remainder
; D4 = total count of proper divisors.

MOVEM.L D1-D4,-(SP)      ;push data regs except D0
MOVE.L #0,D1
MOVEM.L D1,D2-D4         ;clear regs D1 thru D4

CMP.L #0,D0
BEQ notPrime
CMP.L #1,D0
BEQ notPrime
CMP.L #2,D0
BEQ wasPrime

MOVE.L D0,D1            ;D1 will be used for temp storage.
AND.L #1,D1             ;is D1 even?
BEQ notPrime            ;if so, it's not prime!

MOVE.L D0,D1            ;restore D1

MOVE.L #3,D2		;start with 3

computeFactors:
DIVU D2,D1              ;remainder is in top 2 bytes, quotient in bottom 2.
MOVE.L D1,D3		;temporarily store into D3 to check the remainder
SWAP D3			;swap the high and low words of D3. Now bottom 2 bytes contain remainder.
CMP.W #0,D3		;is the bottom word equal to 0?
BNE D2_Wasnt_A_Divisor	;if not, D2 was not a factor of D1.

ADDQ.L #1,D4            ;increment the count of proper divisors.
CMP.L #2,D4             ;is D4 two or greater?
BCC notPrime            ;if so, it's not prime! (Ends early. We'll need to check again if we made it to the end.)

D2_Wasnt_A_Divisor:
MOVE.L D0,D1            ;restore D1.
ADDQ.L #1,D2		;increment D2

CMP.L D2,D1             ;is D2 now greater than D1?
BLS computeFactors      ;if not, loop again

CMP.L #1,D4		;was there only one factor?
BEQ wasPrime		;if so, D0 was prime.

notPrime:
MOVE.L #0,D0             ;return false
MOVEM.L (SP)+,D1-D4      ;pop D1-D4
RTS

wasPrime:
MOVE.L #1,D0             ;return true
MOVEM.L (SP)+,D1-D4      ;pop D1-D4
RTS
;end of program


StringForm["`` count: ``   frequency: ``", [email protected]@ #[[1]], StringPadLeft[[email protected] #[[2]], 8], PercentForm[[email protected] #[[2]]/(10^8 -1)]]& /@
  Sort[Tally[Partition[Mod[Prime[Range[10^8]], 10], 2, 1]]] // Column


# Prime conspiracy.

from algorithm import sorted
from math import sqrt
from sequtils import toSeq
from strformat import fmt
import tables

const N = 1_020_000_000.int     # Size of sieve of Eratosthenes.

proc newSieve(): seq[bool] =
  ## Create a sieve with only odd values.
  ## Index "i" in sieve represents value "n = 2 * i + 3".
  result.setLen(N)
  for item in result.mitems: item = true
  # Apply sieve.
  var i = 0
  const Limit = sqrt(2 * N.toFloat + 3).int
  while true:
    let n = 2 * i + 3
    if n > Limit:
      break
    if result[i]:
      # Found prime, so eliminate multiples.
      for k in countup((n * n - 3) div 2, N - 1, n):
        result[k] = false
    inc i

var isPrime = newSieve()

proc countTransitions(isPrime: seq[bool]; nprimes: int) =
  ## Build the transition count table and print it.

  var counts = [(2, 3)].toCountTable()    # Count of transitions.
  var d1 = 3      # Last digit of first prime in transition.
  var count = 2   # Count of primes (starting with 2 and 3).
  for i in 1..isPrime.high:
    if isPrime[i]:
      inc count
      let d2 = (2 * i + 3) mod 10   # Last digit of second prime in transition.
      counts.inc((d1, d2))
      if count == nprimes: break
      d1 = d2

  # Check if sieve was big enough.
  if count < nprimes:
    echo fmt"Found only {count} primes; expected {nprimes} primes. Increase value of N."
    quit(QuitFailure)

  # Print result.
  echo fmt"{nprimes} first primes. Transitions prime % 10 → next-prime % 10."
  for key in sorted(toSeq(counts.keys)):
    let count = counts[key]
    let freq = count.toFloat * 100 / nprimes.toFloat
    echo fmt"{key[0]} -> {key[1]}: count: {count:7d}  frequency: {freq:4.2f}%"
  echo ""

isPrime.countTransitions(10_000)
isPrime.countTransitions(1_000_000)
isPrime.countTransitions(100_000_000)


conspiracy(maxx)={
print("primes considered= ",maxx);
x=matrix(9,9);cnt=0;p=2;q=2%10;
while(cnt<=maxx,
cnt+=1;
m=q;
p=nextprime(p+1);
q= p%10;
x[m,q]+=1);
print (2," to ",3, " count: ",x[2,3],"  freq ", 100./cnt,"  %" );
forstep(i=1,9,2,
forstep(j=1,9,2,
if( x[i,j]<1,continue);
print (i," to ",j, " count: ",x[i,j],"  freq ", 100.* x[i,j]/cnt,"  %" )));
print ("total transitions= ",cnt);
print(p);
}


defmodule RC do
  use Bitwise
  def powerset1(list) do
    n = length(list)
    max = round(:math.pow(2,n))
    for i <- 0..max-1, do: (for pos <- 0..n-1, band(i, bsl(1, pos)) != 0, do: Enum.at(list, pos) )
  end

  def powerset2([]), do: [[]]
  def powerset2([h|t]) do
    pt = powerset2(t)
    (for x <- pt, do: [h|x]) ++ pt
  end

  def powerset3([]), do: [[]]
  def powerset3([h|t]) do
    pt = powerset3(t)
    powerset3(h, pt, pt)
  end

  defp powerset3(_, [], acc), do: acc
  defp powerset3(x, [h|t], acc), do: powerset3(x, t, [[x|h] | acc])
end

IO.inspect RC.powerset1([1,2,3])
IO.inspect RC.powerset2([1,2,3])
IO.inspect RC.powerset3([1,2,3])
IO.inspect RC.powerset1([])
IO.inspect RC.powerset1(["one"])


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

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

/*******************************************/
/* Initialized data */
/*******************************************/
.data
szMessStartPgm:            .asciz "Program start \n"
szMessEndPgm:              .asciz "Program normal end.\n"
szMessNotPrime:            .asciz "Not prime.\n"
szMessPrime:               .asciz "Prime\n"
szCarriageReturn:          .asciz "\n"

/*******************************************/
/* UnInitialized data                      */
/*******************************************/
.bss
.align 4
/*******************************************/
/*  code section                           */
/*******************************************/
.text
.global main
main:                                           // program start
    ldr x0,qAdrszMessStartPgm                   // display start message
    bl affichageMess
    ldr x0,qVal
    bl isPrime                                  // test prime ?
    cmp x0,#0
    beq 1f
    ldr x0,qAdrszMessPrime                      // yes
    bl affichageMess
    b 2f
1:
    ldr x0,qAdrszMessNotPrime                   // no
    bl affichageMess
2:

    ldr x0,qAdrszMessEndPgm                     // display end message
    bl affichageMess

100:                                            // standard end of the program
    mov x0,0                                    // return code
    mov x8,EXIT                                 // request to exit program
    svc 0                                       // perform system call
qAdrszMessStartPgm:        .quad szMessStartPgm
qAdrszMessEndPgm:          .quad szMessEndPgm
qAdrszCarriageReturn:      .quad szCarriageReturn
qAdrszMessNotPrime:        .quad szMessNotPrime
qAdrszMessPrime:           .quad szMessPrime
//qVal:                      .quad 1042441       // test not prime
//qVal:                      .quad 1046527       // test prime
//qVal:                       .quad 37811          // test prime
//qVal:                      .quad 1429671721    // test not prime (37811 * 37811)
qVal:                      .quad 100000004437    // test prime
/******************************************************************/
/*     test if number is prime                                    */
/******************************************************************/
/* x0 contains the number  */
/* x0 return 1 if prime else return 0 */
isPrime:
    stp x1,lr,[sp,-16]!        // save  registers
    cmp x0,1                   // <= 1 ?
    ble 98f
    cmp x0,3                   // 2 and 3 prime
    ble 97f
    tst x0,1                   //  even ?
    beq 98f
    mov x11,3                 // first divisor
1:
    udiv x12,x0,x11
    msub x13,x12,x11,x0       // compute remainder
    cbz x13,98f               // end if zero
    add x11,x11,#2            // increment divisor
    cmp x11,x12               // divisors<=quotient ?
    ble 1b                    // loop
97:
    mov x0,1                  // return prime
    b 100f
98:
    mov x0,0                  // not prime
    b 100f
100:
    ldp x1,lr,[sp],16         // restaur  2 registers
    ret                       // return to address lr x30

/********************************************************/
/*        File Include fonctions                        */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"


class ZMLA_ROSETTA definition
  public
  create public .

public section.

  types:
    enumber         TYPE          N  LENGTH 60 .
  types:
    listof_enumber  TYPE TABLE OF enumber .

  class-methods IS_PRIME
    importing
      value(N) type ENUMBER
    returning
      value(OFLAG) type ABAP_BOOL .
  class-methods IS_PRIME_I
    importing
      value(N) type I
    returning
      value(OFLAG) type ABAP_BOOL .
  protected section.
  private section.
ENDCLASS.

CLASS ZMLA_ROSETTA IMPLEMENTATION.

* <SIGNATURE>---------------------------------------------------------------------------------------+
* | Static Public Method ZMLA_ROSETTA=>IS_PRIME
* +-------------------------------------------------------------------------------------------------+
* | [--->] N                              TYPE        ENUMBER
* | [<-()] OFLAG                          TYPE        ABAP_BOOL
* +--------------------------------------------------------------------------------------</SIGNATURE>
  method IS_PRIME.
    IF n < 2.
      oflag = abap_false.
      RETURN.
    ENDIF.
    IF n = 2 or n = 3.
      oflag = abap_true.
      RETURN.
    ENDIF.
    IF n mod 2 = 0 or n mod 3 = 0.
      oflag = abap_false.
      RETURN.
    ENDIF.
    DATA: lim type enumber,
          d   type enumber,
          i   TYPE i        VALUE 2.
    lim = sqrt( n ).
    d   = 5.
    WHILE d <= lim.
      IF n mod d = 0.
        oflag = abap_false.
        RETURN.
      ENDIF.
      d = d + i.
      i = 6 - i.  " this modifies 2 into 4 and viceversa
    ENDWHILE.
    oflag = abap_true.
    RETURN.
  endmethod.

* <SIGNATURE>---------------------------------------------------------------------------------------+
* | Static Public Method ZMLA_ROSETTA=>IS_PRIME_I
* +-------------------------------------------------------------------------------------------------+
* | [--->] N                              TYPE        I
* | [<-()] OFLAG                          TYPE        ABAP_BOOL
* +--------------------------------------------------------------------------------------</SIGNATURE>
  method IS_PRIME_I.
    IF n < 2.
      oflag = abap_false.
      RETURN.
    ENDIF.
    IF n = 2 or n = 3.
      oflag = abap_true.
      RETURN.
    ENDIF.
    IF n mod 2 = 0 or n mod 3 = 0.
      oflag = abap_false.
      RETURN.
    ENDIF.
    DATA: lim type i,
          d   type i,
          i   TYPE i        VALUE 2.
    lim = sqrt( n ).
    d   = 5.
    WHILE d <= lim.
      IF n mod d = 0.
        oflag = abap_false.
        RETURN.
      ENDIF.
      d = d + i.
      i = 6 - i.  " this modifies 2 into 4 and viceversa
    ENDWHILE.
    oflag = abap_true.
    RETURN.
  endmethod.
ENDCLASS.


program primCons;
{$IFNDEF FPC}
  {$APPTYPE CONSOLE}
{$ENDIF}
const
  PrimeLimit =  2038074748 DIV 2;
type
  tLimit = 0..PrimeLimit;
  tCntTransition = array[0..9,0..9] of NativeInt;
  tCntTransRec = record
                   CTR_CntTrans:tCntTransition;
                   CTR_primCnt,
                   CTR_Limit : NativeInt;
                 end;
  tCntTransRecField = array[0..19] of tCntTransRec;
var
  primes: array [tLimit] of boolean;
  CntTransitions : tCntTransRecField;

procedure SieveSmall;
//sieve of eratosthenes with only odd numbers
var
  i,j,p: NativeInt;
Begin
  FillChar(primes[1],SizeOF(primes),chr(ord(true)));
  i := 1;
  p := 3;
  j := i*(i+1)*2;
  repeat
    IF (primes[i]) then
    begin
      p := i+i+1;
      repeat
        primes[j] := false;
        inc(j,p);
      until j > PrimeLimit;
    end;
    inc(i);
    j := i*(i+1)*2;//position of i*i
    IF PrimeLimit < j then
      BREAK;
  until false;
end;

procedure OutputTransitions(const Trs:tCntTransRecField);
var
  i,j,k,res,cnt: NativeInt;
  ThereWasOutput: boolean;
Begin
  cnt := 0;
  while Trs[cnt].CTR_primCnt > 0 do
    inc(cnt);
  dec(cnt);
  IF cnt < 0 then
    EXIT;

  write('PrimCnt ');
  For i := 0 to cnt do
    write(Trs[i].CTR_primCnt:i+7);
  writeln;
  For i := 0 to 9 do
  Begin
    ThereWasOutput := false;
    For j := 0 to 9 do
    Begin
      res := Trs[0].CTR_CntTrans[i,j];
      IF res > 0 then
      Begin
        ThereWasOutput := true;
        write('''',i,'''->''',j,'''');
        For k := 0 to cnt do
        Begin
          res := Trs[k].CTR_CntTrans[i,j];
          write(res/Trs[k].CTR_primCnt*100:k+6:k+2,'%');
        end;
        writeln;
      end;
    end;
    IF ThereWasOutput then
      writeln;
  end;
end;

var
  pCntTransOld,
  pCntTransNew  : ^tCntTransRec;
  i,primCnt,lmt : NativeInt;
  prvChr,
  nxtChr : NativeInt;
Begin
  SieveSmall;
  pCntTransOld := @CntTransitions[0].CTR_CntTrans;

  pCntTransOld^.CTR_CntTrans[2,3]:= 1;
  lmt := 10*1000;

  //starting at 2 *2+1 => 5
  primCnt := 2; // the prime 2,3
  prvChr := 3;
  nxtChr  := prvChr;
  for i:= 2 to PrimeLimit do
  Begin
    inc(nxtChr,2);
    if nxtChr >= 10 then nxtChr := 1;
    IF primes[i] then
    Begin
      inc(pCntTransOld^.CTR_CntTrans[prvChr][nxtChr]);
      inc(primCnt);
      prvchr := nxtChr;
      IF primCnt >= lmt then
      Begin
        with pCntTransOld^ do Begin
          CTR_Limit := i;
          CTR_primCnt := primCnt;
        end;
        pCntTransNew := pCntTransOld;
        inc(pCntTransNew);
        pCntTransNew^:= pCntTransOld^;
        pCntTransOld := pCntTransNew;
        lmt := lmt*10;
      end;
    end;
  end;
  pCntTransOld^.CTR_primCnt := 0;
  OutputTransitions(CntTransitions);
end.


let subsets xs = List.foldBack (fun x rest -> rest @ List.map (fun ys -> x::ys) rest) xs [[]]


USING: kernel prettyprint sequences arrays sets hash-sets ;
IN: powerset

: add ( set elt -- newset ) 1array <hash-set> union ;
: powerset ( set -- newset ) members { HS{ } } [ dupd [ add ] curry map append ] reduce <hash-set> ;


: ?print dup 1 and if over args type space then ;
: .set begin dup while ?print >r 1+ r> 1 rshift repeat drop drop ;
: .powerset 0 do ." ( " 1 i .set ." )" cr loop ;
: check-none dup 2 < abort" Usage: powerset [val] .. [val]" ;
: check-size dup /cell 8 [*] >= abort" Set too large" ;
: powerset 1 argn check-none check-size 1- lshift .powerset ;

powerset


(defun is-prime-r (x i)
   (declare (xargs :measure (nfix (- x i))))
   (if (zp (- (- x i) 1))
       t
       (and (/= (mod x i) 0)
            (is-prime-r x (1+ i)))))

(defun is-prime (x)
   (or (= x 2)
       (is-prime-r x 2)))


BYTE FUNC IsPrime(CARD a)
  CARD i

  IF a<=1 THEN
    RETURN (0)
  FI

  FOR i=2 TO a/2
  DO
    IF a MOD i=0 THEN
      RETURN (0)
    FI
  OD
RETURN (1)

PROC Test(CARD a)
  IF IsPrime(a) THEN
    PrintF("%I is prime%E",a)
  ELSE
    PrintF("%I is not prime%E",a)
  FI
RETURN

PROC Main()
  Test(13)
  Test(997)
  Test(1)
  Test(6)
  Test(120)
  Test(0)
RETURN


use ntheory qw/forprimes nth_prime/;

my $upto = 1_000_000;
my %freq;
my($this_digit,$last_digit)=(2,0);

forprimes {
  ($last_digit,$this_digit) = ($this_digit, $_ % 10);
  $freq{$last_digit . $this_digit}++;
} 3,nth_prime($upto);

print "$upto first primes.  Transitions prime % 10 → next-prime % 10.\n";
printf "%s → %s count:\t%7d\tfrequency: %4.2f %%\n",
  substr($_,0,1), substr($_,1,1), $freq{$_}, 100*$freq{$_}/$upto
    for sort keys %freq;


with javascript_semantics
sequence p10k = get_primes(-10_000),
  transitions = repeat(repeat(0,9),9)
integer l = length(p10k), last = p10k[1], curr
for i=2 to l do
    curr = remainder(p10k[i],10)
    transitions[last][curr] += 1
    last = curr
end for
for i=1 to 9 do
    for j=1 to 9 do
        atom tij = transitions[i][j]
        if tij!=0 then
            atom pc = tij*100/l
            printf(1,"%d->%d:%3.2f%%\n",{i,j,pc})
        end if
    end for
end for


Function ConjuntoPotencia(set() As String) As String
    If Ubound(set,1) > 31 Then Print "Set demasiado grande para representarlo como un entero" : Exit Function
    If Ubound(set,1) < 0 Then Print "{}": Exit Function ' Set vacío
    Dim As Integer i, j
    Dim As String s = "{"
    For i = Lbound(set) To (2 Shl Ubound(set,1)) - 1
        s += "{"
        For j = Lbound(set) To Ubound(set,1)
            If i And (1 Shl j) Then s += set(j) + ","
        Next j
        If Right(s,1) = "," Then s = Left(s,Len(s)-1)
        s += "},"
    Next i
    Return Left(s,Len(s)-1) + "}"
End Function

Print "El power set de [1, 2, 3, 4] comprende:"
Dim As String set(3) = {"1", "2", "3", "4"}
Print ConjuntoPotencia(set())
Print !"\nEl power set de [] comprende:"
Dim As String set0()
Print ConjuntoPotencia(set0())
Print "El power set de [[]] comprende:"
Dim As String set1(0) = {""}
Print ConjuntoPotencia(set1())
Sleep


function isPrime(n:int):Boolean
{
	if(n < 2) return false;
	if(n == 2) return true;
	if((n & 1) == 0) return false;
	for(var i:int = 3; i <= Math.sqrt(n); i+= 2)
		if(n % i == 0) return false;
	return true;
}


function Is_Prime(Item : Positive) return Boolean is
   Test : Natural;
begin
   if Item = 1 then
      return False;
   elsif Item = 2 then
      return True;
   elsif Item mod 2 = 0 then
      return False;
   else
      Test := 3;
      while Test <= Integer(Sqrt(Float(Item))) loop
         if Item mod Test = 0 then
            return False;
         end if;
         Test := Test + 2;
      end loop;
   end if;
   return True;
end Is_Prime;


go =>
  N = 15_485_863, % 1_000_000 primes
  Primes = {P mod 10 : P in primes(N)},
  Len = Primes.len,
  A = new_array(10,10), bind_vars(A,0),
  foreach(I in 2..Len)
    P1 = 1 + Primes[I-1], % adjust for 1-based
    P2 = 1 + Primes[I],
    A[P1,P2] := A[P1,P2] + 1
  end,
  foreach(I in 0..9, J in 0..9, V = A[I+1,J+1], V > 0)
    printf("%d -> %d count: %5d frequency: %0.4f%%\n", I,J,V,100*V/Len)
  end,
  nl.


(load "pluser/sieve.l")  # See the task "Sieve of Eratosthanes"

(setq NthPrime '(
            (     10 . 29)
            (    100 . 541)
            (   1000 . 7919)
            (  10000 . 104729)
            ( 100000 . 1299709)
            (1000000 . 15485863)))

(de conspiracy (Power)
   (let (Upto (cdr (assoc (** 10 Power) NthPrime)))
      (if Upto
         (report Upto)
         (prog (prinl "Sorry, I don't know the value of the 1e" Power "th prime number.") NIL))))

(de report (Upto)
   (for Count (tally Upto)
      (let (((A . B) . C) Count)
         (prinl A " -> " B ": " C)))
   NIL)

(de tally (Upto)
   (let
      (Transitions
         (maplist '((L)
                     (and
                        (cdr L)
                        (cons
                           (% (car L) 10)
                           (% (cadr L) 10))))
                     (sieve Upto)))
      (let (Tally NIL)
         (for Pair Transitions
            (setq Tally (bump-trans Pair Tally)))
         (cdr (sort Tally)))))   # NOTE: After sorting, first element is NIL
                                 # (since the last element from the maplist call is NIL)

(de bump-trans (Trans Tally)
   (cond
      ((== Tally NIL)
         (list (cons Trans 1)))
      ((= Trans (caar Tally))
         (cons (cons Trans (inc (cdar Tally))) (cdr Tally)))
      (T
         (cons (car Tally) (bump-trans Trans (cdr Tally))))))


% table of nth prime values (up to 100,000)

nthprime(    10, 29).
nthprime(   100, 541).
nthprime(  1000, 7919).
nthprime( 10000, 104729).
nthprime(100000, 1299709).

conspiracy(M) :-
    N is 10**M,
    nthprime(N, P),
    sieve(P, Ps),
    tally(Ps, Counts),
    sort(Counts, Sorted),
    show(Sorted).

show(Results) :-
    forall(
        member(tr(D1, D2, Count), Results),
        format("~d -> ~d: ~d~n", [D1, D2, Count])).

% count results

tally(L, R) :- tally(L, [], R).
tally([_], T, T) :- !.
tally([A|As], T0, R) :-
    [B|_] = As,
    Da is A mod 10, Db is B mod 10,
    count(Da, Db, T0, T1),
    tally(As, T1, R).

count(D1, D2, [], [tr(D1, D2, 1)]) :- !.
count(D1, D2, [tr(D1, D2, N)|Ts], [tr(D1, D2, Sn)|Ts]) :- succ(N, Sn), !.
count(D1, D2, [T|Ts], [T|Us]) :- count(D1, D2, Ts, Us).

% implement a prime sieve

sieve(Limit, Ps) :-
    numlist(2, Limit, Ns),
    sieve(Limit, Ns, Ps).

sieve(Limit, W, W) :- W = [P|_], P*P > Limit, !.
sieve(Limit, [P|Xs], [P|Ys]) :-
    Q is P*P,
    remove_multiples(P, Q, Xs, R),
    sieve(Limit, R, Ys).

remove_multiples(_, _, [], []) :- !.
remove_multiples(N, M, [A|As], R) :-
    A =:= M, !,
    remove_multiples(N, M, As, R).
remove_multiples(N, M, [A|As], [A|R]) :-
    A < M, !,
    remove_multiples(N, M, As, R).
remove_multiples(N, M, L, R) :-
    plus(M, N, M2),
    remove_multiples(N, M2, L, R).


COMMENT
  This routine is used in more than one place, and is essentially a
  template that can by used for many different types, eg INT, LONG INT...
USAGE
  MODE ISPRIMEINT = INT, LONG INT, etc
  PR READ "prelude/is_prime.a68" PR
END COMMENT


BEGIN

% RETURN P MOD Q %
INTEGER FUNCTION MOD(P, Q);
INTEGER P, Q;
BEGIN
  MOD := P - Q * (P / Q);
END;

% RETURN INTEGER SQUARE ROOT OF N %
INTEGER FUNCTION ISQRT(N);
INTEGER N;
BEGIN
  INTEGER R1, R2;
  R1 := N;
  R2 := 1;
  WHILE R1 > R2 DO
    BEGIN
      R1 := (R1+R2) / 2;
      R2 := N / R1;
    END;
  ISQRT := R1;
END;

% RETURN 1 IF N IS PRIME, OTHERWISE 0 %
INTEGER FUNCTION ISPRIME(N);
INTEGER N;
BEGIN
  IF N = 2 THEN
    ISPRIME := 1
  ELSE IF (N < 2) OR (MOD(N,2) = 0) THEN
    ISPRIME := 0
  ELSE % TEST ODD NUMBERS UP TO SQRT OF N %
    BEGIN
      INTEGER I, LIMIT;
      LIMIT := ISQRT(N);
      I := 3;
      WHILE I <= LIMIT AND MOD(N,I) <> 0 DO
        I := I + 2;
      ISPRIME := (IF I <= LIMIT THEN 0 ELSE 1);
    END;
END;

% TEST FOR PRIMES IN RANGE 1 TO 50 %
INTEGER I;
WRITE("");
FOR I := 1 STEP 1 UNTIL 50 DO
  BEGIN
    IF ISPRIME(I)=1 THEN WRITEON(I,"  "); % WORKS FOR 80 COL SCREEN %
  END;

END


% returns true if n is prime, false otherwise %
% uses trial division                         %
logical procedure isPrime ( integer value n ) ;
    if n < 3 or not odd( n ) then n = 2
    else begin
        % odd number > 2 %
        integer f, rootN;
        logical havePrime;
        f         := 3;
        rootN     := entier( sqrt( n ) );
        havePrime := true;
        while f <= rootN and havePrime do begin
            havePrime := ( n rem f ) not = 0;
            f         := f + 2
        end;
        havePrime
    end isPrime ;


class
	APPLICATION

create
	make

feature

	make
			--Tests the price_adjusted feature.
		local
			i: REAL
		do
			create price_fraction.initialize
			from
				i := 5
			until
				i = 100
			loop
				io.put_string ("Given: ")
				io.put_real (i / 100)
				io.put_string ("%TAdjusted:")
				io.put_real (price_fraction.adjusted_price (i / 100))
				io.new_line
				i := i + 5
			end
		end

	price_fraction: PRICE_FRACTION

end


def isPrime(n):
    if n < 2:
        return False
    if n % 2 == 0:
        return n == 2
    if n % 3 == 0:
        return n == 3

    d = 5
    while d * d <= n:
        if n % d == 0:
            return False
        d += 2

        if n % d == 0:
            return False
        d += 4
    return True

def generatePrimes():
    yield 2
    yield 3

    p = 5
    while p > 0:
        if isPrime(p):
            yield p
        p += 2
        if isPrime(p):
            yield p
        p += 4

g = generatePrimes()
transMap = {}
prev = None
limit = 1000000
for _ in xrange(limit):
    prime = next(g)
    if prev:
        transition = (prev, prime %10)
        if transition in transMap:
            transMap[transition] += 1
        else:
            transMap[transition] = 1
    prev = prime % 10

print "First {:,} primes. Transitions prime % 10 > next-prime % 10.".format(limit)
for trans in sorted(transMap):
    print "{0} -> {1} count {2:5} frequency: {3}%".format(trans[0], trans[1], transMap[trans], 100.0 * transMap[trans] / limit)


suppressMessages(library(gmp))

limit <- 1e6
result <- vector('numeric', 99)
prev_prime <- 2
count <- 0

getOutput <- function(transition) {
	if (result[transition] == 0) return()
	second <- transition %% 10
        first <-  (transition - second) / 10
	cat(first,"->",second,"count:", sprintf("%6d",result[transition]), "frequency:",
            sprintf("%5.2f%%\n",result[transition]*100/limit))
}

while (count <= limit) {
	count <- count + 1
	next_prime <- nextprime(prev_prime)
	transition <- 10*(asNumeric(prev_prime) %% 10) + (asNumeric(next_prime) %% 10)
	prev_prime <- next_prime
	result[transition] <- result[transition] + 1
}

cat(sprintf("%d",limit),"first primes. Transitions prime % 10 -> next-prime % 10\n")
invisible(sapply(1:99,getOutput))


package main

import (
    "fmt"
    "strconv"
    "strings"
)

// types needed to implement general purpose sets are element and set

// element is an interface, allowing different kinds of elements to be
// implemented and stored in sets.
type elem interface {
    // an element must be distinguishable from other elements to satisfy
    // the mathematical definition of a set.  a.eq(b) must give the same
    // result as b.eq(a).
    Eq(elem) bool
    // String result is used only for printable output.  Given a, b where
    // a.eq(b), it is not required that a.String() == b.String().
    fmt.Stringer
}

// integer type satisfying element interface
type Int int

func (i Int) Eq(e elem) bool {
    j, ok := e.(Int)
    return ok && i == j
}

func (i Int) String() string {
    return strconv.Itoa(int(i))
}

// a set is a slice of elem's.  methods are added to implement
// the element interface, to allow nesting.
type set []elem

// uniqueness of elements can be ensured by using add method
func (s *set) add(e elem) {
    if !s.has(e) {
        *s = append(*s, e)
    }
}

func (s *set) has(e elem) bool {
    for _, ex := range *s {
        if e.Eq(ex) {
            return true
        }
    }
    return false
}

func (s set) ok() bool {
    for i, e0 := range s {
        for _, e1 := range s[i+1:] {
            if e0.Eq(e1) {
                return false
            }
        }
    }
    return true
}

// elem.Eq
func (s set) Eq(e elem) bool {
    t, ok := e.(set)
    if !ok {
        return false
    }
    if len(s) != len(t) {
        return false
    }
    for _, se := range s {
        if !t.has(se) {
            return false
        }
    }
    return true
}

// elem.String
func (s set) String() string {
    if len(s) == 0 {
        return "∅"
    }
    var buf strings.Builder
    buf.WriteRune('{')
    for i, e := range s {
        if i > 0 {
            buf.WriteRune(',')
        }
        buf.WriteString(e.String())
    }
    buf.WriteRune('}')
    return buf.String()
}

// method required for task
func (s set) powerSet() set {
    r := set{set{}}
    for _, es := range s {
        var u set
        for _, er := range r {
            er := er.(set)
            u = append(u, append(er[:len(er):len(er)], es))
        }
        r = append(r, u...)
    }
    return r
}

func main() {
    var s set
    for _, i := range []Int{1, 2, 2, 3, 4, 4, 4} {
        s.add(i)
    }
    fmt.Println("      s:", s, "length:", len(s))
    ps := s.powerSet()
    fmt.Println("   𝑷(s):", ps, "length:", len(ps))

    fmt.Println("\n(extra credit)")
    var empty set
    fmt.Println("  empty:", empty, "len:", len(empty))
    ps = empty.powerSet()
    fmt.Println("   𝑷(∅):", ps, "len:", len(ps))
    ps = ps.powerSet()
    fmt.Println("𝑷(𝑷(∅)):", ps, "len:", len(ps))

    fmt.Println("\n(regression test for earlier bug)")
    s = set{Int(1), Int(2), Int(3), Int(4), Int(5)}
    fmt.Println("      s:", s, "length:", len(s), "ok:", s.ok())
    ps = s.powerSet()
    fmt.Println("   𝑷(s):", "length:", len(ps), "ok:", ps.ok())
    for _, e := range ps {
        if !e.(set).ok() {
            panic("invalid set in ps")
        }
    }
}


on isPrime(n)
    if (n < 3) then return (n is 2)
    if (n mod 2 is 0) then return false
    repeat with i from 3 to (n ^ 0.5) div 1 by 2
        if (n mod i is 0) then return false
    end repeat

    return true
end isPrime

-- Test code:
set output to {}
repeat with n from -7 to 100
    if (isPrime(n)) then set end of output to n
end repeat
return output


isPrime?: function [n][
    if n=2 -> return true
    if n=3 -> return true
    if or? n=<1 0=n%2 -> return false

    high: to :integer sqrt n
    loop high..2 .step: 3 'i [
    	if 0=n%i -> return false
    ]

    return true
]

loop 1..20 'i [
    print ["isPrime?" i "=" isPrime? i ]
]


priceFraction(N) when N < 0 orelse N > 1 ->
    erlang:error('Values must be between 0 and 1.');
priceFraction(N) when N < 0.06 -> 0.10;
priceFraction(N) when N < 0.11 -> 0.18;
priceFraction(N) when N < 0.16 -> 0.26;
priceFraction(N) when N < 0.21 -> 0.32;
priceFraction(N) when N < 0.26 -> 0.38;
priceFraction(N) when N < 0.31 -> 0.44;
priceFraction(N) when N < 0.36 -> 0.50;
priceFraction(N) when N < 0.41 -> 0.54;
priceFraction(N) when N < 0.46 -> 0.58;
priceFraction(N) when N < 0.51 -> 0.62;
priceFraction(N) when N < 0.56 -> 0.66;
priceFraction(N) when N < 0.61 -> 0.70;
priceFraction(N) when N < 0.66 -> 0.74;
priceFraction(N) when N < 0.71 -> 0.78;
priceFraction(N) when N < 0.76 -> 0.82;
priceFraction(N) when N < 0.81 -> 0.86;
priceFraction(N) when N < 0.86 -> 0.90;
priceFraction(N) when N < 0.91 -> 0.94;
priceFraction(N) when N < 0.96 -> 0.98;
priceFraction(N) -> 1.00.


#lang racket

(require math/number-theory)

(define limit 1000000)

(define table
  (for/fold ([table (hash)] [prev 2] #:result table)
            ([p (in-list (next-primes 2 (sub1 limit)))])
    (define p-mod (modulo p 10))
    (values (hash-update table (cons prev p-mod) add1 0) p-mod)))

(define (pair<? p q) (or (< (car p) (car q)) (and (= (car p) (car q)) (< (cdr p) (cdr q)))))

(printf "~a first primes. Transitions prime % 10 → next-prime % 10.\n" limit)
(for ([item (sort (hash->list table) pair<? #:key car)])
  (match-define (cons (cons x y) freq) item)
  (printf "~a → ~a count: ~a frequency: ~a %\n"
          x y (~a freq #:min-width 8 #:align 'right) (~r (* 100 freq (/ 1 limit)) #:precision '(= 2))))


use Math::Primesieve;

my %conspiracy;
my $upto = 1_000_000;
my $sieve = Math::Primesieve.new;
my @primes = $sieve.n-primes($upto+1);

@primes[^($upto+1)].reduce: -> $a, $b {
    my $d = $b % 10;
    %conspiracy{"$a → $d count:"}++;
    $d;
}

say "$_ \tfrequency: {($_.value/$upto*100).round(.01)} %" for %conspiracy.sort;


/*REXX pgm shows a table of what last digit follows the previous last digit for N primes*/
parse arg N .                                    /*N:  the number of primes to be genned*/
if N=='' | N==","  then N= 1000000               /*Not specified?  Then use the default.*/
Np= N+1;                w= length(N-1)           /*W:  width used for formatting output.*/
H= N* (2**max(4, (w%2+1) ) )                     /*used as a rough limit for the sieve. */
@.= .                                            /*assume all numbers are prime (so far)*/
#= 1                                             /*primes found so far {assume prime 2}.*/
     do j=3  by 2;     if @.j==''  then iterate  /*Is composite?  Then skip this number.*/
     #= #+1                                      /*bump the prime number counter.       */
             do m=j*j  to H  by j+j;    @.m=     /*strike odd multiples as composite.   */
             end   /*m*/
     if #==Np  then leave                        /*Enough primes?   Then done with gen. */
     end   /*j*/                                 /* [↑]  gen using Eratosthenes' sieve. */
!.= 0                                            /*initialize all the frequency counters*/
say 'For '   N   " primes used in this study:"   /*show hdr information about this run. */
r= 2                                             /*the last digit of the very 1st prime.*/
#= 1                                             /*the number of primes looked at so far*/
     do i=3  by 2;     if @.i==''  then iterate  /*This number composite? Then ignore it*/
     #= # + 1;         parse var  i   ''  -1  x  /*bump prime counter; get its last dig.*/
     !.r.x= !.r.x +1;  r= x                      /*bump the last digit counter for prev.*/
     if #==Np  then leave                        /*Done?   Then leave this  DO  loop.   */
     end   /*i*/                                 /* [↑]  examine almost all odd numbers.*/
say                                              /* [↓]  display the results to the term*/
     do    d=1  for 9; if d//2 | d==2  then say  /*display a blank line (if appropriate)*/
        do f=1  for 9; if !.d.f==0  then iterate /*don't show if the count is zero.     */
        say 'digit '      d      "──►"       f        ' has a count of: ',
             right(!.d.f, w)",  frequency of:"   right(format(!.d.f / N*100, , 4)'%.', 10)
        end   /*f*/
     end      /*d*/                              /*stick a fork in it,  we're all done. */


def powerSetRec(head, tail) {
    if (!tail) return [head]
    powerSetRec(head, tail.tail()) + powerSetRec(head + [tail.head()], tail.tail())
}

def powerSet(set) { powerSetRec([], set as List) as Set}


import Data.Set
import Control.Monad

powerset :: Ord a => Set a -> Set (Set a)
powerset = fromList . fmap fromList . listPowerset . toList

listPowerset :: [a] -> [[a]]
listPowerset = filterM (const [True, False])


MsgBox % IsPrime(1995937)
Loop
   MsgBox % A_Index-3 . " is " . (IsPrime(A_Index-3) ? "" : "not ") . "prime."

IsPrime(n,k=2) { ; testing primality with trial divisors not multiple of 2,3,5, up to sqrt(n)
   d := k+(k<7 ? 1+(k>2) : SubStr("6-----4---2-4---2-4---6-----2",Mod(k,30),1))
   Return n < 3 ? n>1 : Mod(n,k) ? (d*d <= n ? IsPrime(n,d) : 1) : 0
}


#cs ----------------------------------------------------------------------------

 AutoIt Version: 3.3.8.1
 Author:         Alexander Alvonellos

 Script Function:
	Perform primality test on a given integer $number.
	RETURNS: TRUE/FALSE

#ce ----------------------------------------------------------------------------
Func main()
	ConsoleWrite("The primes up to 100 are: " & @LF)
	For $i = 1 To 100 Step 1
		If(isPrime($i)) Then
			If($i <> 97) Then
				ConsoleWrite($i & ", ")
			Else
				ConsoleWrite($i)
			EndIf
		EndIf
	Next
EndFunc

Func isPrime($n)
	If($n < 2) Then Return False
	If($n = 2) Then Return True
	If(BitAnd($n, 1) = 0) Then Return False
	For $i = 3 To Sqrt($n) Step 2
		If(Mod($n, $i) = 0) Then Return False
	Next
	Return True
EndFunc
main()


require "prime"

def prime_conspiracy(m)
  conspiracy = Hash.new(0)
  Prime.take(m).map{|n| n%10}.each_cons(2){|a,b| conspiracy[[a,b]] += 1}
  puts "#{m} first primes. Transitions prime % 10 → next-prime % 10."
  conspiracy.sort.each do |(a,b),v|
    puts "%d → %d count:%10d frequency:%7.4f %" % [a, b, v, 100.0*v/m]
  end
end

prime_conspiracy(1_000_000)


// main.rs
mod bit_array;
mod prime_sieve;

use prime_sieve::PrimeSieve;

// See https://en.wikipedia.org/wiki/Prime_number_theorem#Approximations_for_the_nth_prime_number
fn upper_bound_for_nth_prime(n: usize) -> usize {
    let x = n as f64;
    (x * (x.ln() + x.ln().ln())) as usize
}

fn compute_transitions(limit: usize) {
    use std::collections::BTreeMap;
    let mut transitions = BTreeMap::new();
    let mut prev = 2;
    let mut count = 0;
    let sieve = PrimeSieve::new(upper_bound_for_nth_prime(limit));
    let mut n = 3;
    while count < limit {
        if sieve.is_prime(n) {
            count += 1;
            let digit = n % 10;
            let key = (prev, digit);
            if let Some(v) = transitions.get_mut(&key) {
                *v += 1;
            } else {
                transitions.insert(key, 1);
            }
            prev = digit;
        }
        n += 2;
    }
    println!("First {} prime numbers:", limit);
    for ((from, to), c) in &transitions {
        let freq = 100.0 * (*c as f32) / (limit as f32);
        println!(
            "{} -> {}: count = {:7}, frequency = {:.2} %",
            from, to, c, freq
        );
    }
}

fn main() {
    compute_transitions(1000000);
    println!();
    compute_transitions(100000000);
}


import scala.annotation.tailrec
import scala.collection.mutable

object PrimeConspiracy extends App {
  val limit = 1000000
  val sieveTop = 15485863/*one millionth prime*/ + 1
  val buckets = Array.ofDim[Int](10, 10)
  var prevPrime = 2

  def sieve(limit: Int) = {
    val composite = new mutable.BitSet(sieveTop)
    composite(0) = true
    composite(1) = true

    for (n <- 2 to math.sqrt(limit).toInt)
      if (!composite(n)) for (k <- n * n until limit by n) composite(k) = true
    composite
  }

  val notPrime = sieve(sieveTop)

  def isPrime(n: Long) = {
    @tailrec
    def inner(d: Int, end: Int): Boolean = {
      if (d > end) true
      else if (n % d != 0 && n % (d + 2) != 0) inner(d + 6, end) else false
    }

    n > 1 && ((n & 1) != 0 || n == 2) &&
      (n % 3 != 0 || n == 3) && inner(5, math.sqrt(n).toInt)
  }

  var primeCount = 1
  var n = 3

  while (primeCount < limit) {
    if (!notPrime(n)) {
      val prime = n
      buckets(prevPrime % 10)(prime % 10) += 1
      prevPrime = prime
      primeCount += 1
    }
    n += 1
  }

  for {i <- buckets.indices
       j <- buckets.head.indices} {
    val nPrime = buckets(i)(j)
    if (nPrime != 0) println(f"$i%d -> $j%d : $nPrime%5d  ${nPrime / (limit / 100.0)}%2f")
  }

  println(s"Successfully completed without errors. [total ${scala.compat.Platform.currentTime - executionStart} ms]")
}


procedure power_set (s)
  result := set ()
  if *s = 0
    then insert (result, set ()) # empty set
    else {
      head := set(?s) # take a random element
      # and find powerset of remaining part of set
      tail_pset := power_set (x -- head)
      result ++:= tail_pset # add powerset of remainder to results
      every ps := !tail_pset do # and add head to each powerset from the remainder
        insert (result, ps ++ head)
    }
  return result
end


$ awk 'func prime(n){for(d=2;d<=sqrt(n);d++)if(!(n%d)){return 0};return 1}{print prime($1)}'


isprime(n) {
  auto p;
  if(n<2) return(0);
  if(!(n%2)) return(n==2);
  p=3;
  while(n/p>p) {
    if(!(n%p)) return(0);
    p=p+2;
  }
  return(1);
}


FUNCTION prime% (n!)
  STATIC i AS INTEGER
  IF n = 2 THEN
    prime = 1
  ELSEIF n <= 1 OR n MOD 2 = 0 THEN
    prime = 0
  ELSE
    prime = 1
    FOR i = 3 TO INT(SQR(n)) STEP 2
      IF n MOD i = 0 THEN
        prime = 0
        EXIT FUNCTION
      END IF
    NEXT i
  END IF
END FUNCTION

' Test and display primes 1 .. 50
DECLARE FUNCTION prime% (n!)
FOR n = 1 TO 50
  IF prime(n) = 1 THEN PRINT n;
NEXT n


let cin = [ 0.06m .. 0.05m ..1.01m ]
let cout = [0.1m; 0.18m] @ [0.26m .. 0.06m .. 0.44m] @ [0.50m .. 0.04m .. 0.98m] @ [1.m]

let priceadjuster p =
    let rec bisect lo hi =
        if lo < hi then
            let mid = (lo+hi)/2.
            let left = p < cin.[int mid]
            bisect (if left then lo else mid+1.) (if left then mid else hi)
        else lo

    if p < 0.m || 1.m < p then p
    else cout.[int (bisect 0. (float cin.Length))]

[ 0.m .. 0.01m .. 1.m ]
|> Seq.ofList
|> Seq.iter (fun p -> printfn "%.2f -> %.2f" p (priceadjuster p))


$ include "seed7_05.s7i";
  include "float.s7i";

const func set of integer: eratosthenes (in integer: n) is func
  result
    var set of integer: sieve is EMPTY_SET;
  local
    var integer: i is 0;
    var integer: j is 0;
  begin
    sieve := {2 .. n};
    for i range 2 to sqrt(n) do
      if i in sieve then
        for j range i ** 2 to n step i do
          excl(sieve, j);
        end for;
      end if;
    end for;
  end func;

const type: countHashType is hash [string] integer;

const proc: main is func
  local
    const set of integer: primes is eratosthenes(15485863);
    var integer: lastPrime is 0;
    var integer: currentPrime is 0;
    var string: aKey is "";
    var countHashType: countHash is countHashType.value;
    var integer: count is 0;
    var integer: total is 0;
  begin
    for currentPrime range primes do
      if lastPrime <> 0 then
        incr(total);
        aKey := str(lastPrime rem 10) <& " -> " <& str(currentPrime rem 10);
	if aKey in countHash then
	  incr(countHash[aKey]);
	else
	  countHash @:= [aKey] 1;
	end if;
      end if;
      lastPrime := currentPrime;
    end for;
    for aKey range sort(keys(countHash)) do
      count := countHash[aKey];
      writeln(aKey <& " count: " <& count lpad 5 <& " frequency: " <&
              flt(count * 100)/flt(total) digits 2 lpad 4 <& " %");
    end for;
  end func;


var primes = (^Inf -> lazy.grep{.is_prime})

var upto = 1e6
var conspiracy = Hash()

primes.first(upto+1).reduce { |a,b|
    var d = b%10
    conspiracy{"#{a} → #{d}"} := 0 ++
    d
}

for k,v in (conspiracy.sort_by{|k,_v| k }) {
    printf("%s count: %6s\tfrequency: %2.2f %\n", k, v.commify, v / upto * 100)
}


Option Explicit

Sub Main()
Dim Dict As Object, L() As Long
Dim t As Single

   Init Dict
   L = ListPrimes(100000000)
t = Timer
   PrimeConspiracy L, Dict, 1000000
Debug.Print "----------------------------"
Debug.Print "Execution time : " & Format(Timer - t, "0.000s.")
Debug.Print ""
   Init Dict
t = Timer
   PrimeConspiracy L, Dict, 5000000
Debug.Print "----------------------------"
Debug.Print "Execution time : " & Format(Timer - t, "0.000s.")
End Sub

Private Function ListPrimes(MAX As Long) As Long()
'http://rosettacode.org/wiki/Extensible_prime_generator#VBA
Dim t() As Boolean, L() As Long, c As Long, s As Long, i As Long, j As Long
    ReDim t(2 To MAX)
    ReDim L(MAX \ 2)
    s = Sqr(MAX)
    For i = 3 To s Step 2
        If t(i) = False Then
            For j = i * i To MAX Step i
                t(j) = True
            Next
        End If
    Next i
    L(0) = 2
    For i = 3 To MAX Step 2
        If t(i) = False Then
            c = c + 1
            L(c) = i
        End If
    Next i
    ReDim Preserve L(c)
    ListPrimes = L
End Function

Private Sub Init(d As Object)
   Set d = CreateObject("Scripting.Dictionary")
   d("1 to 1") = 0
   d("1 to 3") = 0
   d("1 to 7") = 0
   d("1 to 9") = 0
   d("2 to 3") = 0
   d("3 to 1") = 0
   d("3 to 3") = 0
   d("3 to 5") = 0
   d("3 to 7") = 0
   d("3 to 9") = 0
   d("5 to 7") = 0
   d("7 to 1") = 0
   d("7 to 3") = 0
   d("7 to 7") = 0
   d("7 to 9") = 0
   d("9 to 1") = 0
   d("9 to 3") = 0
   d("9 to 7") = 0
   d("9 to 9") = 0
End Sub

Private Sub PrimeConspiracy(Primes() As Long, Dict As Object, Nb)
Dim n As Long, temp As String, r, s, K
   For n = LBound(Primes) To Nb
      r = CStr((Primes(n)))
      s = CStr((Primes(n + 1)))
      temp = Right(r, 1) & " to " & Right(s, 1)
      If Dict.Exists(temp) Then Dict(temp) = Dict(temp) + 1
   Next
   Debug.Print Nb & " primes, last prime considered: " & Primes(Nb)
   Debug.Print "Transition  Count     Frequency"
   Debug.Print "==========  =======   ========="
   For Each K In Dict.Keys
      Debug.Print K & "      " & Right("      " & Dict(K), 6) & "    " & Dict(K) / Nb * 100 & "%"
   Next
End Sub


public static ArrayList<String> getpowerset(int a[],int n,ArrayList<String> ps)
    {
        if(n<0)
        {
            return null;
        }
        if(n==0)
        {
            if(ps==null)
                ps=new ArrayList<String>();
            ps.add(" ");
            return ps;
        }
        ps=getpowerset(a, n-1, ps);
        ArrayList<String> tmp=new ArrayList<String>();
        for(String s:ps)
        {
            if(s.equals(" "))
                tmp.add(""+a[n-1]);
            else
                tmp.add(s+a[n-1]);
        }
        ps.addAll(tmp);
        return ps;
    }


function powerset(ary) {
    var ps = [[]];
    for (var i=0; i < ary.length; i++) {
        for (var j = 0, len = ps.length; j < len; j++) {
            ps.push(ps[j].concat(ary[i]));
        }
    }
    return ps;
}

var res = powerset([1,2,3,4]);

load('json2.js');
print(JSON.stringify(res));


for i = 1 to 99
    if isPrime(i) then print string(i); " ";
next i
end

function isPrime(v)
    if v < 2 then return False
    if v mod 2 = 0 then return v = 2
    if v mod 3 = 0 then return v = 3
    d = 5
    while d * d <= v
        if v mod d = 0 then return False else d += 2
    end while
    return True
end function


      FOR i% = -1 TO 100
        IF FNisprime(i%) PRINT ; i% " is prime"
      NEXT
      END

      DEF FNisprime(n%)
      IF n% <= 1 THEN = FALSE
      IF n% <= 3 THEN = TRUE
      IF (n% AND 1) = 0 THEN = FALSE
      LOCAL t%
      FOR t% = 3 TO SQR(n%) STEP 2
        IF n% MOD t% = 0 THEN = FALSE
      NEXT
      = TRUE


class Defn // to hold the three numbers from a 'row' in the table
{
  Float low
  Float high
  Float value
  new make (Float low, Float high, Float value)
  {
    this.low = low
    this.high = high
    this.value = value
  }
}

class PriceConverter
{
  Defn[] defns := [,]
  new make (Str table) // process given table and store numbers from each row in a defn
  {
    table.split('\n').each |Str line|
    {
      data := line.split
      defns.add (Defn(Float.fromStr(data[1]), Float.fromStr(data[3]), Float.fromStr(data[5])))
    }
  }

  public Float convert (Float price) // convert by looking through list of defns
  {
    Float result := price
    defns.each |Defn defn|
    {
      if (price >= defn.low && price < defn.high)
        result = defn.value
    }
    return result
  }
}

class Main
{
  public static Void main ()
  {
    table := ">=  0.00  <  0.06  :=  0.10
              >=  0.06  <  0.11  :=  0.18
              >=  0.11  <  0.16  :=  0.26
              >=  0.16  <  0.21  :=  0.32
              >=  0.21  <  0.26  :=  0.38
              >=  0.26  <  0.31  :=  0.44
              >=  0.31  <  0.36  :=  0.50
              >=  0.36  <  0.41  :=  0.54
              >=  0.41  <  0.46  :=  0.58
              >=  0.46  <  0.51  :=  0.62
              >=  0.51  <  0.56  :=  0.66
              >=  0.56  <  0.61  :=  0.70
              >=  0.61  <  0.66  :=  0.74
              >=  0.66  <  0.71  :=  0.78
              >=  0.71  <  0.76  :=  0.82
              >=  0.76  <  0.81  :=  0.86
              >=  0.81  <  0.86  :=  0.90
              >=  0.86  <  0.91  :=  0.94
              >=  0.91  <  0.96  :=  0.98
              >=  0.96  <  1.01  :=  1.00"
    converter := PriceConverter (table)
    10.times  // simple test with random values
    {
      price := (0..100).random.toFloat / 100
      echo ("$price -> ${converter.convert (price)}")
    }
  }
}


: as begin parse-word dup while evaluate , repeat 2drop ;

create bounds   as  96 91 86 81 76 71 66 61 56 51 46 41 36 31 26 21 16 11  6  0
create official as 100 98 94 90 86 82 78 74 70 66 62 58 54 50 44 38 32 26 18 10

: [email protected] ( a-bounds -- +n )
  \ (a+n) - a + b = (a+n) + (b - a) = (b+n)
  [ official bounds - ] literal + @ ;

: round ( n-cents -- n-cents' )
  >r bounds begin dup @ [email protected] > while cell+ repeat
  r> drop [email protected] ;


import "/fmt" for Fmt
import "/math" for Int
import "/sort" for Sort

var reportTransitions = Fn.new { |transMap, num|
    var keys = transMap.keys.toList
    Sort.quick(keys)
    System.print("First %(Fmt.dc(0, num)) primes. Transitions prime \% 10 -> next-prime \% 10.")
    for (key in keys) {
        var count = transMap[key]
        var freq = count / num * 100
        System.write("%((key/10).floor) -> %(key%10)  count: %(Fmt.dc(8, count))")
        System.print("  frequency: %(Fmt.f(4, freq, 2))\%")
    }
    System.print()
}

// sieve up to the 10 millionth prime
var start = System.clock
var sieved = Int.primeSieve(179424673)
var transMap = {}
var i = 2 // last digit of first prime (2)
var n = 1 // index of next prime (3) in sieved
for (num in [1e4, 1e5, 1e6, 1e7]) {
    while(n < num) {
        var p = sieved[n]
        // count transition of i -> j
        var j = p % 10
        var k = i*10 + j
        var t = transMap[k]
        if (!t) {
            transMap[k] = 1
        } else {
            transMap[k] = t + 1
        }
        i = j
        n = n + 1
    }
    reportTransitions.call(transMap, n)
}
System.print("Took %(System.clock - start) seconds.")


const CNT  =0d1_000_000;
sieve     :=Import("sieve.zkl",False,False,False).postponed_sieve;
conspiracy:=Dictionary();
Utils.Generator(sieve).reduce(CNT,'wrap(digit,p){
   d:=p%10;
   conspiracy.incV("%d → %d count:".fmt(digit,d));
   d
});
foreach key in (conspiracy.keys.sort()){ v:=conspiracy[key].toFloat();
   println("%s%,6d\tfrequency: %2.2F%".fmt(key,v,v/CNT *100))
}


def powerset:
  reduce .[] as $i ([[]];
     reduce .[] as $r (.; . + [$r + [$i]]));


function powerset{T}(x::Vector{T})
    result = Vector{T}[[]]
    for elem in x, j in eachindex(result)
        push!(result, [result[j] ; elem])
    end
    result
end


/* Return 1 if n is prime, 0 otherwise */
define p(n) {
    auto i

    if (n < 2) return(0)
    if (n == 2) return(1)
    if (n % 2 == 0) return(0)
    for (i = 3; i * i <= n; i += 2) {
        if (n % i == 0) return(0)
    }
    return(1)
}


get "libhdr"

let sqrt(s) =
    s <= 1 -> 1,
    valof
$(  let x0 = s >> 1
    let x1 = (x0 + s/x0) >> 1
    while x1 < x0
    $(  x0 := x1
        x1 := (x0 + s/x0) >> 1
    $)
    resultis x0
$)

let isprime(n) =
    n < 2       -> false,
    (n & 1) = 0 -> n = 2,
    valof
$(  for i = 3 to sqrt(n) by 2
        if n rem i = 0 resultis false
    resultis true
$)

let start() be
$(  for i=1 to 100
        if isprime(i) then writef("%N ",i)
    wrch('*N')
$)


// purely functional & lazy version, leveraging recursion and Sequences (a.k.a. streams)
fun <T> Set<T>.subsets(): Sequence<Set<T>> =
    when (size) {
        0 -> sequenceOf(emptySet())
        else -> {
            val head = first()
            val tail = this - head
            tail.subsets() + tail.subsets().map { setOf(head) + it }
        }
    }

// if recursion is an issue, you may change it this way:

fun <T> Set<T>.subsets(): Sequence<Set<T>> = sequence {
    when (size) {
        0 -> yield(emptySet<T>())
        else -> {
            val head = first()
            val tail = this@subsets - head
            yieldAll(tail.subsets())
            for (subset in tail.subsets()) {
                yield(setOf(head) + subset)
            }
        }
    }
}


' FB 1.050.0 Win64

Function rescale(price As Double) As Double
  If price < 0.00 OrElse price > 1.00 Then Return price
  Select Case price
    Case Is < 0.06 : Return 0.10
    Case Is < 0.11 : Return 0.18
    Case Is < 0.16 : Return 0.26
    Case Is < 0.21 : Return 0.32
    Case Is < 0.26 : Return 0.38
    Case Is < 0.31 : Return 0.44
    Case Is < 0.36 : Return 0.50
    Case Is < 0.41 : Return 0.54
    Case Is < 0.46 : Return 0.58
    Case Is < 0.51 : Return 0.62
    Case Is < 0.56 : Return 0.66
    Case Is < 0.61 : Return 0.70
    Case Is < 0.66 : Return 0.74
    Case Is < 0.71 : Return 0.78
    Case Is < 0.76 : Return 0.82
    Case Is < 0.81 : Return 0.86
    Case Is < 0.86 : Return 0.90
    Case Is < 0.91 : Return 0.94
    Case Is < 0.96 : Return 0.98
  End Select
  Return 1.00
End Function

For i As Integer = 1 To 100
  Dim d As Double = i/100.0
  Print Using "#.##"; d;
  Print " -> ";
  Print Using "#.##"; rescale(d);
  Print "  ";
  If i Mod 5 = 0 Then Print
Next

Print
Print "Press any key to quit"
Sleep


to powerset :set
  if empty? :set [output [[]]]
  localmake "rest powerset butfirst :set
  output sentence  map [sentence first :set ?] :rest  :rest
end

show powerset [1 2 3]
[[1 2 3] [1 2] [1 3] [1] [2 3] [2] [3] []]


:- object(set).

    :- public(powerset/2).

    powerset(Set, PowerSet) :-
        reverse(Set, RSet),
        powerset_1(RSet, [[]], PowerSet).

    powerset_1([], PowerSet, PowerSet).
    powerset_1([X| Xs], Yss0, Yss) :-
        powerset_2(Yss0, X, Yss1),
        powerset_1(Xs, Yss1, Yss).

    powerset_2([], _, []).
    powerset_2([Zs| Zss], X, [Zs, [X| Zs]| Yss]) :-
        powerset_2(Zss, X, Yss).

    reverse(List, Reversed) :-
        reverse(List, [], Reversed).

    reverse([], Reversed, Reversed).
    reverse([Head| Tail], List, Reversed) :-
        reverse(Tail, [Head| List], Reversed).

:- end_object.


int is_prime(unsigned int n)
{
	unsigned int p;
	if (!(n & 1) || n < 2 ) return n == 2;

	/* comparing p*p <= n can overflow */
	for (p = 3; p <= n/p; p += 2)
		if (!(n % p)) return 0;
	return 1;
}


Public Sub Main()
Dim byValue As Byte[] = [10, 18, 26, 32, 38, 44, 50, 54, 58, 62, 66, 70, 74, 78, 82, 86, 90, 94, 98, 100]
Dim byLimit As Byte[] = [6, 11, 16, 21, 26, 31, 36, 41, 46, 51, 56, 61, 66, 71, 76, 81, 86, 91, 96]
Dim byCount, byCheck As Byte

For byCount = 0 To 100
  For byCheck = 0 To byLimit.Max
    If byCount < byLimit[byCheck] Then Break
  Next
  Print Format(byCount / 100, "0.00") & " = " & Format(byValue[byCheck] / 100, "0.00") & gb.Tab;
  If byCount Mod 5 = 0 Then Print
Next

End


--returns the powerset of s, out of order.
function powerset(s, start)
  start = start or 1
  if(start > #s) then return {{}} end
  local ret = powerset(s, start + 1)
  for i = 1, #ret do
    ret[#ret + 1] = {s[start], unpack(ret[i])}
  end
  return ret
end

--non-recurse implementation
function powerset(s)
   local t = {{}}
   for i = 1, #s do
      for j = 1, #t do
         t[#t+1] = {s[i],unpack(t[j])}
      end
   end
   return t
end

--alternative, copied from the Python implementation
function powerset2(s)
  local ret = {{}}
  for i = 1, #s do
    local k = #ret
    for j = 1, k do
      ret[k + j] = {s[i], unpack(ret[j])}
    end
  end
  return ret
end


define(`for',
  `ifelse($#, 0, ``$0'',
          eval($2 <= $3), 1,
          `pushdef(`$1', `$2')$4`'popdef(
             `$1')$0(`$1', incr($2), $3, `$4')')')dnl
define(`nth',
  `ifelse($1, 1, $2,
          `nth(decr($1), shift(shift([email protected])))')')dnl
define(`range',
  `for(`x', eval($1 + 2), eval($2 + 2),
       `nth(x, [email protected])`'ifelse(x, eval($2+2), `', `,')')')dnl
define(`powerpart',
  `{range(2, incr($1), [email protected])}`'ifelse(incr($1), $#, `',
     `for(`x', eval($1+2), $#,
        `,powerpart(incr($1), ifelse(
           eval(2 <= ($1 + 1)), 1,
           `range(2,incr($1), [email protected]), ')`'nth(x, [email protected])`'ifelse(
              eval((x + 1) <= $#),1,`,range(incr(x), $#, [email protected])'))')')')dnl
define(`powerset',
  `{powerpart(0, substr(`$1', 1, eval(len(`$1') - 2)))}')dnl
dnl
powerset(`{a,b,c}')


static bool isPrime(int n)
        {
            if (n <= 1) return false;
            for (int i = 2; i * i <= n; i++)
                if (n % i == 0) return false;
            return true;
        }


#include <cmath>

bool is_prime(unsigned int n)
{
    if (n <= 1)
        return false;
    if (n == 2)
        return true;
    for (unsigned int i = 2; i <= sqrt(n); ++i)
        if (n % i == 0)
            return false;
    return true;
}


package main

import "fmt"

func pf(v float64) float64 {
    switch {
    case v < .06:
        return .10
    case v < .11:
        return .18
    case v < .16:
        return .26
    case v < .21:
        return .32
    case v < .26:
        return .38
    case v < .31:
        return .44
    case v < .36:
        return .50
    case v < .41:
        return .54
    case v < .46:
        return .58
    case v < .51:
        return .62
    case v < .56:
        return .66
    case v < .61:
        return .70
    case v < .66:
        return .74
    case v < .71:
        return .78
    case v < .76:
        return .82
    case v < .81:
        return .86
    case v < .86:
        return .90
    case v < .91:
        return .94
    case v < .96:
        return .98
    }
    return 1
}

func main() {
    tests := []float64{0.3793, 0.4425, 0.0746, 0.6918, 0.2993,
        0.5486, 0.7848, 0.9383, 0.2292, 0.9760}
    for _, v := range tests {
        fmt.Printf("%0.4f -> %0.2f\n", v, pf(v))
    }
}


function pset = powerset(theSet)

    pset = cell(size(theSet)); %Preallocate memory

    %Generate all numbers from 0 to 2^(num elements of the set)-1
    for i = ( 0:(2^numel(theSet))-1 )

        %Convert i into binary, convert each digit in binary to a boolean
        %and store that array of booleans
        indicies = logical(bitget( i,(1:numel(theSet)) ));

        %Use the array of booleans to extract the members of the original
        %set, and store the set containing these members in the powerset
        pset(i+1) = {theSet(indicies)};

    end

end


proc is_prime(n)
{
    if n == 2 then
        return true;
    if n <= 1 || n % 2 == 0 then
        return false;
    for i in 3..floor(sqrt(n)):int by 2 do
        if n % i == 0 then
            return false;
    return true;
}


isqrt = proc (s: int) returns (int)
    x0: int := s/2
    if x0=0 then return(s) end
    x1: int := (x0 + s/x0)/2
    while x1 < x0 do
        x0 := x1
        x1 := (x0 + s/x0)/2
    end
    return(x0)
end isqrt

prime = proc (n: int) returns (bool)
    if n<=2 then return(n=2) end
    if n//2=0 then return(false) end
    for d: int in int$from_to_by(3,isqrt(n),2) do
        if n//d=0 then return(false) end
    end
    return(true)
end prime

start_up = proc ()
    po: stream := stream$primary_input()
    for i: int in int$from_to(1,100) do
        if prime(i) then
            stream$puts(po, int$unparse(i) || " ")
        end
    end
end start_up


import sets, hashes

proc hash(x: HashSet[int]): Hash =
  var h = 0
  for i in x: h = h !& hash(i)
  result = !$h

proc powerset[T](inset: HashSet[T]): HashSet[HashSet[T]] =
  result.incl(initHashSet[T]())  # Initialized with empty set.
  for val in inset:
    let previous = result
    for aSet in previous:
      var newSet = aSet
      newSet.incl(val)
      result.incl(newSet)

echo powerset([1,2,3,4].toHashSet())


#import <Foundation/Foundation.h>

+ (NSArray *)powerSetForArray:(NSArray *)array {
	UInt32 subsetCount = 1 << array.count;
	NSMutableArray *subsets = [NSMutableArray arrayWithCapacity:subsetCount];
	for(int subsetIndex = 0; subsetIndex < subsetCount; subsetIndex++) {
		NSMutableArray *subset = [[NSMutableArray alloc] init];
		for (int itemIndex = 0; itemIndex < array.count; itemIndex++) {
			if((subsetIndex >> itemIndex) & 0x1) {
				[subset addObject:array[itemIndex]];
			}
		}
		[subsets addObject:subset];
	}
	return subsets;
}


# Prime predicate: does n be a prime number? Sets var to true or false.
function(primep var n)
  if(n GREATER 2)
    math(EXPR odd "${n} % 2")
    if(odd)
      # n > 2 and n is odd.
      set(factor 3)
      # Loop for odd factors from 3, while factor <= n / factor.
      math(EXPR quot "${n} / ${factor}")
      while(NOT factor GREATER quot)
        math(EXPR rp "${n} % ${factor}")        # Trial division
        if(NOT rp)
          # factor divides n, so n is not prime.
          set(${var} false PARENT_SCOPE)
          return()
        endif()
        math(EXPR factor "${factor} + 2")       # Next odd factor
        math(EXPR quot "${n} / ${factor}")
      endwhile(NOT factor GREATER quot)
      # Loop found no factor, so n is prime.
      set(${var} true PARENT_SCOPE)
    else()
      # n > 2 and n is even, so n is not prime.
      set(${var} false PARENT_SCOPE)
    endif(odd)
  elseif(n EQUAL 2)
    set(${var} true PARENT_SCOPE)       # 2 is prime.
  else()
    set(${var} false PARENT_SCOPE)      # n < 2 is not prime.
  endif()
endfunction(primep)


module PowerSet(S: Set.S) =
struct

  include Set.Make (S)

  let map f s =
    let work x r = add (f x) r in
    fold work s empty
  ;;

  let powerset s =
    let base = singleton (S.empty) in
    let work x r = union r (map (S.add x) r) in
    S.fold work s base
  ;;

end;; (* PowerSet *)


{string} s={"A","B","C","D"};
range r=1.. ftoi(pow(2,card(s)));
{string} s2 [k in r] = {i | i in s: ((k div (ftoi(pow(2,(ord(s,i))))) mod 2) == 1)};

execute
{
 writeln(s2);
}


declare
  %% Given a set as a list, returns its powerset (again as a list)
  fun {Powerset Set}
     proc {Describe Root}
        %% Describe sets by lower bound (nil) and upper bound (Set)
        Root = {FS.var.bounds nil Set}
        %% enumerate all possible sets
        {FS.distribute naive [Root]}
     end
     AllSets = {SearchAll Describe}
  in
     %% convert to list representation
     {Map AllSets FS.reflect.lowerBoundList}
  end
in
  {Inspect {Powerset [1 2 3 4]}}


       Identification Division.
       Program-Id. Primality-By-Subdiv.

       Data Division.
       Working-Storage Section.
       78  True-Val  Value 0.
       78  False-Val Value 1.

       Local-Storage Section.
       01  lim Pic 9(10).
       01  i   Pic 9(10).

       Linkage Section.
       01  num    Pic 9(10).
       01  result Pic 9.

       Procedure Division Using num result.
       Main.
           If num <= 1
               Move False-Val To result
               Goback
           Else If num = 2
               Move True-Val To result
               Goback
           End-If

           Compute lim = Function Sqrt(num) + 1
           Perform Varying i From 3 By 1 Until lim < i
               If Function Mod(num, i) = 0
                   Move False-Val To result
                   Goback
               End-If
           End-Perform

           Move True-Val To Result

           Goback
           .


is_prime = (n) ->
  # simple prime detection using trial division, works
  # for all integers
  return false if n <= 1 # by definition
  p = 2
  while p * p <= n
    return false if n % p == 0
    p += 1
  true

for i in [-1..100]
  console.log i if is_prime i


use Algorithm::Combinatorics "subsets";
my @S = ("a","b","c");
my @PS;
my $iter = subsets(\@S);
while (my $p = $iter->next) {
  push @PS, "[@$p]"
}
say join("  ",@PS);


(defun primep (n)
  "Is N prime?"
  (and (> n 1)
       (or (= n 2) (oddp n))
       (loop for i from 3 to (isqrt n) by 2
	  never (zerop (rem n i)))))


Mathematicaly basis of Prime Generators
https://www.academia.edu/19786419/PRIMES-UTILS_HANDBOOK
https://www.academia.edu/42734410/Improved_Primality_Testing_and_Factorization_in_Ruby_revised


Home is a room.

Price is a kind of value. 0.99 specifies a price.

Table of Price Standardization
upper bound	replacement
0.06		0.10
0.11		0.18
0.16		0.26
0.21		0.32
0.26		0.38
0.31		0.44
0.36		0.50
0.41		0.54
0.46		0.58
0.51		0.62
0.56		0.66
0.61		0.70
0.66		0.74
0.71		0.78
0.76		0.82
0.81		0.86
0.86		0.90
0.91		0.94
0.96		0.98
1.01		1.00

To decide which price is the standardized value of (P - price):
	repeat with N running from 1 to the number of rows in the Table of Price Standardization:
		choose row N in the Table of Price Standardization;
		if P is less than the upper bound entry, decide on the replacement entry.

When play begins:
	repeat with N running from 1 to 5:
		let P be a random price between 0.00 and 1.00;
		say "[P] -> [standardized value of P].";
	end the story.


sequence powerset
integer step = 1

function pst(object key, object /*data*/, object /*user_data*/)
    integer k = 1
    while k<length(powerset) do
        k += step
        for j=1 to step do
            powerset[k] = append(powerset[k],key)
            k += 1
        end for
    end while
    step *= 2
    return 1
end function

function power_set(integer d)
    powerset = repeat({},power(2,dict_size(d)))
    step = 1
    traverse_dict(routine_id("pst"),0,d)
    return powerset
end function

integer d1234 = new_dict({{1,0},{2,0},{3,0},{4,0}})
?power_set(d1234)
integer d0 = new_dict()
?power_set(d0)
setd({},0,d0)
?power_set(d0)


<?php
function get_subset($binary, $arr) {
  // based on true/false values in $binary array, include/exclude
  // values from $arr
  $subset = array();
  foreach (range(0, count($arr)-1) as $i) {
    if ($binary[$i]) {
      $subset[] = $arr[count($arr) - $i - 1];
    }
  }
  return $subset;
}

function print_array($arr) {
  if (count($arr) > 0) {
    echo join(" ", $arr);
  } else {
    echo "(empty)";
  }
  echo '
';
}

function print_power_sets($arr) {
  echo "POWER SET of [" . join(", ", $arr) . "]
";
  foreach (power_set($arr) as $subset) {
    print_array($subset);
  }
}

function power_set($arr) {
  $binary = array();
  foreach (range(1, count($arr)) as $i) {
    $binary[] = false;
  }
  $n = count($arr);
  $powerset = array();

  while (count($binary) <= count($arr)) {
    $powerset[] = get_subset($binary, $arr);
    $i = 0;
    while (true) {
      if ($binary[$i]) {
        $binary[$i] = false;
        $i += 1;
      } else {
        $binary[$i] = true;
        break;
      }
    }
    $binary[$i] = true;
  }

  return $powerset;
}

print_power_sets(array());
print_power_sets(array('singleton'));
print_power_sets(array('dog', 'c', 'b', 'a'));
?>


import std.stdio, std.algorithm, std.range, std.math;

bool isPrime1(in int n) pure nothrow {
    if (n == 2)
        return true;
    if (n <= 1 || (n & 1) == 0)
        return false;

    for(int i = 3; i <= real(n).sqrt; i += 2)
        if (n % i == 0)
            return false;
    return true;
}

void main() {
    iota(2, 40).filter!isPrime1.writeln;
}


function IsPrime(aNumber: Integer): Boolean;
var
  I: Integer;
begin
  Result:= True;
  if(aNumber = 2) then Exit;

  Result:= not ((aNumber mod 2 = 0)  or
                (aNumber <= 1));
  if not Result then Exit;

  for I:=3 to Trunc(Sqrt(aNumber)) do
  if(aNumber mod I = 0) then
  begin
    Result:= False;
    Break;
  end;
end;


import java.util.Random;

public class Main {
	private static float priceFraction(float f) {
		if (0.00f <= f && f < 0.06f) return 0.10f;
		else if (f < 0.11f) return 0.18f;
		else if (f < 0.16f) return 0.26f;
		else if (f < 0.21f) return 0.32f;
		else if (f < 0.26f) return 0.38f;
		else if (f < 0.31f) return 0.44f;
		else if (f < 0.36f) return 0.50f;
		else if (f < 0.41f) return 0.54f;
		else if (f < 0.46f) return 0.58f;
		else if (f < 0.51f) return 0.62f;
		else if (f < 0.56f) return 0.66f;
		else if (f < 0.61f) return 0.70f;
		else if (f < 0.66f) return 0.74f;
		else if (f < 0.71f) return 0.78f;
		else if (f < 0.76f) return 0.82f;
		else if (f < 0.81f) return 0.86f;
		else if (f < 0.86f) return 0.90f;
		else if (f < 0.91f) return 0.94f;
		else if (f < 0.96f) return 0.98f;
		else if (f < 1.01f) return 1.00f;
		else throw new IllegalArgumentException();
	}

	public static void main(String[] args) {
		Random rnd = new Random();
		for (int i = 0; i < 5; i++) {
			float f = rnd.nextFloat();
			System.out.format("%8.6f -> %4.2f%n", f, priceFraction(f));
		}
	}
}


(de powerset (Lst)
   (ifn Lst
      (cons)
      (let L (powerset (cdr Lst))
         (conc
            (mapcar '((X) (cons (car Lst) X)) L)
            L ) ) ) )


*process source attributes xref or(!);
 /*--------------------------------------------------------------------
 * 06.01.2014 Walter Pachl  translated from REXX
 *-------------------------------------------------------------------*/
 powerset: Proc Options(main);
 Dcl (hbound,index,left,substr) Builtin;
 Dcl sysprint Print;
 Dcl s(4) Char(5) Var Init('one','two','three','four');
 Dcl ps   Char(1000) Var;
 Dcl (n,chunk,p) Bin Fixed(31);
 n=hbound(s);                      /* number of items in the list.   */
 ps='{} ';                         /* start with a null power set.   */
 Do chunk=1 To n;                  /* loop through the ...     .     */
   ps=ps!!combn(chunk);            /* a CHUNK at a time.             */
   End;
 Do While(ps>'');
   p=index(ps,' ');
   Put Edit(left(ps,p-1))(Skip,a);
   ps=substr(ps,p+1);
   End;

 combn: Proc(y) Returns(Char(1000) Var);
 /*--------------------------------------------------------------------
 * returns the list of subsets with y elements of set s
 *-------------------------------------------------------------------*/
 Dcl (y,base,bbase,ym,p,j,d,u) Bin Fixed(31);
 Dcl (z,l) Char(1000) Var Init('');
 Dcl a(20) Bin Fixed(31) Init((20)0);
 Dcl i Bin Fixed(31);
 base=hbound(s)+1;
 bbase=base-y;
 ym=y-1;
 Do p=1 To y;
   a(p)=p;
   End;
 Do j=1 By 1;
   l='';
   Do d=1 To y;
     u=a(d);
     l=l!!','!!s(u);
     End;
   z=z!!'{'!!substr(l,2)!!'} ';
   a(y)=a(y)+1;
   If a(y)=base Then
     If combu(ym) Then
       Leave;
   End;
 /* Put Edit('combn',y,z)(Skip,a,f(2),x(1),a); */
 Return(z);

 combu: Proc(d) Recursive Returns(Bin Fixed(31));
 Dcl (d,u) Bin Fixed(31);
 If d=0 Then
   Return(1);
 p=a(d);
 Do u=d To y;
   a(u)=p+1;
   If a(u)=bbase+u Then
     Return(combu(u-1));
   p=a(u);
   End;
 Return(0);
 End;
 End;

 End;


def isPrime(n :int) {
    if (n == 2) {
        return true
    } else if (n <= 1 || n %% 2 == 0) {
        return false
    } else {
        def limit := (n :float64).sqrt().ceil()
        var divisor := 1
        while ((divisor += 2) <= limit) {
            if (n %% divisor == 0) {
                return false
            }
        }
        return true
    }
}


function power-set ($array) {
    if($array) {
        $n = $array.Count
        function state($set, $i){
            if($i -gt -1) {
                state $set ($i-1)
                state ($set[email protected]($array[$i])) ($i-1)
            } else {
                "$($set | sort)"
            }
        }
        $set = state @() ($n-1)
        $power = 0..($set.Count-1) | foreach{@(0)}
        $i = 0
        $set | sort | foreach{$power[$i++] = $_.Split()}
        $power | sort {$_.Count}
    } else {@()}

}
$OFS = " "
$setA = power-set  @(1,2,3,4)
"number of sets in setA: $($setA.Count)"
"sets in setA:"
$OFS = ", "
$setA | foreach{"{"+"$_"+"}"}
$setB = @()
"number of sets in setB: $($setB.Count)"
"sets in setB:"
$setB | foreach{"{"+"$_"+"}"}
$setC = @(@(), @(@()))
"number of sets in setC: $($setC.Count)"
"sets in setC:"
$setC | foreach{"{"+"$_"+"}"}
$OFS = " "


class
	APPLICATION

create
	make

feature

	make
                -- Tests the feature is_prime.
		do
			io.put_boolean (is_prime (1))
			io.new_line
			io.put_boolean (is_prime (2))
			io.new_line
			io.put_boolean (is_prime (3))
			io.new_line
			io.put_boolean (is_prime (4))
			io.new_line
			io.put_boolean (is_prime (97))
			io.new_line
			io.put_boolean (is_prime (15589))
			io.new_line
		end

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

end


defmodule RC do
  def is_prime(2), do: true
  def is_prime(n) when n<2 or rem(n,2)==0, do: false
  def is_prime(n), do: is_prime(n,3)

  def is_prime(n,k) when n<k*k, do: true
  def is_prime(n,k) when rem(n,k)==0, do: false
  def is_prime(n,k), do: is_prime(n,k+2)
end

IO.inspect for n <- 1..50, RC.is_prime(n), do: n


const PFCUT = [6:5:101]//100
const PFVAL = [10:8:26, 32:6:50, 54:4:98, 100]//100

function pricefraction{T<:FloatingPoint}(a::T)
    zero(T) <= a || error("a = ", a, ", but it must be >= 0.")
    a <= one(T) || error("a = ", a, ", but it must be <= 1.")
    convert(T, PFVAL[findfirst(a .< PFCUT)])
end

test = [0.:0.05:1., 0.51, 0.56, 0.61, rand(), rand(), rand(), rand()]

println("Testing the price fraction function")
for t in test
    println(@sprintf "    %.4f -> %.4f" t pricefraction(t))
end


powerset(X,Y) :- bagof( S, subseq(S,X), Y).

subseq( [], []).
subseq( [], [_|_]).
subseq( [X|Xs], [X|Ys] ) :- subseq(Xs, Ys).
subseq( [X|Xs], [_|Ys] ) :- append(_, [X|Zs], Ys), subseq(Xs, Zs).


If OpenConsole()
  Define argc=CountProgramParameters()
  If argc>=(SizeOf(Integer)*8) Or argc<1
    PrintN("Set out of range.")
    End 1
  Else
    Define i, j, text$
    Define.q bset=1<<argc
    Print("{")
    For i=0 To bset-1   ; check all binary combinations
      If Not i: text$=  "{"
      Else    : text$=", {"
      EndIf
      k=0
      For j=0 To argc-1  ; step through each bit
        If i&(1<<j)
          If k: text$+", ": EndIf         ; pad the output
          text$+ProgramParameter(j): k+1  ; append each matching bit
        EndIf
      Next j
      Print(text$+"}")
    Next i
    PrintN("}")
  EndIf
EndIf


(defun prime (a)
  (not (or (< a 2)
           (cl-loop for x from 2 to (sqrt a)
                    when (zerop (% a x))
                    return t))))


is_prime(N) when N == 2 -> true;
is_prime(N) when N < 2 orelse N rem 2 == 0 -> false;
is_prime(N) -> is_prime(N,3).

is_prime(N,K) when K*K > N -> true;
is_prime(N,K) when N rem K == 0 -> false;
is_prime(N,K) -> is_prime(N,K+2).


def list_powerset(lst):
    # the power set of the empty set has one element, the empty set
    result = [[]]
    for x in lst:
        # for every additional element in our set
        # the power set consists of the subsets that don't
        # contain this element (just take the previous power set)
        # plus the subsets that do contain the element (use list
        # comprehension to add [x] onto everything in the
        # previous power set)
        result.extend([subset + [x] for subset in result])
    return result

# the above function in one statement
def list_powerset2(lst):
    return reduce(lambda result, x: result + [subset + [x] for subset in result],
                  lst, [[]])

def powerset(s):
    return frozenset(map(frozenset, list_powerset(list(s))))


(define powerset
  [] -> [[]]
  [A|As] -> (append (map (cons A) (powerset As))
                    (powerset As)))


PROGRAM PRIME_TRIAL

PROCEDURE ISPRIME(N%->OK%)
      LOCAL T%
      IF N%<=1 THEN OK%=FALSE  EXIT PROCEDURE END IF
      IF N%<=3 THEN OK%=TRUE EXIT PROCEDURE END IF
      IF (N% AND 1)=0 THEN OK%=FALSE EXIT PROCEDURE END IF
      FOR T%=3 TO SQR(N%) STEP 2 DO
        IF N% MOD T%=0 THEN OK%=FALSE EXIT PROCEDURE END IF
      END FOR
      OK%=TRUE
END PROCEDURE

BEGIN

      FOR I%=1 TO 100 DO
         ISPRIME(I%->OK%)
         IF OK% THEN PRINT(i%;"is prime") END IF
      END FOR

END PROGRAM


function is_prime(integer n)
    if n<=2 or remainder(n,2)=0 then
        return 0
    else
        for i=3 to sqrt(n) by 2 do
            if remainder(n,i)=0 then
                return 0
            end if
        end for
        return 1
    end if
end function


dim DR(38)    'decimal range
dim PF(38)    'corresponding price fraction
range$="0.06 0.11 0.16 0.21 0.26 0.31 0.36 0.41 0.46 0.51 0.56 0.61 0.66 0.71 0.76 0.81 0.86 0.91 0.96 0.01"
frac$="0.10 0.18 0.26 0.32 0.38 0.44 0.50 0.54 0.58 0.62 0.66 0.70 0.74 0.78 0.82 0.86 0.90 0.94 0.98 1.00"
for i = 1 to 38
  DR(i)=val(word$(range$,i))
  PF(i)=val(word$(frac$,i))
next

for i = 0 to .99 step 0.03
  print i;" -> ";PriceFraction(i)
next
end

Function PriceFraction(n)
    PriceFraction=n  'return original if outside test bounds
    for i = 1 to 38
    if n<=DR(i) then
        PriceFraction=PF(i)
        exit for
    end if
    next
    end function


  [ stack ]                              is (ps).stack
  [ stack ]                              is (ps).items
  [ stack ]                              is (ps).result

  [ 1 - (ps).items put
    0 (ps).stack put
    [] (ps).result put
    [ (ps).result take
      (ps).stack behead
      drop nested join
      (ps).result put
      (ps).stack take
      dup (ps).items share
      = iff
          [ drop
            (ps).stack size 1 > iff
              [ 1 (ps).stack tally ] ]
            else
              [ dup (ps).stack put
                1+ (ps).stack put ]
             (ps).stack size 1 = until ]
    (ps).items release
    (ps).result take ]                   is (ps)     (   n -->   )

  [ dup size dip
      [ witheach
          [ over swap peek swap ] ]
      nip pack ]                         is arrange  ( [ [ --> [ )

  [ dup [] = iff
      nested done
    dup size (ps)
    ' [ [ ] ] swap join
    [] unrot witheach
      [ dip dup arrange
        nested
        rot swap join swap ]
    drop ]                               is powerset (   [ --> [ )

   ' [ [ 1 2 3 4 ] [ ] [ [ ] ] ]
   witheach
     [ say "The powerset of "
       dup echo cr
       powerset witheach [ echo cr ]
       cr ]


for each element in the set:
	for each subset constructed so far:
		new subset = (subset + element)


;;; Direct translation of 'functional' ruby method
(define (powerset s)
  (for/fold ([outer-set (set(set))]) ([element s])
    (set-union outer-set
               (list->set (set-map outer-set
                                   (λ(inner-set) (set-add inner-set element)))))))


open NUnit.Framework
open FsUnit
let inline isPrime n = not ({uint64 2..uint64 (sqrt (double n))} |> Seq.exists (fun (i:uint64) -> uint64 n % i = uint64 0))
[<Test>]
let ``Validate that 2 is prime`` () =
  isPrime 2 |> should equal true

[<Test>]
let ``Validate that 4 is not prime`` () =
  isPrime 4 |> should equal false

[<Test>]
let ``Validate that 3 is prime`` () =
  isPrime 3 |> should equal true

[<Test>]
let ``Validate that 9 is not prime`` () =
  isPrime 9 |> should equal false

[<Test>]
let ``Validate that 5 is prime`` () =
  isPrime 5 |> should equal true

[<Test>]
let ``Validate that 277 is prime`` () =
  isPrime 277 |> should equal true


USING: combinators kernel math math.functions math.ranges sequences ;

: prime? ( n -- ? )
    {
        { [ dup 2 < ] [ drop f ] }
        { [ dup even? ] [ 2 = ] }
        [ 3 over sqrt 2 <range> [ mod 0 > ] with all? ]
    } cond ;


sub powerset(Set $s) { $s.combinations.map(*.Set).Set }
say powerset set <a b c d>;


import Set;

public set[set[&T]] PowerSet(set[&T] s) = power(s);


/*REXX program  displays a  power set;  items may be  anything  (but can't have blanks).*/
parse arg S                                      /*allow the user specify optional set. */
if S=''  then S= 'one two three four'            /*Not specified?  Then use the default.*/
@= '{}'                                          /*start process with a null power set. */
N= words(S);     do chunk=1  for N               /*traipse through the items in the set.*/
                 @[email protected]  combN(N, chunk)            /*take  N  items, a  CHUNK  at a time. */
                 end    /*chunk*/
w= length(2**N)                                  /*the number of items in the power set.*/
                 do k=1  for words(@)            /* [↓]  show combinations,  1 per line.*/
                 say right(k, w)     word(@, k)  /*display a single combination to term.*/
                 end    /*k*/
exit 0                                           /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
combN:  procedure expose S;  parse arg x,y;      base= x + 1;             bbase= base - y
        !.= 0
                         do p=1  for y;          !.p= p
                         end      /*p*/
        $=                                                         /* [↓] build powerset*/
                         do j=1;                 L=
                            do d=1  for y;       L= L','word(S, !.d)
                            end   /*d*/
                         $= $  '{'strip(L, "L", ',')"}";                  !.y= !.y + 1
                         if !.y==base  then  if .combU(y - 1)  then leave
                         end      /*j*/
        return strip($)                          /*return with a partial power set chunk*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
.combU: procedure expose !. y bbase;        parse arg d;           if d==0  then return 1
        p= !.d
                  do u=d  to y;   !.u= p + 1;     if !.u==bbase+u  then return .combU(u-1)
                  p= !.u                                           /*             ↑     */
                  end   /*u*/                                      /*recurse──►───┘     */
        return 0


[0\$2=$[@[email protected]@]?~[$$2>\1&&[\~\
   3[\[email protected][email protected]+\$*>][\[email protected][email protected][email protected][email protected]\/*=[%\~\$]?2+]#%
]?]?%]p:


#APPTYPE CONSOLE

FUNCTION ISPRIME(n AS INTEGER) AS INTEGER
    IF n = 2 THEN
        RETURN TRUE
    ELSEIF n <= 1 ORELSE n MOD 2 = 0 THEN
        RETURN FALSE
    ELSE
        FOR DIM i = 3 TO SQR(n) STEP 2
            IF n MOD i = 0 THEN
                RETURN FALSE
            END IF
        NEXT
        RETURN TRUE
    END IF
END FUNCTION

FUNCTION ISPRIME2(N AS INTEGER) AS INTEGER
    IF N <= 1 THEN RETURN FALSE
    DIM I AS INTEGER = 2
    WHILE I * I <= N
        IF N MOD I = 0 THEN
            RETURN FALSE
        END IF
        I = I + 1
    WEND
    RETURN TRUE
END FUNCTION

' Test and display primes 1 .. 50
DIM n AS INTEGER

FOR n = 1 TO 50
    IF ISPRIME(n) THEN
        PRINT n, " ";
    END IF
NEXT

PAUSE


# Project : Power set

list = ["1", "2", "3", "4"]
see powerset(list)

func powerset(list)
        s = "{"
        for i = 1 to (2 << len(list)) - 1 step 2
             s = s + "{"
             for j = 1 to len(list)
                  if i & (1 << j)
                     s = s + list[j] + ","
                  ok
             next
             if right(s,1) = ","
                s = left(s,len(s)-1)
             ok
             s = s + "},"
        next
        return left(s,len(s)-1) + "}"


# Based on http://johncarrino.net/blog/2006/08/11/powerset-in-ruby/
# See the link if you want a shorter version.
# This was intended to show the reader how the method works.
class Array
  # Adds a power_set method to every array, i.e.: [1, 2].power_set
  def power_set

    # Injects into a blank array of arrays.
    # acc is what we're injecting into
    # you is each element of the array
    inject([[]]) do |acc, you|
      ret = []             # Set up a new array to add into
      acc.each do |i|      # For each array in the injected array,
        ret << i           # Add itself into the new array
        ret << i + [you]   # Merge the array with a new array of the current element
      end
      ret       # Return the array we're looking at to inject more.
    end

  end

  # A more functional and even clearer variant.
  def func_power_set
    inject([[]]) { |ps,item|    # for each item in the Array
      ps +                      # take the powerset up to now and add
      ps.map { |e| e + [item] } # it again, with the item appended to each element
    }
  end
end

#A direct translation of the "power array" version above
require 'set'
class Set
  def powerset
    inject(Set[Set[]]) do |ps, item|
      ps.union ps.map {|e| e.union (Set.new [item])}
    end
  end
end

p [1,2,3,4].power_set
p %w(one two three).func_power_set

p Set[1,2,3].powerset


: prime? ( n -- f )
        dup 2 < if      drop false
    else dup 2 = if      drop true
    else dup 1 and 0= if drop false
    else 3
        begin 2dup dup * >=
        while 2dup mod 0=
              if       2drop false exit
              then 2 +
        repeat         2drop true
    then then then ;


 FUNCTION isPrime(number)
   LOGICAL :: isPrime
   INTEGER, INTENT(IN) :: number
   INTEGER :: i

   IF(number==2) THEN
      isPrime = .TRUE.
   ELSE IF(number < 2 .OR. MOD(number,2) == 0) THEN
      isPRIME = .FALSE.
   ELSE
      isPrime = .TRUE.
      DO i = 3, INT(SQRT(REAL(number))), 2
         IF(MOD(number,i) == 0) THEN
            isPrime = .FALSE.
            EXIT
         END IF
      END DO
   END IF
 END FUNCTION


:- module price.
:- interface.
:- import_module int.
:- type price == int.
:- func standard(price) = price.

:- implementation.
:- import_module require, list.

standard(P) = SP :-
        require(P >= 0, "P must be positive"),
        Cents = P `mod` 100,
        P + adjust(Cents) = SP.

:- func adjust(int) = int.
adjust(Cents) = adjust(Cents, rules).

:- func adjust(int, list(price_rule)) = int.
adjust(_, []) = unexpected("price", "adjust/2", "exhausted rules").
adjust(N, [rule(Low, High, To)|T]) = R :-
        ( N >= Low, N < High -> To - N = R ; adjust(N, T) = R ).

:- type price_rule ---> rule(int, int, int).
:- func rules = list(price_rule).
rules = [rule(00, 06, 10),
        rule(06, 11, 18),
        rule(11, 16, 26),
        rule(16, 21, 32),
        rule(21, 26, 38),
        rule(26, 31, 44),
        rule(31, 36, 50),
        rule(36, 41, 54),
        rule(41, 46, 58),
        rule(46, 51, 62),
        rule(51, 56, 66),
        rule(56, 61, 70),
        rule(61, 66, 74),
        rule(66, 71, 78),
        rule(71, 76, 82),
        rule(76, 81, 86),
        rule(81, 86, 90),
        rule(86, 91, 94),
        rule(91, 96, 98),
        rule(96, 101, 100)].


use std::collections::BTreeSet;

fn powerset<T: Ord + Clone>(mut set: BTreeSet<T>) -> BTreeSet<BTreeSet<T>> {
    if set.is_empty() {
        let mut powerset = BTreeSet::new();
        powerset.insert(set);
        return powerset;
    }
    // Access the first value. This could be replaced with `set.pop_first().unwrap()`
    // But this is an unstable feature
    let entry = set.iter().nth(0).unwrap().clone();
    set.remove(&entry);
    let mut powerset = powerset(set);
    for mut set in powerset.clone().into_iter() {
        set.insert(entry.clone());
        powerset.insert(set);
    }
    powerset
}

fn main() {
    let set = (1..5).collect();
    let set = powerset(set);
    println!("{:?}", set);

    let set = ["a", "b", "c", "d"].iter().collect();
    let set = powerset(set);
    println!("{:?}", set);
}


options mprint mlogic symbolgen source source2;

%macro SubSets (FieldCount = );
data _NULL_;
	Fields = &FieldCount;
	SubSets = 2**Fields;
	call symput ("NumSubSets", SubSets);
run;

%put &NumSubSets;

data inital;
	%do j = 1 %to &FieldCount;
		F&j. = 1;
	%end;
run;

data SubSets;
	set inital;
	RowCount =_n_;
	call symput("SetCount",RowCount);
run;

%put SetCount ;

%do %while (&SetCount < &NumSubSets);

data loop;
	%do j=1 %to &FieldCount;
		if rand('GAUSSIAN') > rand('GAUSSIAN') then F&j. = 1;
	%end;

data SubSets_  ;
set SubSets loop;
run;

proc sort data=SubSets_  nodupkey;
	by F1 - F&FieldCount.;
run;

data Subsets;
	set SubSets_;
	RowCount =_n_;
run;

proc sql noprint;
	select max(RowCount) into :SetCount
	from SubSets;
quit;
run;

%end;
%Mend SubSets;


' FB 1.05.0 Win64

Function isPrime(n As Integer) As Boolean
  If n < 2 Then Return False
  If n = 2 Then Return True
  If n Mod 2  = 0 Then Return False
  Dim limit As Integer = Sqr(n)
  For i As Integer = 3 To limit Step 2
    If n Mod i = 0 Then Return False
  Next
  Return True
End Function

' To test this works, print all primes under 100
For i As Integer = 1 To 99
  If isPrime(i) Then
    Print Str(i); " ";
  End If
Next

Print : Print
Print "Press any key to quit"
Sleep


isPrimeByTrialDivision[x] :=
{
   for p = primes[]
   {
      if p*p > x
         return true
      if x mod p == 0
         return false
   }

   return true
}


PRICFRAC(X)
 ;Outputs a specified value dependent upon the input value
 ;The non-inclusive upper limits are encoded in the PFMAX string, and the values
 ;to convert to are encoded in the PFRES string.
 NEW PFMAX,PFRES,I,RESULT
 SET PFMAX=".06^.11^.16^.21^.26^.31^.36^.41^.46^.51^.56^.61^.66^.71^.76^.81^.86^.91^.96^1.01"
 SET PFRES=".10^.18^.26^.32^.38^.44^.50^.54^.58^.62^.66^.70^.74^.78^.82^.86^.90^.94^.98^1.00"
 Q:(X<0)!(X>1.01) ""
 FOR I=1:1:$LENGTH(PFMAX,"^") Q:($DATA(RESULT)'=0)  SET:X<$P(PFMAX,"^",I) RESULT=$P(PFRES,"^",I)
 KILL PFMAX,PFRES,I
 QUIT RESULT


/* NetRexx */
options replace format comments java crossref symbols nobinary

runSample(arg)
return

-- -----------------------------------------------------------------------------
method runSample(arg) public static
  parse arg in_val .
  if in_val \= '' then test_vals = [in_val]
  else                 test_vals = getTestData()

  say 'Input Adjustment'
  loop tv = 0 to test_vals.length - 1
    in_val = test_vals[tv]
    adjust = priceFraction(in_val)
    say in_val.format(null, 2).right(5) adjust.format(null, 2).right(10)
    end tv

  return

-- -----------------------------------------------------------------------------
method priceFraction(in_val) public static
  out_val = -1
  limit_table = getLimitTable()
  limit_table_K = limit_table.length
  loop p1 = 0 to limit_table_K - 1
    pair = limit_table[p1]
    hi_limit = pair[0]
    adjustmt = pair[1]
    if in_val < hi_limit then do
      out_val = adjustmt
      leave p1
      end
    end p1
  if out_val = -1 then signal IllegalArgumentException('Input' in_val 'is outside of acceptable range.')

  return out_val

-- -----------------------------------------------------------------------------
method getLimitTable() public static returns Rexx[,]
  limit_table = [ -
    [0.06, 0.10], [0.11, 0.18], [0.16, 0.26], [0.21, 0.32], [0.26, 0.38], -
    [0.31, 0.44], [0.36, 0.50], [0.41, 0.54], [0.46, 0.58], [0.51, 0.62], -
    [0.56, 0.66], [0.61, 0.70], [0.66, 0.74], [0.71, 0.78], [0.76, 0.82], -
    [0.81, 0.86], [0.86, 0.90], [0.91, 0.94], [0.96, 0.98], [1.01, 1.00]  -
  ]
  return limit_table

-- -----------------------------------------------------------------------------
method getTestData() private static returns Rexx[]
  test_vals = Rexx[5]
  rng = Random(1024)
  loop tv = 0 to test_vals.length - 1
    test_vals[tv] = rng.nextFloat()
    end tv
  return test_vals


import scala.compat.Platform.currentTime

object Powerset extends App {
  def powerset[A](s: Set[A]) = s.foldLeft(Set(Set.empty[A])) { case (ss, el) => ss ++ ss.map(_ + el)}

  assert(powerset(Set(1, 2, 3, 4)) == Set(Set.empty, Set(1), Set(2), Set(3), Set(4), Set(1, 2), Set(1, 3), Set(1, 4),
    Set(2, 3), Set(2, 4), Set(3, 4), Set(1, 2, 3), Set(1, 3, 4), Set(1, 2, 4), Set(2, 3, 4), Set(1, 2, 3, 4)))
  println(s"Successfully completed without errors. [total ${currentTime - executionStart} ms]")
}


(define (power-set set)
  (if (null? set)
      '(())
      (let ((rest (power-set (cdr set))))
        (append (map (lambda (element) (cons (car set) element))
                     rest)
                rest))))

(display (power-set (list 1 2 3)))
(newline)

(display (power-set (list "A" "C" "E")))
(newline)


import math.sqrt

def
  isPrime( 2 )      =  true
  isPrime( n )
    | n < 3 or 2|n  =  false
    | otherwise     =  (3..int(sqrt(n)) by 2).forall( (/|n) )

(10^10..10^10+50).filter( isPrime ).foreach( println )


window 1, @"Primality By Trial Division", (0,0,480,270)

local fn isPrime( n as long ) as Boolean
  long    i
  Boolean result

  if n < 2 then result = NO : exit fn
  if n = 2 then result = YES : exit fn
  if n mod 2 == 0  then result = NO : exit fn

  result = YES
  for i = 3 to int( n^.5 ) step 2
    if n mod i == 0 then result = NO : break
  next i
end fn = result

long i, j = 0

print "Prime numbers between 0 and 1000:"
for i = 0 to 1000
  if ( fn isPrime(i) != _false )
    printf @"%3d\t",i : j++
    if j mod 10 == 0 then print
  end if
next

HandleEvents


'Reworked from the BBC Basic example

Public Sub Main()
Dim iNum As Integer

For iNum = 1 To 100
  If FNisprime(iNum) Then Print iNum & " is prime"
Next

End
'___________________________________________________
Public Sub FNisprime(iNum As Integer) As Boolean
Dim iLoop As Integer
Dim bReturn As Boolean = True

If iNum <= 1 Then bReturn = False
If iNum <= 3 Then bReturn = True
If (iNum And 1) = 0 Then bReturn = False

For iLoop = 3 To Sqr(iNum) Step 2
  If iNum Mod iLoop = 0 Then bReturn = False
Next

Return bReturn

End


import random, strformat

# Representation of a standard value as an int (actual value * 100).
type StandardValue = distinct int

proc `<`(a, b: StandardValue): bool {.borrow.}

const Pricemap = [10, 18, 26, 32, 38, 44, 50, 54, 58, 62, 66, 70, 74, 78, 82, 86, 90, 94, 98, 100]

proc toStandardValue(f: float): StandardValue =
  ## Convert a float to a standard value (decimal value multiplied by 100).
  ## Index: 0.01..0.05 -> 0, 0.06..0.10 -> 1, 0.11..0.15 -> 2...
  var value = int(f * 100)
  if value == 0: return StandardValue(10)
  dec value
  # Increment index every 5 of value, so value in 1..100 translates to index in 0..19.
  let index = 2 * (value div 10) + (value mod 10) div 5
  result = StandardValue(Pricemap[index])

proc `$`(price: StandardValue): string =
  ## Return the string representation of a standard value.
  if price < StandardValue(10): "0.0" & $int(price)
  elif price < StandardValue(100): "0." & $int(price)
  else: "1.00"

when isMainModule:
  randomize()
  for _ in 0 .. 10:
    let price = rand(1.01)
    echo &"Price for {price:.2f} is {price.toStandardValue()}"


$ include "seed7_05.s7i";

const func array bitset: powerSet (in bitset: baseSet) is func
  result
    var array bitset: pwrSet is [] (bitset.value);
  local
    var integer: element is 0;
    var integer: index is 0;
    var bitset: aSet is bitset.value;
  begin
    for element range baseSet do
      for key index range pwrSet do
        aSet := pwrSet[index];
        if element not in aSet then
          incl(aSet, element);
          pwrSet &:= aSet;
        end if;
      end for;
    end for;
  end func;

const proc: main is func
  local
    var bitset: aSet is bitset.value;
  begin
    for aSet range powerSet({1, 2, 3, 4}) do
      writeln(aSet);
    end for;
  end func;


Pfour := pow({1, 2, 3, 4});
Pempty := pow({});
PPempty := pow(Pempty);

print(Pfour);
print(Pempty);
print(PPempty);


var arr = %w(a b c)
for i in (0 .. arr.len) {
    say arr.combinations(i)
}


IsPrimeTrial := function(n)
   local k, m;
   if n < 5 then
      return (n = 2) or (n = 3);
   fi;
   if RemInt(n, 2) = 0 then
      return false;
   fi;
   m := RootInt(n);
   k := 3;
   while k <= m do
      if RemInt(n, k) = 0 then
         return false;
      fi;
      k := k + 2;
   od;
   return true;
end;

Filtered([1 .. 100], IsPrimeTrial);
# [ 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 ]


func IsPrime(n int) bool {
	if n < 0 { n = -n }
	switch {
        case n == 2:
		return true
	case n < 2 || n % 2 == 0:
		return false

	default:
		for i = 3; i*i <= n; i += 2 {
			if n % i == 0 { return false }
		}
	}
	return true
}