import std.stdio, std.bigint, std.algorithm, std.traits, std.range;

Unqual!T[] decompose(T)(in T number) pure nothrow
in {
    assert(number > 1);
} body {
    typeof(return) result;
    Unqual!T n = number;

    for (Unqual!T i = 2; n % i == 0; n /= i)
        result ~= i;
    for (Unqual!T i = 3; n >= i * i; i += 2)
        for (; n % i == 0; n /= i)
            result ~= i;

    if (n != 1)
        result ~= n;
    return result;
}

void main() {
    writefln("%(%s\n%)", iota(2, 10).map!decompose);
    decompose(1023 * 1024).writeln;
    BigInt(2 * 3 * 5 * 7 * 11 * 11 * 13 * 17).decompose.writeln;
    decompose(16860167264933UL.BigInt * 179951).writeln;
    decompose(2.BigInt ^^ 100_000).group.writeln;
}


program Prime_decomposition;

{$APPTYPE CONSOLE}

uses
  System.SysUtils;

function IsPrime(n: UInt64): Boolean;
var
  i: Integer;
begin
  if n <= 1 then
    exit(False);

  i := 2;
  while i < Sqrt(n) do
  begin
    if n mod i = 0 then
      exit(False);
    inc(i);
  end;

  Result := True;
end;

function GetPrimes(n: UInt64): TArray<UInt64>;
var
  i: Integer;
begin
  while n > 1 do
  begin
    i := 1;
    while True do
    begin
      if IsPrime(i) then
      begin
        if n / i = (round(n / i)) then
        begin
          n := n div i;
          SetLength(Result, Length(Result) + 1);
          Result[High(Result)] := i;
          Break;
        end;
      end;
      inc(i);
    end;
  end;
end;

begin
  for var v in GetPrimes(12) do
    write(v, ' ');
  readln;
end.


def primes := {
    var primesCache := [2]
    /** A collection of all prime numbers. */
    def primes {
        to iterate(f) {
            primesCache.iterate(f)
            for x in (int > primesCache.last()) {
                if (isPrime(x)) {
                    f(primesCache.size(), x)
                    primesCache with= x
                }
            }
        }
    }
}

def primeDecomposition(var x :(int > 0)) {
    var factors := []
    for p in primes {
        while (x % p <=> 0) {
            factors with= p
            x //= p
        }
        if (x <=> 1) {
            break
        }
    }
    return factors
}


class
    PRIME_DECOMPOSITION

feature

    factor (p: INTEGER): ARRAY [INTEGER]
            -- Prime decomposition of 'p'.
        require
            p_positive: p > 0
        local
            div, i, next, rest: INTEGER
        do
            create Result.make_empty
            if p = 1 then
                Result.force (1, 1)
            end
            div := 2
            next := 3
            rest := p
            from
                i := 1
            until
                rest = 1
            loop
                from
                until
                    rest \\ div /= 0
                loop
                    Result.force (div, i)
                    rest := (rest / div).floor
                    i := i + 1
                end
                div := next
                next := next + 2
            end
        ensure
            is_divisor: across Result as r all p \\ r.item = 0 end
            is_prime: across Result as r all prime (r.item) end
        end


open integer //arbitrary sized integers

decompose_prime n = loop n 2I
  where
    loop c p | c < (p * p) = [c]
             | c % p == 0I = p :: (loop (c / p) p)
             | else = loop c (p + 1I)

decompose_prime 600851475143I


defmodule Prime do
  def decomposition(n), do: decomposition(n, 2, [])

  defp decomposition(n, k, acc) when n < k*k, do: Enum.reverse(acc, [n])
  defp decomposition(n, k, acc) when rem(n, k) == 0, do: decomposition(div(n, k), k, [k | acc])
  defp decomposition(n, k, acc), do: decomposition(n, k+1, acc)
end

prime = Stream.iterate(2, &(&1+1)) |>
        Stream.filter(fn n-> length(Prime.decomposition(n)) == 1 end) |>
        Enum.take(17)
mersenne = Enum.map(prime, fn n -> {n, round(:math.pow(2,n)) - 1} end)
Enum.each(mersenne, fn {n,m} ->
  :io.format "~3s :~20w = ~s~n", ["M#{n}", m, Prime.decomposition(m) |> Enum.join(" x ")]
end)


% no stack consuming version

factors(N) ->
     factors(N,2,[]).

factors(1,_,Acc) -> Acc;
factors(N,K,Acc) when N < K*K -> [N|Acc];
factors(N,K,Acc) when N rem K == 0 ->
    factors(N div K,K, [K|Acc]);
factors(N,K,Acc) ->
    factors(N,K+1,Acc).


PROGRAM DECOMPOSE

!
! for rosettacode.org
!

!VAR NUM,J

DIM PF[100]

PROCEDURE STORE_FACTOR
   PF[0]=PF[0]+1
   PF[PF[0]]=CA
   I=I/CA
END PROCEDURE

PROCEDURE DECOMP(I)
  PF[0]=0  CA=2 ! special case
  LOOP
     IF I=1 THEN EXIT PROCEDURE END IF
     EXIT IF INT(I/CA)*CA<>I
     STORE_FACTOR
  END LOOP
  FOR CA=3 TO INT(SQR(I)) STEP 2 DO
     LOOP
        IF I=1 THEN EXIT PROCEDURE END IF
        EXIT IF INT(I/CA)*CA<>I
        STORE_FACTOR
     END LOOP
  END FOR
  IF I>1 THEN CA=I STORE_FACTOR END IF
END PROCEDURE

BEGIN
 ! ----- function generate
 ! in ...  I     ... number
 ! out ... PF[]  ... factors
 !         PF[0] ... # of factors
 ! mod ... CA    ... pr.fact. candidate
 PRINT(CHR$(12);) !CLS
 INPUT("Numero ",NUM)
 DECOMP(NUM)
 PRINT(NUM;"=";)
 FOR J=1 TO PF[0] DO
    PRINT(PF[J];)
 END FOR
 PRINT
END PROGRAM


## இந்த நிரல் தரப்பட்ட எண்ணின் பகாஎண் கூறுகளைக் கண்டறியும்

நிரல்பாகம் பகாஎண்ணா(எண்1)

  ## இந்த நிரல்பாகம் தரப்பட்ட எண் பகு எண்ணா அல்லது பகா எண்ணா என்று கண்டறிந்து சொல்லும்
  ## பகுஎண் என்றால் 0 திரும்பத் தரப்படும்
  ## பகாஎண் என்றால் 1 திரும்பத் தரப்படும்

  @(எண்1 < 0) ஆனால்

   ## எதிர்மறை எண்களை நேராக்குதல்

    எண்1 = எண்1 * (-1)

  முடி

  @(எண்1 < 2) ஆனால்

   ## பூஜ்ஜியம், ஒன்று ஆகியவை பகா எண்கள் அல்ல

    பின்கொடு 0

  முடி

  @(எண்1 == 2) ஆனால்

    ## இரண்டு என்ற எண் ஒரு பகா எண்

    பின்கொடு 1

  முடி

  மீதம் = எண்1%2

  @(மீதம் == 0) ஆனால்

    ## இரட்டைப்படை எண், ஆகவே, இது பகா எண் அல்ல

    பின்கொடு 0

  முடி

    எண்1வர்க்கமூலம் = எண்1^0.5

    @(எண்2 = 3, எண்2 <= எண்1வர்க்கமூலம், எண்2 = எண்2 + 2) ஆக

      மீதம்1 = எண்1%எண்2

      @(மீதம்1 == 0) ஆனால்

        ## ஏதேனும் ஓர் எண்ணால் முழுமையாக வகுபட்டுவிட்டது, ஆகவே அது பகா எண் அல்ல

        பின்கொடு 0

      முடி

    முடி

    பின்கொடு 1

முடி

நிரல்பாகம் பகுத்தெடு(எண்1)

  ## இந்த எண் தரப்பட்ட எண்ணின் பகா எண் கூறுகளைக் கண்டறிந்து பட்டியல் இடும்

  கூறுகள் = பட்டியல்()

  @(எண்1 < 0) ஆனால்

    ## எதிர்மறை எண்களை நேராக்குதல்

    எண்1 = எண்1 * (-1)

  முடி

  @(எண்1 <= 1) ஆனால்

    ## ஒன்று அல்லது அதற்குக் குறைவான எண்களுக்குப் பகா எண் விகிதம் கண்டறியமுடியாது

    பின்கொடு கூறுகள்

  முடி

  @(பகாஎண்ணா(எண்1) == 1) ஆனால்

    ## தரப்பட்ட எண்ணே பகா எண்ணாக அமைந்துவிட்டால், அதற்கு அதுவே பகாஎண் கூறு ஆகும்

    பின்இணை(கூறுகள், எண்1)
    பின்கொடு கூறுகள்

  முடி

  தாற்காலிகஎண் = எண்1

  எண்2 = 2

  @(எண்2 <= தாற்காலிகஎண்) வரை

    விடை1 = பகாஎண்ணா(எண்2)
    மீண்டும்தொடங்கு = 0

    @(விடை1 == 1) ஆனால்

      விடை2 = தாற்காலிகஎண்%எண்2

      @(விடை2 == 0) ஆனால்

        ## பகா எண்ணால் முழுமையாக வகுபட்டுள்ளது, அதனைப் பட்டியலில் இணைக்கிறோம்

        பின்இணை(கூறுகள், எண்2)
        தாற்காலிகஎண் = தாற்காலிகஎண்/எண்2

        ## மீண்டும் இரண்டில் தொடங்கி இதே கணக்கிடுதலைத் தொடரவேண்டும்

        எண்2 = 2
        மீண்டும்தொடங்கு = 1

      முடி

    முடி

    @(மீண்டும்தொடங்கு == 0) ஆனால்

      ## அடுத்த எண்ணைத் தேர்ந்தெடுத்துக் கணக்கிடுதலைத் தொடரவேண்டும்

      எண்2 = எண்2 + 1

    முடி

  முடி

  பின்கொடு கூறுகள்

முடி

அ = int(உள்ளீடு("உங்களுக்குப் பிடித்த ஓர் எண்ணைத் தாருங்கள்: "))

பகாஎண்கூறுகள் = பட்டியல்()

பகாஎண்கூறுகள் = பகுத்தெடு(அ)

பதிப்பி "நீங்கள் தந்த எண்ணின் பகா எண் கூறுகள் இவை: ", பகாஎண்கூறுகள்


let decompose_prime n =
  let rec loop c p =
    if c < (p * p) then [c]
    elif c % p = 0I then p :: (loop (c/p) p)
    else loop c (p + 1I)

  loop n 2I

printfn "%A" (decompose_prime 600851475143I)


USING: io kernel math math.parser math.primes.factors sequences ;

27720 factors
[ number>string ] map
" " join print ;


[2[\[email protected]$$*@>~][\[email protected][email protected][email protected][email protected]\/*=$[%$." "[email protected]\/\0~]?~[1+1|]?]#%.]d:
27720d;!   {2 2 2 3 3 5 7 11}


: decomp ( n -- )
  2
  begin  2dup dup * >=
  while  2dup /mod swap
         if   drop  1+ 1 or    \ next odd number
         else -rot nip  dup .
         then
  repeat
  drop . ;


module PrimeDecompose
  implicit none

  integer, parameter :: huge = selected_int_kind(18)
  ! => integer(8) ... more fails on my 32 bit machine with gfortran(gcc) 4.3.2

contains

  subroutine find_factors(n, d)
    integer(huge), intent(in) :: n
    integer, dimension(:), intent(out) :: d

    integer(huge) :: div, next, rest
    integer :: i

    i = 1
    div = 2; next = 3; rest = n

    do while ( rest /= 1 )
       do while ( mod(rest, div) == 0 )
          d(i) = div
          i = i + 1
          rest = rest / div
       end do
       div = next
       next = next + 2
    end do

  end subroutine find_factors

end module PrimeDecompose


' FB 1.05.0 Win64

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

Sub getPrimeFactors(factors() As UInteger, n As UInteger)
  If n < 2 Then Return
  If isPrime(n) Then
    Redim factors(0 To 0)
    factors(0) = n
    Return
  End If
  Dim factor As UInteger = 2
  Do
    If n Mod factor = 0 Then
      Redim Preserve factors(0 To UBound(factors) + 1)
      factors(UBound(factors)) = factor
      n \= factor
      If n = 1 Then Return
      If isPrime(n) Then factor = n
    Else
      factor += 1
    End If
  Loop
End Sub

Dim factors() As UInteger
Dim primes(1 To 17) As UInteger = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59}
Dim n As UInteger
For i As UInteger = 1 To 17
  Erase factors
  n = 1 Shl primes(i) - 1
  getPrimeFactors factors(), n
  Print "2^";Str(primes(i)); Tab(5); " - 1 = "; Str(n); Tab(30);" => ";
  For j As UInteger = LBound(factors) To UBound(factors)
     Print factors(j);
     If j < UBound(factors) Then Print " x ";
  Next j
  Print
Next i
Print
Print "Press any key to quit"
Sleep


package main

import (
    "fmt"
    "math/big"
)

var (
    ZERO = big.NewInt(0)
    ONE  = big.NewInt(1)
)

func Primes(n *big.Int) []*big.Int {
    res := []*big.Int{}
    mod, div := new(big.Int), new(big.Int)
    for i := big.NewInt(2); i.Cmp(n) != 1; {
        div.DivMod(n, i, mod)
        for mod.Cmp(ZERO) == 0 {
            res = append(res, new(big.Int).Set(i))
            n.Set(div)
            div.DivMod(n, i, mod)
        }
        i.Add(i, ONE)
    }
    return res
}

func main() {
    vals := []int64{
        1 << 31,
        1234567,
        333333,
        987653,
        2 * 3 * 5 * 7 * 11 * 13 * 17,
    }
    for _, v := range vals {
        fmt.Println(v, "->", Primes(big.NewInt(v)))
    }
}


def factorize = { long target ->

    if (target == 1) return [1L]

    if (target < 4) return [1L, target]

    def targetSqrt = Math.sqrt(target)
    def lowfactors = (2L..targetSqrt).findAll { (target % it) == 0 }
    if (lowfactors == []) return [1L, target]
    def nhalf = lowfactors.size() - ((lowfactors[-1]**2 == target) ? 1 : 0)

    [1] + lowfactors + (0..<nhalf).collect { target.intdiv(lowfactors[it]) }.reverse() + [target]
}

def decomposePrimes = { target ->
    def factors = factorize(target) - [1]
    def primeFactors = []
    factors.eachWithIndex { f, i ->
        if (i==0 || factors[0..<i].every {f % it != 0}) {
            primeFactors << f
            def pfPower = f*f
            while (target % pfPower == 0) {
                primeFactors << f
                pfPower *= f
            }
        }
    }
    primeFactors
}


factorize n = [ d | p <- [2..n], isPrime p, d <- divs n p ]
           -- [2..n] >>= (\p-> [p|isPrime p]) >>= divs n
    where
    divs n p | rem n p == 0 = p : divs (quot n p) p
             | otherwise    = []


procedure main()
factors := primedecomp(2^43-1)   # a big int
end

procedure primedecomp(n)         #: return a list of factors
local F,o,x
F := []

every writes(o,n|(x := genfactors(n))) do {
   \o := "*"
   /o := "="
   put(F,x)   # build a list of factors to satisfy the task
   }
write()
return F
end

link factors


function run_factorize(input, output) {
    var n = new BigInteger(input.value, 10);
    var TWO = new BigInteger("2", 10);
    var divisor = new BigInteger("3", 10);
    var prod = false;

    if (n.compareTo(TWO) < 0)
        return;

    output.value = "";

    while (true) {
        var qr = n.divideAndRemainder(TWO);
        if (qr[1].equals(BigInteger.ZERO)) {
            if (prod)
                output.value += "*";
            else
                prod = true;
            output.value += "2";
            n = qr[0];
        }
        else
            break;
    }

    while (!n.equals(BigInteger.ONE)) {
        var qr = n.divideAndRemainder(divisor);
        if (qr[1].equals(BigInteger.ZERO)) {
            if (prod)
                output.value += "*";
            else
                prod = true;
            output.value += divisor;
            n = qr[0];
        }
        else
            divisor = divisor.add(TWO);
    }
}


def factors:
  . as $in
  | [2, $in, false]
  | recurse(
      . as [$p, $q, $valid, $s]
      | if $q == 1        then empty
        elif $q % $p == 0 then [$p, $q/$p, true]
        elif $p == 2      then [3, $q, false, $s]
        else ($s // ($q | sqrt)) as $s
        | if $p + 2 <= $s then [$p + 2, $q, false, $s]
          else [$q, 1, true]
          end
        end )
   | if .[2] then .[0] else empty end ;


// version 1.0.6

import java.math.BigInteger

val bigTwo   = BigInteger.valueOf(2L)
val bigThree = BigInteger.valueOf(3L)

fun getPrimeFactors(n: BigInteger): MutableList<BigInteger> {
    val factors = mutableListOf<BigInteger>()
    if (n < bigTwo) return factors
    if (n.isProbablePrime(20)) {
        factors.add(n)
        return factors
    }
    var factor = bigTwo
    var nn = n
    while (true) {
        if (nn % factor == BigInteger.ZERO) {
            factors.add(factor)
            nn /= factor
            if (nn == BigInteger.ONE) return factors
            if (nn.isProbablePrime(20)) factor = nn
        }
        else if (factor >= bigThree) factor += bigTwo
        else factor = bigThree
    }
}

fun main(args: Array<String>) {
    val primes = intArrayOf(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)
    for (prime in primes) {
        val bigPow2 = bigTwo.pow(prime) - BigInteger.ONE
        println("2^${"%2d".format(prime)} - 1 = ${bigPow2.toString().padEnd(30)} => ${getPrimeFactors(bigPow2)}")
    }
}


(defun factors (n)
  (factors n 2 '()))

(defun factors
  ((1 _ acc)
    acc)
  ((n k acc) (when (== 0 (rem n k)))
    (factors (div n k) k (cons k acc)))
  ((n k acc)
    (factors n (+ k 1) acc)))


-- Returns list of prime factors for given number.
-- To overcome the limits of integers (signed 32-bit in Lingo),
-- the number can be specified as float (which works up to 2^53).
-- For the same reason, values in returned list are floats, not integers.
on getPrimeFactors (n)
  f = []
  f.sort()
  c = sqrt(n)
  i = 1.0
  repeat while TRUE
    i=i+1
    if i>c then exit repeat
    check = n/i
    if bitOr(check,0)=check then
      f.add(i)
      n = check
      c = sqrt(n)
      i = 1.0
    end if
  end repeat
  f.add(n)
  return f
end


to decompose :n [:p 2]
  if :p*:p > :n [output (list :n)]
  if less? 0 modulo :n :p [output (decompose :n bitor 1 :p+1)]
  output fput :p (decompose :n/:p :p)
end


function PrimeDecomposition( n )
    local f = {}

    if IsPrime( n ) then
        f[1] = n
        return f
    end

    local i = 2
    repeat
        while n % i == 0 do
            f[#f+1] = i
            n = n / i
        end

        repeat
            i = i + 1
        until IsPrime( i )
    until n == 1

    return f
end


Module  Prime_decomposition    {
      Inventory [email protected], [email protected]
      IsPrime=lambda  Known1 (x as decimal) -> {
                  =0=1
                  if exist(Known1, x) then =1=1 : exit
                  if x<=5 OR frac(x) then {if x == 2 OR x == 3 OR x == 5 then Append Known1, x  : =1=1
                  Break}
                  if frac(x/2) else exit
                  if frac(x/3) else exit
                  x1=sqrt(x):d = [email protected]
                  {if frac(x/d ) else exit
                        d += 2: if d>x1 then Append Known1, x : =1=1 : exit
                        if frac(x/d) else exit
                        d += 4: if d<= x1 else Append Known1, x :  =1=1: exit
                   loop}
            }
      decompose=lambda IsPrime (n as decimal) -> {
            Inventory queue Factors
            {
                 [email protected]
                 While frac(n/k)=0 {
                 n/=k
                      Append Factors, k
                 }
                 if n=1 then exit
                 k++
                 While frac(n/k)=0 {
                 n/=k
                        Append Factors, k
                 }
                 if n=1 then exit
                 {
                 k+=2
                 while not isprime(k) {k+=2}
                 While frac(n/k)=0 {
                 n/=k
                        Append Factors, k
                 }
                      if n=1 then exit
                      loop
                 }
            }
            =Factors
      }
      Data 10, 100, 12, 144, 496, 1212454
      while not empty {
        Print Decompose(Number)
      }
}
Prime_decomposition


function [outputPrimeDecomposition] = primedecomposition(inputValue)
   outputPrimeDecomposition = factor(inputValue);


(%i1) display2d: false$ /* disable rendering exponents as superscripts */
(%i2) factor(2016);
(%o2) 2^5*3^2*7


ERATO1(HI)
 SET HI=HI\1
 KILL ERATO1 ;Don't make it new - we want it to remain after the quit
 NEW I,J,P
 FOR I=2:1:(HI**.5)\1 DO
 .FOR J=I*I:I:HI DO
 ..SET P(J)=1 ;$SELECT($DATA(P(J))#10:P(J)+1,1:1)
 ;WRITE !,"Prime numbers between 2 and ",HI,": "
 FOR I=2:1:HI DO
 .S:'$DATA(P(I)) ERATO1(I)=I ;WRITE $SELECT((I<3):"",1:", "),I
 KILL I,J,P
 QUIT
PRIMDECO(N)
 ;Returns its results in the string PRIMDECO
 ;Kill that before the first call to this recursive function
 QUIT:N<=1
 IF $D(PRIMDECO)=1 SET PRIMDECO="" D ERATO1(N)
 SET N=N\1,I=0
 FOR  SET I=$O(ERATO1(I)) Q:+I<1  Q:'(N#I)
 IF I>1 SET PRIMDECO=$S($L(PRIMDECO)>0:PRIMDECO_"^",1:"")_I D PRIMDECO(N/I)
 ;that is, if I is a factor of N, add it to the string
 QUIT


import math, sequtils, strformat, strutils, times

proc getStep(n: int64): int64 {.inline.} =
  result = 1 + n shl 2 - n shr 1 shl 1

proc primeFac(n: int64): seq[int64] =
  var maxq = int64(sqrt(float(n)))
  var d = 1
  var q: int64 = 2 + (n and 1)   # Start with 2 or 3 according to oddity.
  while q <= maxq and n %% q != 0:
    q = getStep(d)
    inc d
  if q <= maxq:
    let q1 = primeFac(n /% q)
    let q2 = primeFac(q)
    result = concat(q2, q1, result)
  else:
    result.add(n)

iterator primes(limit: int): int =
  var isPrime = newSeq[bool](limit + 1)
  for n in 2..limit: isPrime[n] = true
  for n in 2..limit:
    if isPrime[n]:
      yield n
      for i in countup(n *% n, limit, n):
        isPrime[i] = false

when isMainModule:

  # Example: calculate factors of Mersenne numbers from M2 to M59.
  for m in primes(59):
    let p = 2i64^m - 1
    let s = &"2^{m}-1"
    stdout.write &"{s:<6} = {p} with factors: "
    let start = cpuTime()
    stdout.write primeFac(p).join(", ")
    echo &" => {(1000 * (cpuTime() - start)).toInt} ms"


open Big_int;;

let prime_decomposition x =
  let rec inner c p =
    if lt_big_int p (square_big_int c) then
      [p]
    else if eq_big_int (mod_big_int p c) zero_big_int then
      c :: inner c (div_big_int p c)
    else
      inner (succ_big_int c) p
  in
  inner (succ_big_int (succ_big_int zero_big_int)) x;;


: factors(n)   // ( aInteger -- aList )
| k p |
   ListBuffer new
   2 ->k
   n nsqrt ->p
   while( k p <= ) [
      n k /mod swap ifZero: [
         dup ->n nsqrt ->p
         k over add continue
         ]
      drop k 1+ ->k
      ]
   n 1 > ifTrue: [ n over add ]
   dup freeze ;


Program PrimeDecomposition(output);

type
  DynArray = array of integer;

procedure findFactors(n: Int64; var d: DynArray);
  var
    divisor, next, rest: Int64;
    i: integer;
 begin
    i := 0;
    divisor := 2;
    next := 3;
    rest := n;
    while (rest <> 1) do
    begin
      while (rest mod divisor = 0) do
      begin
        setlength(d, i+1);
        d[i] := divisor;
        inc(i);
        rest := rest div divisor;
      end;
      divisor := next;
      next := next + 2;
    end;
  end;

var
  factors: DynArray;
  j: integer;

begin
  setlength(factors, 1);
  findFactors(1023*1024, factors);
  for j := low(factors) to high(factors) do
    writeln (factors[j]);
end.


sub prime_factors {
    my ($n, $d, @out) = (shift, 1);
    while ($n > 1 && $d++) {
        $n /= $d, push @out, $d until $n % $d;
    }
    @out
}

print "@{[prime_factors(1001)]}\n";


with javascript_semantics
requires("1.0.0")
include mpfr.e
atom t0 = time()
mpz z = mpz_init()
for i=1 to 25 do
    integer pi = get_prime(i)
    mpz_ui_pow_ui(z,2,pi)
    mpz_sub_ui(z,z,1)
    string zs = mpz_get_str(z),
           fs = mpz_factorstring(mpz_pollard_rho(z))
    if fs!=zs then zs &= " = "&fs end if
    printf(1,"2^%d-1 = %s\n",{pi,zs})
end for
string s = "600851475143"
for i=1 to 2 do
    mpz_set_str(z,s)
    printf(1,"%s = %s\n",{s,mpz_factorstring(mpz_pollard_rho(z))})
    s = "100000000000000000037"
end for
?elapsed(time()-t0)


go =>
  % Checking 2**prime-1
  foreach(P in primes(60))
     Factors = factors(2**P-1),
     println([n=2**P-1,factors=Factors])
  end,
  nl,
  % Testing a larger number
  println(factors(1361129467683753853853498429727072845823)),
  nl.

%
% factors of N
%
factors(N) = Factors =>
   Factors = [],
   M = N,
   while (M mod 2 == 0)
      Factors := Factors ++ [2],
      M := M div 2
   end,
   T = 3,
   while (M > 1, T < 1+(sqrt(M)))
      if M mod T == 0 then
         [Divisors, NewM] = alldivisorsM(M, T),
         Factors := Factors ++ Divisors,
         M := NewM
      end,
      T := T + 2
   end,
   if M > 1 then Factors := Factors ++ [M] end.

alldivisorsM(N,Div) = [Divisors,M] =>
   M = N,
   Divisors = [],
   while (M mod Div == 0)
      Divisors := Divisors ++ [Div],
      M := M div Div
   end.


test: procedure options (main, reorder);
   declare (n, i) fixed binary (31);

   get list (n);
   put edit ( n, '[' ) (x(1), a);
restart:
   if is_prime(n) then
      do;
         put edit (trim(n), ']' ) (x(1), a);
         stop;
      end;
   do i = n/2 to 2 by -1;
      if is_prime(i) then
         if (mod(n, i) = 0) then
            do;
               put edit ( trim(i) ) (x(1), a);
               n = n / i;
               go to restart;
            end;
   end;
   put edit ( ' ]' ) (a);

is_prime: procedure (n) options (reorder) returns (bit(1));
   declare n fixed binary (31);
   declare i fixed binary (31);

   if n < 2 then return ('0'b);
   if n = 2 then return ('1'b);
   if mod(n, 2) = 0 then return ('0'b);

   do i = 3 to sqrt(n) by 2;
      if mod(n, i) = 0 then return ('0'b);
   end;
   return ('1'b);
end is_prime;

end test;


function eratosthenes ($n) {
    if($n -gt 1){
        $prime = @(1..($n+1) | foreach{$true})
        $prime[1] = $false
        $m = [Math]::Floor([Math]::Sqrt($n))
        function multiple($i) {
            for($j = $i*$i; $j -le $n; $j += $i) {
                $prime[$j] = $false
            }
        }
        multiple 2
        for($i = 3; $i -le $m; $i += 2) {
            if($prime[$i]) {multiple $i}
        }
        1..$n | where{$prime[$_]}
    } else {
        Write-Error "$n is not greater than 1"
    }
}
function prime-decomposition ($n) {
    $array = eratosthenes $n
    $prime = @()
    foreach($p in $array) {
        while($n%$p -eq 0) {
            $n /= $p
            $prime += @($p)
        }
    }
    $prime
}
"$(prime-decomposition  12)"
"$(prime-decomposition  100)"


prime_decomp(N, L) :-
    SN is sqrt(N),
    prime_decomp_1(N, SN, 2, [], L).

prime_decomp_1(1, _, _, L, L) :- !.

% Special case for 2, increment 1
prime_decomp_1(N, SN, D, L, LF) :-
    (   0 is N mod D ->
        Q is N / D,
        SQ is sqrt(Q),
        prime_decomp_1(Q, SQ, D, [D |L], LF)
    ;
        D1 is D+1,
        (   D1 > SN ->
            LF = [N |L]
        ;
            prime_decomp_2(N, SN, D1, L, LF)
        )
    ).

% General case, increment 2
prime_decomp_2(1, _, _, L, L) :- !.

prime_decomp_2(N, SN, D, L, LF) :-
    (   0 is N mod D ->
        Q is N / D,
        SQ is sqrt(Q),
        prime_decomp_2(Q, SQ, D, [D |L], LF);
        D1 is D+2,
        (   D1 > SN ->
            LF = [N |L]
        ;
            prime_decomp_2(N, SN, D1, L, LF)
        )
    ).


factor n = factor 2 n with
  factor k n = k : factor k (n div k) if n mod k == 0;
         = if n>1 then [n] else [] if k*k>n;
         = factor (k+1) n if k==2;
         = factor (k+2) n otherwise;
end;


CompilerIf #PB_Compiler_Debugger
  CompilerError "Turn off the debugger if you want reasonable speed in this example."
CompilerEndIf

Define.q

Procedure Factor(Number, List Factors())
  Protected I = 3
  While Number % 2 = 0
    AddElement(Factors())
    Factors() = 2
    Number / 2
  Wend
  Protected Max = Number
  While I <= Max And Number > 1
    While Number % I = 0
      AddElement(Factors())
      Factors() = I
      Number/I
    Wend
    I + 2
  Wend
EndProcedure

Number = 9007199254740991
NewList Factors()
time = ElapsedMilliseconds()
Factor(Number, Factors())
time = ElapsedMilliseconds()-time
S.s = "Factored " + Str(Number) + " in " + StrD(time/1000, 2) + " seconds."
ForEach Factors()
  S + #CRLF$ + Str(Factors())
Next
MessageRequester("", S)


from __future__ import print_function

import sys
from itertools import islice, cycle, count

try:
    from itertools import compress
except ImportError:
    def compress(data, selectors):
        """compress('ABCDEF', [1,0,1,0,1,1]) --> A C E F"""
        return (d for d, s in zip(data, selectors) if s)

def is_prime(n):
    return list(zip((True, False), decompose(n)))[-1][0]

class IsPrimeCached(dict):
    def __missing__(self, n):
        r = is_prime(n)
        self[n] = r
        return r

is_prime_cached = IsPrimeCached()

def croft():
    """Yield prime integers using the Croft Spiral sieve.

    This is a variant of wheel factorisation modulo 30.
    """
    # Copied from:
    #   https://code.google.com/p/pyprimes/source/browse/src/pyprimes.py
    # Implementation is based on erat3 from here:
    #   http://stackoverflow.com/q/2211990
    # and this website:
    #   http://www.primesdemystified.com/
    # Memory usage increases roughly linearly with the number of primes seen.
    # dict ``roots`` stores an entry x:p for every prime p.
    for p in (2, 3, 5):
        yield p
    roots = {9: 3, 25: 5}  # Map d**2 -> d.
    primeroots = frozenset((1, 7, 11, 13, 17, 19, 23, 29))
    selectors = (1, 0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0)
    for q in compress(
            # Iterate over prime candidates 7, 9, 11, 13, ...
            islice(count(7), 0, None, 2),
            # Mask out those that can't possibly be prime.
            cycle(selectors)
            ):
        # Using dict membership testing instead of pop gives a
        # 5-10% speedup over the first three million primes.
        if q in roots:
            p = roots[q]
            del roots[q]
            x = q + 2*p
            while x in roots or (x % 30) not in primeroots:
                x += 2*p
            roots[x] = p
        else:
            roots[q*q] = q
            yield q
primes = croft

def decompose(n):
    for p in primes():
        if p*p > n: break
        while n % p == 0:
            yield p
            n //=p
    if n > 1:
        yield n

if __name__ == '__main__':
    # Example: calculate factors of Mersenne numbers to M59 #

    import time

    for m in primes():
        p = 2 ** m - 1
        print( "2**{0:d}-1 = {1:d}, with factors:".format(m, p) )
        start = time.time()
        for factor in decompose(p):
            print(factor, end=' ')
            sys.stdout.flush()

        print( "=> {0:.2f}s".format( time.time()-start ) )
        if m >= 59:
            break


  [ [] swap
    dup times
    [ [ dup i^ 2 + /mod
        0 = while
        nip dip
          [ i^ 2 + join ]
        again ]
      drop
      dup 1 = if conclude ]
    drop ]                  is primefactors ( n --> [ )

 1047552 primefactors echo


findfactors <- function(num) {
  x <- NULL
  firstprime<- 2; secondprime <- 3; everyprime <- num
  while( everyprime != 1 ) {
    while( everyprime%%firstprime == 0 ) {
      x <- c(x, firstprime)
      everyprime <- floor(everyprime/ firstprime)
    }
    firstprime <- secondprime
    secondprime <- secondprime + 2
  }
  x
}

print(findfactors(1027*4))


#lang racket
(require math)
(define (factors n)
  (append-map (λ (x) (make-list (cadr x) (car x))) (factorize n)))


sub prime-factors ( Int $n where * > 0 ) {
    return $n if $n.is-prime;
    return () if $n == 1;
    my $factor = find-factor( $n );
    sort flat ( $factor, $n div $factor ).map: &prime-factors;
}

sub find-factor ( Int $n, $constant = 1 ) {
    return 2 unless $n +& 1;
    if (my $gcd = $n gcd 6541380665835015) > 1 { # magic number: [*] primes 3 .. 43
        return $gcd if $gcd != $n
    }
    my $x      = 2;
    my $rho    = 1;
    my $factor = 1;
    while $factor == 1 {
        $rho = $rho +< 1;
        my $fixed = $x;
        my int $i = 0;
        while $i < $rho {
            $x = ( $x * $x + $constant ) % $n;
            $factor = ( $x - $fixed ) gcd $n;
            last if 1 < $factor;
            $i = $i + 1;
        }
    }
    $factor = find-factor( $n, $constant + 1 ) if $n == $factor;
    $factor;
}

.put for (2²⁹-1, 2⁴¹-1, 2⁵⁹-1, 2⁷¹-1, 2⁷⁹-1, 2⁹⁷-1, 2¹¹⁷-1, 2²⁴¹-1,
5465610891074107968111136514192945634873647594456118359804135903459867604844945580205745718497)\
.hyper(:1batch).map: -> $n {
    my $start = now;
   "factors of $n: ",
    prime-factors($n).join(' × '), " \t in ", (now - $start).fmt("%0.3f"), " sec."
}


/*REXX pgm does prime decomposition of a range of positive integers (with a prime count)*/
numeric digits 1000                              /*handle thousand digits for the powers*/
parse arg  bot  top  step   base  add            /*get optional arguments from the C.L. */
if  bot==''   then do;  bot=1;  top=100;  end    /*no  BOT given?  Then use the default.*/
if  top==''   then              top=bot          /* "  TOP?  "       "   "   "     "    */
if step==''   then step=  1                      /* " STEP?  "       "   "   "     "    */
if add ==''   then  add= -1                      /* "  ADD?  "       "   "   "     "    */
tell= top>0;       top=abs(top)                  /*if TOP is negative, suppress displays*/
w=length(top)                                    /*get maximum width for aligned display*/
if base\==''  then w=length(base**top)           /*will be testing powers of two later? */
@.=left('', 7);   @.0="{unity}";   @.1='[prime]' /*some literals:  pad;  prime (or not).*/
numeric digits max(9, w+1)                       /*maybe increase the digits precision. */
#=0                                              /*#:    is the number of primes found. */
        do n=bot  to top  by step                /*process a single number  or  a range.*/
        ?=n;  if base\==''  then ?=base**n + add /*should we perform a "Mercenne" test? */
        pf=factr(?);      f=words(pf)            /*get prime factors; number of factors.*/
        if f==1  then #=#+1                      /*Is N prime?  Then bump prime counter.*/
        if tell  then say right(?,w)   right('('f")",9)   'prime factors: '     @.f     pf
        end   /*n*/
say
ps= 'primes';    if p==1  then ps= "prime"       /*setup for proper English in sentence.*/
say right(#, w+9+1)       ps       'found.'      /*display the number of primes found.  */
exit                                             /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
factr: procedure;  parse arg x 1 d,$             /*set X, D  to argument 1;  $  to null.*/
if x==1  then return ''                          /*handle the special case of   X = 1.  */
       do  while x//2==0;  $=$ 2;  x=x%2;  end   /*append all the  2  factors of new  X.*/
       do  while x//3==0;  $=$ 3;  x=x%3;  end   /*   "    "   "   3     "     "  "   " */
       do  while x//5==0;  $=$ 5;  x=x%5;  end   /*   "    "   "   5     "     "  "   " */
       do  while x//7==0;  $=$ 7;  x=x%7;  end   /*   "    "   "   7     "     "  "   " */
                                                 /*                                  ___*/
q=1;   do  while q<=x;  q=q*4;  end              /*these two lines compute integer  √ X */
r=0;   do  while q>1;   q=q%4;  _=d-r-q;  r=r%2;   if _>=0  then do; d=_; r=r+q; end;  end

       do j=11  by 6  to r                       /*insure that  J  isn't divisible by 3.*/
       parse var j  ''  -1  _                    /*obtain the last decimal digit of  J. */
       if _\==5  then  do  while x//j==0;  $=$ j;  x=x%j;  end     /*maybe reduce by J. */
       if _ ==3  then iterate                    /*Is next  Y  is divisible by 5?  Skip.*/
       y=j+2;          do  while x//y==0;  $=$ y;  x=x%y;  end     /*maybe reduce by J. */
       end   /*j*/
                                                 /* [↓]  The $ list has a leading blank.*/
if x==1  then return $                           /*Is residual=unity? Then don't append.*/
              return $ x                         /*return   $   with appended residual. */


prime = 18705
decomp(prime)

func decomp nr
x = ""
for i = 1 to nr
    if isPrime(i) and nr % i = 0
       x = x + string(i) + " * " ok
    if i = nr
       x2 = substr(x,1,(len(x)-2))
       see string(nr) + " = " + x2 + nl ok
next

func isPrime num
     if (num <= 1) return 0 ok
     if (num % 2 = 0) and num != 2 return 0 ok
     for i = 3 to floor(num / 2) -1 step 2
         if (num % i = 0) return 0 ok
     next
     return 1


[package]
name = "prime_decomposition"
version = "0.1.1"
edition = "2018"

[dependencies]
num-bigint = "0.3.0"
num-traits = "0.2.12"


rem - compute p mod q
function mod(p, q = integer) = integer
end = p - q * (p/q)

dim integer factors(16)  rem log2(maxint) is sufficiently large

comment
  Find the prime factors of n and store in global array factors
  (arrays cannot be passed as parameters) and return the number
  found. If n is prime, it will be stored as the one and only
  factor.
end
function primefactors(n = integer) = integer
  var p, count = integer
  p = 2
  count = 1
  while n >= (p * p) do
     begin
       if mod(n, p) = 0 then
         begin
           factors(count) = p
           count = count + 1
           n = n / p
         end
       else
         p = p + 1
     end
   factors(count) = n
end = count

rem -- exercise the routine by checking odd numbers from 77 to 99

var i, k, nfound = integer

for i = 77 to 99 step 2
  nfound = primefactors(i)
  print i;"; ";
  for k = 1 to nfound
    print factors(k);
  next k
  print
next i

end


import annotation.tailrec
import collection.parallel.mutable.ParSeq

object PrimeFactors extends App {
  def factorize(n: Long): List[Long] = {
    @tailrec
    def factors(tuple: (Long, Long, List[Long], Int)): List[Long] = {
      tuple match {
        case (1, _, acc, _)                 => acc
        case (n, k, acc, _) if (n % k == 0) => factors((n / k, k, acc ++ ParSeq(k), Math.sqrt(n / k).toInt))
        case (n, k, acc, sqr) if (k < sqr)  => factors(n, k + 1, acc, sqr)
        case (n, k, acc, sqr) if (k >= sqr) => factors((1, k, acc ++ ParSeq(n), 0))
      }
    }
    factors((n, 2, List[Long](), Math.sqrt(n).toInt))
  }

  def mersenne(p: Int): BigInt = (BigInt(2) pow p) - 1

  def sieve(nums: Stream[Int]): Stream[Int] =
    Stream.cons(nums.head, sieve((nums.tail) filter (_ % nums.head != 0)))
  // An infinite stream of primes, lazy evaluation and memo-ized
  val oddPrimes = sieve(Stream.from(3, 2))
  def primes = sieve(2 #:: oddPrimes)

  oddPrimes takeWhile (_ <= 59) foreach { p =>
    { // Needs some intermediate results for nice formatting
      val numM = s"M${p}"
      val nMersenne = mersenne(p).toLong
      val lit = f"${nMersenne}%30d"

      val datum = System.nanoTime
      val result = factorize(nMersenne)
      val mSec = ((System.nanoTime - datum) / 1.0e+6).round

      def decStr = { if (lit.length > 30) f"(M has ${lit.length}%3d dec)" else "" }
      def sPrime = { if (result.isEmpty) " is a prime number." else "" }

      println(
        f"$numM%4s = 2^$p%03d - 1 = ${lit}%s${sPrime} ($mSec%,4d msec) composed of ${result.mkString(" × ")}")
    }
  }
}


(define (factor number)
  (define (*factor divisor number)
    (if (> (* divisor divisor) number)
        (list number)
        (if (= (modulo number divisor) 0)
            (cons divisor (*factor divisor (/ number divisor)))
            (*factor (+ divisor 1) number))))
  (*factor 2 number))

(display (factor 111111111111))
(newline)


const func array integer: factorise (in var integer: number) is func
  result
    var array integer: result is 0 times 0;
  local
    var integer: checker is 2;
  begin
    while checker * checker <= number do
      if number rem checker = 0 then
        result &:= [](checker);
        number := number div checker;
      else
        incr(checker);
      end if;
    end while;
    if number <> 1 then
      result &:= [](number);
    end if;
  end func;


isPrime(n) := n = 2 or (n > 1 and none(n mod ([2]++((1...floor(sqrt(n)/2))*2+1)) = 0));

primeFactorization(num) := primeFactorizationHelp(num, []);

primeFactorizationHelp(num, current(1)) :=
     let
        primeFactors[i] := i when num mod i = 0 and isPrime(i) foreach i within 2 ... num;
     in
            current when size(primeFactors) = 0
        else
            primeFactorizationHelp(num / product(primeFactors), current ++ primeFactors);


EXTERNAL CLASS BIGNUM;
BIGNUM
BEGIN

    CLASS TEXTLIST;
    BEGIN
        CLASS TEXTARRAY(N); INTEGER N;
        BEGIN
            TEXT ARRAY DATA(1:N);
        END TEXTARRAY;
        PROCEDURE EXPAND(N); INTEGER N;
        BEGIN
            REF(TEXTARRAY) NEWARR;
            INTEGER I;
            NEWARR :- NEW TEXTARRAY(N);
            FOR I := 1 STEP 1 UNTIL SIZE DO BEGIN
                NEWARR.DATA(I) :- ARR.DATA(I);
            END;
            ARR :- NEWARR;
        END EXPAND;
        PROCEDURE APPEND(T); TEXT T;
        BEGIN
            IF SIZE = ARR.N THEN
                EXPAND(2*ARR.N);
            SIZE := SIZE+1;
            ARR.DATA(SIZE) :- T;
        END EXPAND;
        TEXT PROCEDURE GET(I); INTEGER I;
            GET :- ARR.DATA(I);
        REF(TEXTARRAY) ARR;
        INTEGER SIZE;
        EXPAND(20);
    END TEXTLIST;

    REF(TEXTLIST) PROCEDURE PRIME_FACTORS(N); TEXT N;
    BEGIN
        REF(TEXTLIST) FACTORS;
        REF(DIVMOD) DM;
        TEXT P;
        FACTORS :- NEW TEXTLIST;
        IF TCMP(N, "1") < 0 THEN
            GOTO RETURN;
        P :- "2";
        FOR DM :- TDIVMOD(N,P) WHILE TISZERO(DM.MOD) DO BEGIN
            N :- DM.DIV;
            FACTORS.APPEND(P);
        END;
        P :- "3";
        WHILE TCMP(N,"1") > 0 AND THEN TCMP(TMUL(P,P),N) <= 0 DO BEGIN
            FOR DM :- TDIVMOD(N, P) WHILE TISZERO(DM.MOD) DO BEGIN
                N :- DM.DIV;
                FACTORS.APPEND(P);
            END;
            P :- TADD(P,"2");
        END;
        IF TCMP(N,"1") > 0 THEN
            FACTORS.APPEND(N);
    RETURN:
        PRIME_FACTORS :- FACTORS;
    END PRIME_FACTORS;

    REF(TEXTLIST) FACTORS;
    TEXT INP;
    INTEGER I;

    FOR INP :- "536870911", "6768768", "1957", "64865899369365843" DO BEGIN
        FACTORS :- PRIME_FACTORS(INP);
        OUTTEXT("PRIME FACTORS OF ");
        OUTTEXT(INP);
        OUTTEXT(" => [");
        FOR I := 1 STEP 1 UNTIL FACTORS.SIZE DO BEGIN
            IF I > 1 THEN
                OUTTEXT(", ");
            OUTTEXT(FACTORS.GET(I));
        END;
        OUTTEXT("]");
        OUTIMAGE;
    END;

END;


[email protected](Integer traits) primesDo: block
"Decomposes the Integer into primes, applying the block to each (in increasing
order)."
[| div next remaining |
  div: 2.
  next: 3.
  remaining: n.
  [[(remaining \\ div) isZero]
     whileTrue:
       [block applyTo: {div}.
    remaining: remaining // div].
   remaining = 1] whileFalse:
     [div: next.
      next: next + 2] "Just look at the next odd integer."
].


Integer extend [
    primesDo: aBlock [
        | div next rest |
        div := 2. next := 3.
        rest := self.
        [ [ rest \\ div == 0 ]
              whileTrue: [
                  aBlock value: div.
                  rest := rest // div ].
          rest = 1] whileFalse: [
              div := next. next := next + 2 ]
    ]
]
123456 primesDo: [ :each | each printNl ]


val factor = fn n :IntInf.int  =>
let
 val unfactored  = fn (u,_,_)   => u
 val factors     = fn (_,f,_)   => f
 val try         = fn (_,_,i)   => i
 fun getresult t = unfactored t::(factors t)

 fun until done change x =
    if done x
      then    getresult x
      else    until done change (change x);       (* iteration *)

 fun lastprime t = unfactored t  <  (try t)*(try t)
 fun trymore t   = if unfactored t mod (try t) = 0
           then (unfactored t div (try t) , try t::(factors t) , try t    )
       else (unfactored t             ,         factors t  , try t + 1)
in

 until lastprime trymore (n,[],2)

end;


func primeDecomposition<T: BinaryInteger>(of n: T) -> [T] {
  guard n > 2 else { return [] }

  func step(_ x: T) -> T {
    return 1 + (x << 2) - ((x >> 1) << 1)
  }

  let maxQ = T(Double(n).squareRoot())
  var d: T = 1
  var q: T = n % 2 == 0 ? 2 : 3

  while q <= maxQ && n % q != 0 {
    q = step(d)
    d += 1
  }

  return q <= maxQ ? [q] + primeDecomposition(of: n / q) : [n]
}

for prime in Eratosthenes(upTo: 60) {
  let m = Int(pow(2, Double(prime))) - 1
  let decom = primeDecomposition(of: m)

  print("2^\(prime) - 1 = \(m) => \(decom)")
}


proc factors {x} {
    # list the prime factors of x in ascending order
    set result [list]
    while {$x % 2 == 0} {
        lappend result 2
        set x [expr {$x / 2}]
    }
    for {set i 3} {$i*$i <= $x} {incr i 2} {
        while {$x % $i == 0} {
            lappend result $i
            set x [expr {$x / $i}]
        }
    }
    if {$x != 1} {lappend result $x}
    return $result
}


::prgmPREMIER
Disp "FACTEURS PREMIER"
Prompt N
If N<1:Stop
ClrList L1�,L2
0→K
iPart(√(N))→L
N→M
For(I,2,L)
0→J
While fPart(M/I)=0
J+1→J
M/I→M
End
If J≠0
Then
K+1→K
I→L�1(K)
J→L2(K)
I→Z:prgmVSTR
"   "+Str0→Str1
If J≠1
Then
J→Z:prgmVSTR
Str1+"^"+Str0→Str1
End
Disp Str1
End
If M=1:Stop
End
If M≠1
Then
If M≠N
Then
M→Z:prgmVSTR
"   "+Str0→Str1
Disp Str1
Else
Disp "PREMIER"
End
End
::prgmVSTR
{Z,Z}→L5
{1,2}→L6
LinReg(ax+b)L6,L5,Y�₀
Equ►String(Y₀,Str0)
length(Str0)→O
sub(Str0,4,O-3)→Str0
ClrList L5,L6
DelVar Y�


10 PRINT "Enter a number."
20 INPUT N
25 PRINT "------"
30 IF N<0 THEN LET N = -N
40 IF N<2 THEN END
50 LET I = 2
60 IF I*I > N THEN GOTO 200
70 IF (N/I)*I = N THEN GOTO 300
80 LET I = I + 1
90 GOTO 60
200 PRINT N
210 END
300 LET N = N / I
310 PRINT I
320 GOTO 50


@(next :args)
@(do
  (defun factor (n)
    (if (> n 1)
      (for ((max-d (isqrt n))
            (d 2))
           ()
           ((inc d (if (evenp d) 1 2)))
        (cond ((> d max-d) (return (list n)))
              ((zerop (mod n d))
               (return (cons d (factor (trunc n d))))))))))
@{num /[0-9]+/}
@(bind factors @(factor (int-str num 10)))
@(output)
@num -> {@(rep)@factors, @(last)@[email protected](end)}
@(end)


[prime-decomposition
   [inner [c p] let
       [c c * p >]
           [p unit]
           [ [p c % zero?]
                   [c c p c / inner cons]
                   [c 1 + p inner]
             ifte]
       ifte].
   2 swap inner].


Function PrimeFactors(n)
    arrP = Split(ListPrimes(n)," ")
    divnum = n
    Do Until divnum = 1
        'The -1 is to account for the null element of arrP
        For i = 0 To UBound(arrP)-1
            If divnum = 1 Then
                Exit For
            ElseIf divnum Mod arrP(i) = 0 Then
                divnum = divnum/arrP(i)
                PrimeFactors = PrimeFactors & arrP(i) & " "
            End If
        Next
    Loop
End Function

Function IsPrime(n)
    If n = 2 Then
        IsPrime = True
    ElseIf n <= 1 Or n Mod 2 = 0 Then
        IsPrime = False
    Else
        IsPrime = True
        For i = 3 To Int(Sqr(n)) Step 2
            If n Mod i = 0 Then
                IsPrime = False
                Exit For
            End If
        Next
    End If
End Function

Function ListPrimes(n)
    ListPrimes = ""
    For i = 1 To n
        If IsPrime(i) Then
            ListPrimes = ListPrimes & i & " "
        End If
    Next
End Function

WScript.StdOut.Write PrimeFactors(CInt(WScript.Arguments(0)))
WScript.StdOut.WriteLine


import "/big" for BigInt
import "/fmt" for Fmt

var vals = [1 << 31, 1234567, 333333, 987653, 2 * 3 * 5 * 7 * 11 * 13 * 17]
for (val in vals) {
    Fmt.print("$10d -> $n", val, BigInt.primeFactors(val))
}


<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">

    <xsl:template match="/numbers">

                    <xsl:apply-templates />

    </xsl:template>

    <xsl:template match="number">

            Number:
            <xsl:apply-templates mode="value" />
            Factors:
            <xsl:apply-templates mode="factors" />

    </xsl:template>

    <xsl:template match="value" mode="value">
        <xsl:apply-templates />
    </xsl:template>

    <xsl:template match="value" mode="factors">
        <xsl:call-template name="generate">
            <xsl:with-param name="number" select="number(current())" />
            <xsl:with-param name="candidate" select="number(2)" />
        </xsl:call-template>
    </xsl:template>

    <xsl:template name="generate">
        <xsl:param name="number" />
        <xsl:param name="candidate" />
        <xsl:choose>

            <xsl:when test="$number = 1"></xsl:when>

            <xsl:when test="$candidate * $candidate > $number">
                <xsl:value-of select="$number" />
            </xsl:when>

            <xsl:when test="$number mod $candidate = 0">
                <xsl:value-of select="$candidate" />
                <xsl:text> </xsl:text>
                <xsl:call-template name="generate">
                    <xsl:with-param name="number" select="$number div $candidate" />
                    <xsl:with-param name="candidate" select="$candidate" />
                </xsl:call-template>
            </xsl:when>

            <xsl:otherwise>

                <xsl:choose>
                    <xsl:when test="$candidate = 2">
                        <xsl:call-template name="generate">
                            <xsl:with-param name="number" select="$number" />
                            <xsl:with-param name="candidate" select="$candidate + 1" />
                        </xsl:call-template>
                    </xsl:when>
                    <xsl:otherwise>
                        <xsl:call-template name="generate">
                            <xsl:with-param name="number" select="$number" />
                            <xsl:with-param name="candidate" select="$candidate + 2" />
                        </xsl:call-template>
                    </xsl:otherwise>
                </xsl:choose>
            </xsl:otherwise>
        </xsl:choose>
    </xsl:template>

</xsl:stylesheet>


fcn primeFactors(n){  // Return a list of factors of n
   acc:=fcn(n,k,acc,maxD){  // k is 2,3,5,7,9,... not optimum
      if(n==1 or k>maxD) acc.close();
      else{
     q,r:=n.divr(k);   // divr-->(quotient,remainder)
     if(r==0) return(self.fcn(q,k,acc.write(k),q.toFloat().sqrt()));
     return(self.fcn(n,k+1+k.isOdd,acc,maxD))
      }
   }(n,2,Sink(List),n.toFloat().sqrt());
   m:=acc.reduce('*,1);      // mulitply factors
   if(n!=m) acc.append(n/m); // opps, missed last factor
   else acc;
}


V limit = 1000000
V k = limit
V n = k * 17
V primes = [1B] * n
primes[0] = primes[1] = 0B

L(i) 2..Int(sqrt(n))
   I !primes[i]
      L.continue
   L(j) (i * i .< n).step(i)
      primes[j] = 0B

DefaultDict[(Int, Int), Int] trans_map
V prev = -1

L(i) 0 .< n
   I primes[i]
      I prev != -1
         trans_map[(prev, i % 10)]++
      prev = i % 10

      I --k == 0
         L.break

print(‘First #. primes. Transitions prime % 10 > next-prime % 10.’.format(limit))
L(trans) sorted(trans_map.keys())
   print(‘#. -> #. count #5 frequency: #.4%’.format(trans[0], trans[1], trans_map[trans], 100.0 * trans_map[trans] / limit))


# extend SET, CLEAR and ELEM to operate on rows of BITS #
OP   SET   = ( INT n, REF[]BITS b )REF[]BITS:
     BEGIN
         INT w = n OVER bits width;
         b[ w ] := ( ( 1 + ( n MOD bits width ) ) SET b[ w ] );
         b
     END # SET # ;
OP   CLEAR = ( INT n, REF[]BITS b )REF[]BITS:
     BEGIN
         INT w = n OVER bits width;
         b[ w ] := ( ( 1 + ( n MOD bits width ) ) CLEAR b[ w ] );
         b
     END # SET # ;
OP   ELEM  = ( INT n, REF[]BITS b )BOOL: ( 1 + ( n MOD bits width ) ) ELEM b[ n OVER bits width ];

# constructs a bit array long enough to hold n values #
OP   BITARRAY = ( INT n )REF[]BITS: HEAP[ 0 : n OVER bits width ]BITS;

# construct a BITS value of all TRUE #
BITS all true = BEGIN
                    BITS v := 16r0;
                    FOR bit TO bits width DO v := bit SET v OD;
                    v
                END;

# initialises a bit array to all TRUE #
OP   SETALL   = ( REF[]BITS b )REF[]BITS:
     BEGIN
         FOR p FROM LWB b TO UPB b DO b[ p ] := all true OD;
         b
     END # SETALL # ;

# construct a sieve initialised to all TRUE apart from the first bit      #
INT sieve max = 15 500 000; # somewhat larger than the 1 000 000th prime  #
INT prime max =  1 000 000;
REF[]BITS sieve = 1 CLEAR SETALL BITARRAY sieve max;

# sieve the primes #
FOR s FROM 2 TO ENTIER sqrt( sieve max ) DO
    IF s ELEM sieve
    THEN
        FOR p FROM s * s BY s TO sieve max DO p CLEAR sieve OD
    FI
OD;

# count the number of times each combination of                           #
# ( last digit of previous prime, last digit of prime ) occurs            #
[ 0 : 9, 0 : 9 ]INT counts;
FOR p FROM 0 TO 9 DO FOR n FROM 0 TO 9 DO counts[ p, n ] := 0 OD OD;
INT previous prime := 2;
INT primes found   := 1;
FOR p FROM 3 TO sieve max WHILE primes found < prime max DO
    IF p ELEM sieve
    THEN
        primes found +:= 1;
        counts[ previous prime MOD 10, p MOD 10 ] +:= 1;
        previous prime := p
    FI
OD;

# print the counts #
# there are thus 4 possible final digits: 1, 3, 7, 9                      #
STRING labels = "123456789";                   # "labels" for the counts  #
INT total := 0;
FOR p TO 9 DO FOR n TO 9 DO total +:= counts[ p, n ] OD OD;
print( ( whole( primes found, 0 ), " primes, last prime considered: ", previous prime, newline ) );
FOR p TO 9 DO
    FOR n TO 9 DO
        IF counts[ p, n ] /= 0
        THEN
            print( ( labels[ p ], "->", labels[ n ]
                   , whole( counts[ p, n ], -8 )
                   , fixed( ( 100 * counts[ p, n ] ) / total, -8, 2 )
                   , newline
                   )
                 )
        FI
    OD
OD


F list_powerset(lst)
   V result = [[Int]()]
   L(x) lst
      result.extend(result.map(subset -> subset [+] [@x]))
   R result

print(list_powerset([1, 2, 3]))


on isPrime(n)
    if ((n < 4) or (n is 5)) then return (n > 1)
    if ((n mod 2 = 0) or (n mod 3 = 0) or (n mod 5 = 0)) then return false
    repeat with i from 7 to (n ^ 0.5) div 1 by 30
        if ((n mod i = 0) or (n mod (i + 4) = 0) or (n mod (i + 6) = 0) or ¬
            (n mod (i + 10) = 0) or (n mod (i + 12) = 0) or (n mod (i + 16) = 0) or ¬
            (n mod (i + 22) = 0) or (n mod (i + 24) = 0)) then return false
    end repeat

    return true
end isPrime

on conspiracy(limit)
    script o
        property counters : {{0, 0, 0, 0, 0, 0, 0, 0, 0}}
    end script
    repeat 8 times
        copy beginning of o's counters to end of o's counters
    end repeat

    if (limit > 1) then
        set primeCount to 1
        set i to 2 -- First prime.
        set n to 3 -- First number to test for primality.
        repeat until (primeCount = limit)
            if (isPrime(n)) then
                set primeCount to primeCount + 1
                set j to n mod 10
                set item j of item i of o's counters to (item j of item i of o's counters) + 1
                set i to j
            end if
            set n to n + 2
        end repeat
    end if

    set output to {"First " & limit & " primes: transitions between end digits of consecutive primes."}
    set totalTransitions to limit - 1
    repeat with i in {1, 2, 3, 5, 7, 9}
        set iTransitions to 0
        repeat with j from 1 to 9 by 2
            set iTransitions to iTransitions + (item j of item i of o's counters)
        end repeat
        repeat with j from 1 to 9 by 2
            set ijCount to item j of item i of o's counters
            if (ijCount > 0) then ¬
                set end of output to ¬
                    (i as text) & " → " & j & ¬
                    ("     count: " & ijCount) & ¬
                    ("     preference for " & j & ": " & (ijCount * 10000 / iTransitions as integer) / 100) & ¬
                    ("%     overall occurrence: " & (ijCount * 10000 / totalTransitions as integer) / 100 & "%")
        end repeat
    end repeat
    set astid to AppleScript's text item delimiters
    set AppleScript's text item delimiters to linefeed
    set output to output as text
    set AppleScript's text item delimiters to astid
    return output
end conspiracy

conspiracy(1000000)


report z_powerset.

interface set.
  methods:
    add_element
      importing
        element_to_be_added type any
      returning
        value(new_set)      type ref to set,

    remove_element
      importing
        element_to_be_removed type any
      returning
        value(new_set)        type ref to set,

    contains_element
      importing
        element_to_be_found type any
      returning
        value(contains)     type abap_bool,

    get_size
      returning
        value(size) type int4,

    is_equal
      importing
        set_to_be_compared_with type ref to set
      returning
        value(equal)            type abap_bool,

    get_elements
      exporting
        elements type any table,

    stringify
      returning
        value(stringified_set) type string.
endinterface.

class string_set definition.
  public section.
    interfaces:
      set.

    methods:
      constructor
        importing
          elements type stringtab optional,

      build_powerset
        returning
          value(powerset) type ref to string_set.

  private section.
    data elements type stringtab.
endclass.

class string_set implementation.
  method constructor.
    loop at elements into data(element).
      me->set~add_element( element ).
    endloop.
  endmethod.

  method set~add_element.
    if not line_exists( me->elements[ table_line = element_to_be_added ] ).
      append element_to_be_added to me->elements.
    endif.

    new_set = me.
  endmethod.

  method set~remove_element.
    if line_exists( me->elements[ table_line = element_to_be_removed ] ).
      delete me->elements where table_line = element_to_be_removed.
    endif.

    new_set = me.
  endmethod.

  method set~contains_element.
    contains = cond abap_bool(
      when line_exists( me->elements[ table_line = element_to_be_found ] )
      then abap_true
      else abap_false ).
  endmethod.

  method set~get_size.
    size = lines( me->elements ).
  endmethod.

  method set~is_equal.
    if set_to_be_compared_with->get_size( ) ne me->set~get_size( ).
      equal = abap_false.

      return.
    endif.

    loop at me->elements into data(element).
      if not set_to_be_compared_with->contains_element( element ).
        equal = abap_false.

        return.
      endif.
    endloop.

    equal = abap_true.
  endmethod.

  method set~get_elements.
    elements = me->elements.
  endmethod.

  method set~stringify.
    stringified_set = cond string(
      when me->elements is initial
      then `∅`
      when me->elements eq value stringtab( ( `∅` ) )
      then `{ ∅ }`
      else reduce string(
        init result = `{ `
        for element in me->elements
        next result = cond string(
          when element eq ``
          then |{ result }∅, |
          when strlen( element ) eq 1 and element ne `∅`
          then |{ result }{ element }, |
          else |{ result }\{{ element }\}, | ) ) ).

    stringified_set = replace(
      val = stringified_set
      regex = `, $`
      with = ` }`).
  endmethod.

  method build_powerset.
    data(powerset_elements) = value stringtab( ( `` ) ).

    loop at me->elements into data(element).
      do lines( powerset_elements ) times.
        if powerset_elements[ sy-index ] ne `∅`.
          append |{ powerset_elements[ sy-index ] }{ element }| to powerset_elements.
        else.
          append element to powerset_elements.
        endif.
      enddo.
    endloop.

    powerset = new string_set( powerset_elements ).
  endmethod.
endclass.

start-of-selection.
  data(set1) = new string_set( ).
  data(set2) = new string_set( ).
  data(set3) = new string_set( ).

  write: |𝑷( { set1->set~stringify( ) } ) -> { set1->build_powerset( )->set~stringify( ) }|, /.

  set2->set~add_element( `∅` ).
  write: |𝑷( { set2->set~stringify( ) } ) -> { set2->build_powerset( )->set~stringify( ) }|, /.

  set3->set~add_element( `1` )->add_element( `2` )->add_element( `3` )->add_element( `3` )->add_element( `4`
    )->add_element( `4` )->add_element( `4` ).
  write: |𝑷( { set3->set~stringify( ) } ) -> { set3->build_powerset( )->set~stringify( ) }|, /.


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

typedef unsigned char byte;

struct Transition {
    byte a, b;
    unsigned int c;
} transitions[100];

void init() {
    int i, j;
    for (i = 0; i < 10; i++) {
        for (j = 0; j < 10; j++) {
            int idx = i * 10 + j;
            transitions[idx].a = i;
            transitions[idx].b = j;
            transitions[idx].c = 0;
        }
    }
}

void record(int prev, int curr) {
    byte pd = prev % 10;
    byte cd = curr % 10;
    int i;

    for (i = 0; i < 100; i++) {
        int z = 0;
        if (transitions[i].a == pd) {
            int t = 0;
            if (transitions[i].b == cd) {
                transitions[i].c++;
                break;
            }
        }
    }
}

void printTransitions(int limit, int last_prime) {
    int i;

    printf("%d primes, last prime considered: %d\n", limit, last_prime);

    for (i = 0; i < 100; i++) {
        if (transitions[i].c > 0) {
            printf("%d->%d  count: %5d  frequency: %.2f\n", transitions[i].a, transitions[i].b, transitions[i].c, 100.0 * transitions[i].c / limit);
        }
    }
}

bool isPrime(int n) {
    int s, t, a1, a2;

    if (n % 2 == 0) return n == 2;
    if (n % 3 == 0) return n == 3;
    if (n % 5 == 0) return n == 5;
    if (n % 7 == 0) return n == 7;
    if (n % 11 == 0) return n == 11;
    if (n % 13 == 0) return n == 13;
    if (n % 17 == 0) return n == 17;
    if (n % 19 == 0) return n == 19;

    // assuming that addition is faster then multiplication
    t = 23;
    a1 = 96;
    a2 = 216;
    s = t * t;
    while (s <= n) {
        if (n % t == 0) return false;

        // first increment
        s += a1;
        t += 2;
        a1 += 24;
        assert(t * t == s);

        if (s <= n) {
            if (n % t == 0) return false;

            // second increment
            s += a2;
            t += 4;
            a2 += 48;
            assert(t * t == s);
        }
    }

    return true;
}

#define LIMIT 1000000
int main() {
    int last_prime = 3, n = 5, count = 2;

    init();
    record(2, 3);

    while (count < LIMIT) {
        if (isPrime(n)) {
            record(last_prime, n);
            last_prime = n;
            count++;
        }
        n += 2;

        if (count < LIMIT) {
            if (isPrime(n)) {
                record(last_prime, n);
                last_prime = n;
                count++;
            }
            n += 4;
        }
    }

    printTransitions(LIMIT, last_prime);

    return 0;
}


with Ada.Text_IO, Ada.Command_Line;
use Ada.Text_IO, Ada.Command_Line;

procedure powerset is
begin
	for set in 0..2**Argument_Count-1 loop
		Put ("{");
		declare
			k : natural := set;
			first : boolean := true;
		begin
			for i in 1..Argument_Count loop
				if k mod 2 = 1 then
					Put ((if first then "" else ",") & Argument (i));
					first := false;
			  	end if;
				k := k / 2; -- we go to the next bit of "set"
			end loop;
		end;
		Put_Line("}");
	end loop;
end powerset;


MODE MEMBER = INT;

PROC power set = ([]MEMBER s)[][]MEMBER:(
  [2**UPB s]FLEX[1:0]MEMBER r;
  INT upb r := 0;
  r[upb r +:= 1] := []MEMBER(());
  FOR i TO UPB s DO
    MEMBER e = s[i];
    FOR j TO upb r DO
      [UPB r[j] + 1]MEMBER x;
      x[:UPB x-1] := r[j];
      x[UPB x] := e; # append to the end of x #
      r[upb r +:= 1] := x # append to end of r #
    OD
  OD;
  r[upb r] := s;
  r
);
# Example: #
test:(
  [][]MEMBER set = power set((1, 2, 4));
  FOR member TO UPB set DO
    INT upb = UPB set[member];
    FORMAT repr set = $"("f( upb=0 | $$ | $n(upb-1)(d", ")d$ )");"$;
    printf(($"set["d"] = "$,member, repr set, set[member],$l$))
  OD
)


using System;

namespace PrimeConspiracy {
    class Program {
        static void Main(string[] args) {
            const int limit = 1_000_000;
            const int sieveLimit = 15_500_000;

            int[,] buckets = new int[10, 10];
            int prevDigit = 2;
            bool[] notPrime = Sieve(sieveLimit);

            for (int n = 3, primeCount = 1; primeCount < limit; n++) {
                if (notPrime[n]) continue;

                int digit = n % 10;
                buckets[prevDigit, digit]++;
                prevDigit = digit;
                primeCount++;
            }

            for (int i = 0; i < 10; i++) {
                for (int j = 0; j < 10; j++) {
                    if (buckets[i, j] != 0) {
                        Console.WriteLine("{0} -> {1}  count: {2,5:d}  frequency : {3,6:0.00%}", i, j, buckets[i, j], 1.0 * buckets[i, j] / limit);
                    }
                }
            }
        }

        public static bool[] Sieve(int limit) {
            bool[] composite = new bool[limit];
            composite[0] = composite[1] = true;

            int max = (int)Math.Sqrt(limit);
            for (int n = 2; n <= max; n++) {
                if (!composite[n]) {
                    for (int k = n * n; k < limit; k += n) {
                        composite[k] = true;
                    }
                }
            }

            return composite;
        }
    }
}


-- POWER SET -----------------------------------------------------------------

-- powerset :: [a] -> [[a]]
on powerset(xs)
    script subSet
        on |λ|(acc, x)
            script cons
                on |λ|(y)
                    {x} & y
                end |λ|
            end script

            acc & map(cons, acc)
        end |λ|
    end script

    foldr(subSet, {{}}, xs)
end powerset

-- TEST ----------------------------------------------------------------------
on run
    script test
        on |λ|(x)
            set {setName, setMembers} to x
            {setName, powerset(setMembers)}
        end |λ|
    end script

    map(test, [¬
        ["Set [1,2,3]", {1, 2, 3}], ¬
        ["Empty set", {}], ¬
        ["Set containing only empty set", {{}}]])

    --> {{"Set [1,2,3]", {{}, {3}, {2}, {2, 3}, {1}, {1, 3}, {1, 2}, {1, 2, 3}}},
    -->  {"Empty set", {{}}},
    -->  {"Set containing only empty set", {{}, {{}}}}}
end run

-- GENERIC FUNCTIONS ---------------------------------------------------------

-- foldr :: (a -> b -> a) -> a -> [b] -> a
on foldr(f, startValue, xs)
    tell mReturn(f)
        set v to startValue
        set lng to length of xs
        repeat with i from lng to 1 by -1
            set v to |λ|(v, item i of xs, i, xs)
        end repeat
        return v
    end tell
end foldr

-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
    tell mReturn(f)
        set lng to length of xs
        set lst to {}
        repeat with i from 1 to lng
            set end of lst to |λ|(item i of xs, i, xs)
        end repeat
        return lst
    end tell
end map

-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: Handler -> Script
on mReturn(f)
    if class of f is script then
        f
    else
        script
            property |λ| : f
        end script
    end if
end mReturn


#include <vector>
#include <iostream>
#include <cmath>
#include <utility>
#include <map>
#include <iomanip>

bool isPrime( int i ) {
   int stop = std::sqrt( static_cast<double>( i ) ) ;
   for ( int d = 2 ; d <= stop ; d++ )
      if ( i % d == 0 )
	 return false ;
   return true ;
}

class Compare {
public :
   Compare( ) {
   }

   bool operator( ) ( const std::pair<int , int> & a , const std::pair<int, int> & b ) {
      if ( a.first != b.first )
	 return a.first < b.first ;
      else
	 return a.second < b.second ;
   }
};

int main( ) {
   std::vector<int> primes {2} ;
   int current = 3 ;
   while ( primes.size( ) < 1000000 ) {
      if ( isPrime( current ) )
	 primes.push_back( current ) ;
      current += 2 ;
   }
   Compare myComp ;
   std::map<std::pair<int, int>, int , Compare> conspiracy (myComp) ;
   for ( int i = 0 ; i < primes.size( ) -1 ; i++ ) {
      int a = primes[i] % 10 ;
      int b = primes[ i + 1 ] % 10 ;
      std::pair<int , int> numbers { a , b} ;
      conspiracy[numbers]++ ;
   }
   std::cout << "1000000 first primes. Transitions prime % 10 → next-prime % 10.\n" ;
   for ( auto it = conspiracy.begin( ) ; it != conspiracy.end( ) ; it++ ) {
      std::cout << (it->first).first << " -> " << (it->first).second << " count:" ;
      int frequency = it->second ;
      std::cout << std::right << std::setw( 15 ) << frequency << " frequency: " ;
      std::cout.setf(std::ios::fixed, std::ios::floatfield ) ;
      std::cout.precision( 2 ) ;
      std::cout << (static_cast<double>(frequency) / 1000000.0) * 100 << " %\n" ;
   }
   return 0 ;
}


(* ****** ****** *)
//
#include
"share/atspre_define.hats" // defines some names
#include
"share/atspre_staload.hats" // for targeting C
#include
"share/HATS/atspre_staload_libats_ML.hats" // for ...
//
(* ****** ****** *)
//
extern
fun
Power_set(xs: list0(int)): void
//
(* ****** ****** *)

// Helper: fast power function.
fun power(n: int, p: int): int =
	if p = 1 then n
	else if p = 0 then 1
	else if p % 2 = 0 then power(n*n, p/2)
	else n * power(n, p-1)

fun print_list(list: list0(int)): void =
  case+ list of
  | nil0() => println!(" ")
  | cons0(car, crd) =>
    let
      val () = begin print car; print ','; end
      val () = print_list(crd)
    in
    end

fun get_list_length(list: list0(int), length: int): int =
  case+ list of
  | nil0() => length
  | cons0(car, crd) => get_list_length(crd, length+1)

fun get_list_from_bit_mask(mask: int, list: list0(int), result: list0(int)): list0(int) =
  if mask = 0 then result
  else
    case+ list of
    | nil0() => result
    | cons0(car, crd) =>
      let
        val current: int = mask % 2
      in
        if current = 0 then
          get_list_from_bit_mask(mask >> 1, crd, result)
        else
          get_list_from_bit_mask(mask >> 1, crd, list0_cons(car, result))
      end

implement
Power_set(xs) = let
  val len: int = get_list_length(xs, 0)
  val pow: int = power(2, len)
  fun loop(mask: int, list: list0(int)): void =
    if mask > 0 && mask >= pow then ()
    else
      let
        val () = print_list(get_list_from_bit_mask(mask, list, list0_nil()))
      in
        loop(mask+1, list)
      end
  in
    loop(0, xs)
  end

(* ****** ****** *)

implement
main0() =
let
  val xs: list0(int) = cons0(1, list0_pair(2, 3))
in
  Power_set(xs)
end (* end of [main0] *)

(* ****** ****** *)


a = 1,a,--             ; elements separated by commas
StringSplit a, a, `,   ; a0 = #elements, a1,a2,... = elements of the set

t = {
Loop % (1<<a0) {       ; generate all 0-1 sequences
   x := A_Index-1
   Loop % a0
      t .= (x>>A_Index-1) & 1 ? a%A_Index% "," : ""
   t .= "}`n{"         ; new subsets in new lines
}
MsgBox % RegExReplace(SubStr(t,1,StrLen(t)-1),",}","}")


import std.algorithm;
import std.range;
import std.stdio;
import std.typecons;

alias Transition = Tuple!(int, int);

bool isPrime(int n) {
    if (n < 2) return false;
    if (n % 2 == 0) return n == 2;
    if (n % 3 == 0) return n == 3;
    int d = 5;
    while (d*d <= n) {
        if (n%d == 0) return false;
        d += 2;
        if (n%d == 0) return false;
        d += 4;
    }
    return true;
}

auto generatePrimes() {
    import std.concurrency;
    return new Generator!int({
        yield(2);
        int p = 3;
        while (p > 0) {
            if (isPrime(p)) {
                yield(p);
            }
            p += 2;
        }
    });
}

void main() {
    auto primes = generatePrimes().take(1_000_000).array;
    int[Transition] transMap;
    foreach (i; 0 .. primes.length - 1) {
        auto transition = Transition(primes[i] % 10, primes[i + 1] % 10);
        if (transition in transMap) {
            transMap[transition] += 1;
        } else {
            transMap[transition] = 1;
        }
    }
    auto sortedTransitions = transMap.keys.multiSort!(q{a[0] < b[0]}, q{a[1] < b[1]});
    writeln("First 1,000,000 primes. Transitions prime % 10 -> next-prime % 10.");
    foreach (trans; sortedTransitions) {
        writef("%s -> %s  count: %5d", trans[0], trans[1], transMap[trans]);
        writefln("  frequency: %4.2f%%", transMap[trans] / 10_000.0);
    }
}


cat power_set.awk
#!/usr/local/bin/gawk -f

# User defined function
function tochar(l,n,	r) {
 while (l) { n--; if (l%2 != 0) r = r sprintf(" %c ",49+n); l = int(l/2) }; return r
}

# For each input
{ for (i=0;i<=2^NF-1;i++) if (i == 0) printf("empty\n"); else printf("(%s)\n",tochar(i,NF)) }


      DIM list$(3) : list$() = "1", "2", "3", "4"
      PRINT FNpowerset(list$())
      END

      DEF FNpowerset(list$())
      IF DIM(list$(),1) > 31 ERROR 100, "Set too large to represent as integer"
      LOCAL i%, j%, s$
      s$ = "{"
      FOR i% = 0 TO (2 << DIM(list$(),1)) - 1
        s$ += "{"
        FOR j% = 0 TO DIM(list$(),1)
          IF i% AND (1 << j%) s$ += list$(j%) + ","
        NEXT
        IF RIGHT$(s$) = "," s$ = LEFT$(s$)
        s$ += "},"
      NEXT i%
      = LEFT$(s$) + "}"


DEFINE COUNT="20"
BYTE ARRAY levels=[6 11 16 21 26 31 36 41 46 51 56 61 66 71 76 81 86 91 96 101]
BYTE ARRAY values=[10 18 26 32 38 44 50 54 58 62 66 70 74 78 82 86 90 94 98 100]

PROC PrintValue(BYTE v)
  PrintB(v/100) Put('.)
  v=v MOD 100
  PrintB(v/10)
  v=v MOD 10
  PrintB(v)
RETURN

BYTE FUNC Map(BYTE v)
  BYTE i

  FOR i=0 TO COUNT-1
  DO
    IF v<levels(i) THEN
      RETURN (values(i))
    FI
  OD
RETURN (v)

PROC Main()
  BYTE i,v

  FOR i=0 TO 100
  DO
    v=Map(i)
    PrintValue(v)
    IF i MOD 5=4 THEN
      PutE()
    ELSE
      Put(' )
    FI
  OD
RETURN


type Price is delta 0.01 digits 3 range 0.0..1.0;
function Scale (Value : Price) return Price is
   X : constant array (1..19) of Price :=
          (  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
          );
   Y : constant array (1..20) of Price :=
          (  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.0
          );
   Low    : Natural := X'First;
   High   : Natural := X'Last;
   Middle : Natural;
begin
   loop
      Middle := (Low + High) / 2;
      if Value = X (Middle) then
         return Y (Middle + 1);
      elsif Value < X (Middle) then
         if Low = Middle then
            return Y (Low);
         end if;
         High := Middle - 1;
      else
         if High = Middle then
            return Y (High + 1);
         end if;
         Low := Middle + 1;
      end if;
   end loop;
end Scale;


(lib 'math) ;; (in-primes n) stream
(decimals 4)

(define (print-trans trans   m N)
(printf "%d first primes. Transitions prime %% %d → next-prime %% %d." N m m)
	(define s (// (apply + (vector->list trans)) 100))
	(for ((i (* m m)) (t trans))
	#:continue (<= t 1) ;; get rid of 2,5 primes
	(printf  " %d → %d   count: %10d frequency:   %d %%  "
              (quotient i m)  (% i m) t  (// t s) )))

;; can apply to any modulo m
;; (in-primes n) returns a stream of primes

(define (task (m  10) (N 1000_000))
	(define trans (make-vector (* m m)))
	(for ((p1 (in-primes 2)) (p2 (in-primes 3)) (k N))
		 (vector+= trans (+ (* (% p1 m) m) (% p2 m)) 1))
	(print-trans trans   m N))


defmodule Prime do
  def conspiracy(m) do
    IO.puts "#{m} first primes. Transitions prime % 10 → next-prime % 10."
    Enum.map(prime(m), &rem(&1, 10))
    |> Enum.chunk(2,1)
    |> Enum.reduce(Map.new, fn [a,b],acc -> Map.update(acc, {a,b}, 1, &(&1+1)) end)
    |> Enum.sort
    |> Enum.each(fn {{a,b},v} ->
         sv = to_string(v) |> String.rjust(10)
         sf = Float.to_string(100.0*v/m, [decimals: 4])
         IO.puts "#{a} → #{b} count:#{sv} frequency:#{sf} %"
       end)
  end

  def prime(n) do
    max = n * :math.log(n * :math.log(n)) |> trunc      # from Rosser's theorem
    Enum.to_list(2..max)
    |> prime(:math.sqrt(max), [])
    |> Enum.take(n)
  end
  defp prime([h|t], limit, result) when h>limit, do: Enum.reverse(result, [h|t])
  defp prime([h|t], limit, result) do
    prime((for x <- t, rem(x,h)>0, do: x), limit, [h|result])
  end
end

Prime.conspiracy(1000000)


P ← (⥊·↕2⥊˜≠)/¨<


( ( powerset
  =   done todo first
    .   !arg:(?done.?todo)
      & (   !todo:%?first ?todo
          & (powerset$(!done !first.!todo),powerset$(!done.!todo))
        | !done
        )
  )
& out$(powerset$(.1 2 3 4))
);


main:
(
    # Just get a random price between 0 and 1 #
    # srand(time(NIL)); #
    REAL price := random;
    REAL tops := 0.06;
    REAL std val := 0.10;

    # Conditionals are a little odd here "(price-0.001 < tops AND
    price+0.001 > tops)" is to check if they are equal. Stupid
    C floats, right?   :) #
    WHILE ( price>tops OR (price-0.001 < tops AND price+0.001 > tops) ) AND tops<=1.01
    DO
        tops+:=0.05;

        IF std val < 0.26 THEN
                std val +:= 0.08
        ELIF std val < 0.50 THEN
                std val +:= 0.06
        ELSE
                std val +:= 0.04
        FI;

        IF std val > 0.98 THEN
                std val := 1.0
        FI
    OD;

    printf(($"Value :   "z.2dl,"Converted to standard :   "z.2dl$, price, std val))
)


-- This handler just returns the standardised real value. It's up to external processes to format it for display.

on standardisePrice(input)
    set integerPart to input div 1.0
    set fractionalPart to input mod 1.0

    if (fractionalPart is 0.0) then
        return input as real
    else if (fractionalPart < 0.06) then
        return integerPart + 0.1
    else if (fractionalPart < 0.16) then
        return integerPart + 0.18 + (fractionalPart - 0.06) div 0.05 * 0.08
    else if (fractionalPart < 0.36) then
        return integerPart + 0.32 + (fractionalPart - 0.16) div 0.05 * 0.06
    else if (fractionalPart < 0.96) then
        return integerPart + 0.54 + (fractionalPart - 0.36) div 0.05 * 0.04
    else
        return integerPart + 1.0
    end if
end standardisePrice

-- Test code:
set originals to {}
set standardised to {}
repeat 20 times
    set price to (random number 100) / 100
    set end of originals to text 2 thru -2 of ((price + 10.001) as text)
    set end of standardised to text 2 thru -2 of ((standardisePrice(price) + 10.001) as text)
end repeat

set astid to AppleScript's text item delimiters
set AppleScript's text item delimiters to ", "
set output to linefeed & "Originals:    " & originals & linefeed & "Standardised: " & standardised
set AppleScript's text item delimiters to astid
return output


// Prime Conspiracy. Nigel Galloway: March 27th., 2018
primes|>Seq.take 10000|>Seq.map(fun n->n%10)|>Seq.pairwise|>Seq.countBy id|>Seq.groupBy(fun((n,_),_)->n)|>Seq.sortBy(fst)
  |>Seq.iter(fun(_,n)->Seq.sortBy(fun((_,n),_)->n) n|>Seq.iter(fun((n,g),z)->printfn "%d -> %d ocurred %3d times" n g z))


USING: assocs formatting grouping kernel math math.primes math.statistics
sequences sorting ;
IN: rosetta-code.prime-conspiracy

: transitions ( n -- alist )
    nprimes [ 10 mod ] map 2 clump histogram >alist natural-sort ;

: t-values ( transition -- i j count freq )
    first2 [ first2 ] dip dup 10000. / ;

: print-trans ( transition -- )
    t-values "%d -> %d  count: %5d  frequency: %5.2f%%\n" printf ;

: header ( n -- )
    "First %d primes. Transitions prime %% 10 -> next-prime %% 10.\n" printf ;

: main ( -- )
    1,000,000 dup header transitions [ print-trans ] each ;

MAIN: main


      PROGRAM INHERIT	!Last digit persistence in successive prime numbers.
      USE PRIMEBAG	!Inherit this also.
      INTEGER MBASE,P0,NHIC	!Problem bounds.
      PARAMETER (MBASE = 13, P0 = 2, NHIC = 100000000)	!This should do.
      INTEGER N(0:MBASE - 1,0:MBASE - 1,2:MBASE)	!The counts. A triangular shape would be better.
      INTEGER I,B,D1,D2	!Assistants.
      INTEGER P,PP	!Prime, and Previous Prime.

      MSG = 6		!Standard output.
      WRITE (MSG,1) MBASE,P0,NHIC	!Announce intent.
    1 FORMAT ("Working in base 2 to ",I0," count the transitions "
     1 "from the low-order digit of one prime number ",/,
     2 "to the low-order digit of its successor. Starting with ",I0,
     3 " and making ",I0," advances.")
      IF (.NOT.GRASPPRIMEBAG(66)) STOP "Gan't grab my file!"	!Attempt in hope.

Chug through the primes.
   10 N = 0	!Clear all my counts!
      P = P0	!Start with the starting prime.
      DO I = 1,NHIC	!Make the specified number of advances.
        PP = P			!Thus, remember the previous prime.
        P = NEXTPRIME(P)	!And obtain the current prime.
        DO B = 2,MBASE		!For these, step through the relevant bases.
          D1 = MOD(PP,B)		!Last digit of the previous prime.
          D2 = MOD(P,B)			!In the base of the moment.
          N(D1,D2,B) = N(D1,D2,B) + 1	!Whee!
        END DO			!On to the next base.
      END DO		!And the next advance.
      WRITE (MSG,11) P	!Might as well announce where we got to.
   11 FORMAT ("Ending with ",I0)	!Hopefully, no overflow.

Cast forth the results.
   20 DO B = 2,MBASE	!Present results for each base.
        WRITE (MSG,21) B		!Announce it.
   21   FORMAT (/,"For base ",I0)	!Set off with a blank line.
        WRITE (MSG,22) (D1, D1 = 0,B - 1)	!The heading.
   22   FORMAT (" Last digit ending  ",I2,66I9)	!Alignment to match FORMAT 23.
        DO D2 = 0,B - 1		!For a given base, these are the possible ending digits of the successor.
          IF (ALL(N(0:B - 1,D2,B).EQ.0)) CYCLE	!No progenitor advanced to this successor digit?
          WRITE (MSG,23) D2,N(0:B - 1,D2,B)	!Otherwise, show the counts for the progenitor's digits.
   23     FORMAT (" next prime ends",I3,":",I2,66I9)	!Ah, layout.
        END DO			!On to the next successor digit.
      END DO		!On to the next base.
      END	!That was easy.


#include <stdio.h>

struct node {
	char *s;
	struct node* prev;
};

void powerset(char **v, int n, struct node *up)
{
	struct node me;

	if (!n) {
		putchar('[');
		while (up) {
			printf(" %s", up->s);
			up = up->prev;
		}
		puts(" ]");
	} else {
		me.s = *v;
		me.prev = up;
		powerset(v + 1, n - 1, up);
		powerset(v + 1, n - 1, &me);
	}
}

int main(int argc, char **argv)
{
	powerset(argv + 1, argc - 1, 0);
	return 0;
}


public IEnumerable<IEnumerable<T>> GetPowerSet<T>(List<T> list)
{
    return from m in Enumerable.Range(0, 1 << list.Count)
                  select
                      from i in Enumerable.Range(0, list.Count)
                      where (m & (1 << i)) != 0
                      select list[i];
}

public void PowerSetofColors()
{
    var colors = new List<KnownColor> { KnownColor.Red, KnownColor.Green,
        KnownColor.Blue, KnownColor.Yellow };

    var result = GetPowerSet(colors);

    Console.Write( string.Join( Environment.NewLine,
        result.Select(subset =>
            string.Join(",", subset.Select(clr => clr.ToString()).ToArray())).ToArray()));
}


; Submitted by MasterFocus --- http://tiny.cc/iTunis

Loop
{
  InputBox, OutputVar, Price Fraction Example, Insert the value to be rounded.`n* [ 0 < value < 1 ]`n* Press ESC or Cancel to exit, , 200, 150
  If ErrorLevel
    Break
  MsgBox % "Input: " OutputVar "`nResult: " PriceFraction( OutputVar )
}

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

PriceFraction( p_Input )
{

  If p_Input is not float ; returns 0 if input is not a float
    Return 0

  If ( ( p_Input <= 0 ) OR ( p_Input >= 1 ) ) ; returns 0 is input is out of range
    Return 0

  ; declaring the table (arbitrary delimiters in use are '§' and '|')
  l_List := "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"

  Loop, Parse, l_List, § ; retrieves each field (delimited by '§')
  {
    StringSplit, l_Array, A_LoopField, | ; splits current field (using delimiter '|')
    If ( p_Input <= l_Array1 )
      Return l_Array2 ; returns the second value if input <= first value
  }

  Return 0 ; returns 0, indicating failure (shouldn't be reached though)

}


' version 13-04-2017
' updated 09-08-2018 Using bit-sieve of odd numbers
' compile with: fbc -s console
' compile with: fbc -s console -Wc -O2 ->more than 2x faster(20.2-> 8,7s)

const max = 2040*1000*1000  ' enough for 100,000,000 primes
const max2 = (max -1) \ 2
Dim As uByte _bit(7)
Dim shared As uByte sieve(max2 \ 8 + 1)
Dim shared As ULong end_digit(1 To 9, 1 To 9)
Dim As ULong i, j, x, i1, j1, x1, c, c1
Dim As String frmt_str = " # " + Chr(26) + " # count:######## frequency:##.##%"

' bit Mask
For i = 0 To 7
  _bit(i) = 1 shl i
Next
' sieving
For i = 1 To  (sqr(max) -1) / 2
  x = 2*i+1
  If (sieve(i Shr 3) And _bit(i And 7)) = 0 Then
    For j = (2*i+2)*i To max2 Step x
      sieve(j Shr 3) or= _bit(j And 7)
    Next
  End If
Next

' count
x = 2 : c = 1
For i = 1 To max2
    If (sieve(i Shr 3) And _bit(i And 7)) = 0 Then
        j = (2*i+1) Mod 10
        end_digit(x, j) += 1
        x = j
        c += 1
        If c = 1000000 Or c = 100000000 Then
            Print "first "; c; " primes"
            c1 = c \ 100
            For i1 = 1 To 9
                For j1 = 1 To 9
                    x1 = end_digit(i1, j1)
                    If x1 <> 0 Then
                         Print Using frmt_str; i1; j1; x1; (x1 / c1)
                    End If
                Next
            Next
            Print
            If c = 100000000 Then Exit for
        End If
    End If
Next

' empty keyboard buffer
While Inkey <> "" : Wend
Print : Print "hit any key to end program"
Sleep
End


#include <iostream>
#include <set>
#include <vector>
#include <iterator>
#include <algorithm>
typedef std::set<int> set_type;
typedef std::set<set_type> powerset_type;

powerset_type powerset(set_type const& set)
{
  typedef set_type::const_iterator set_iter;
  typedef std::vector<set_iter> vec;
  typedef vec::iterator vec_iter;

  struct local
  {
    static int dereference(set_iter v) { return *v; }
  };

  powerset_type result;

  vec elements;
  do
  {
    set_type tmp;
    std::transform(elements.begin(), elements.end(),
                   std::inserter(tmp, tmp.end()),
                   local::dereference);
    result.insert(tmp);
    if (!elements.empty() && ++elements.back() == set.end())
    {
      elements.pop_back();
    }
    else
    {
      set_iter iter;
      if (elements.empty())
      {
        iter = set.begin();
      }
      else
      {
        iter = elements.back();
        ++iter;
      }
      for (; iter != set.end(); ++iter)
      {
        elements.push_back(iter);
      }
    }
  } while (!elements.empty());

  return result;
}

int main()
{
  int values[4] = { 2, 3, 5, 7 };
  set_type test_set(values, values+4);

  powerset_type test_powerset = powerset(test_set);

  for (powerset_type::iterator iter = test_powerset.begin();
       iter != test_powerset.end();
       ++iter)
  {
    std::cout << "{ ";
    char const* prefix = "";
    for (set_type::iterator iter2 = iter->begin();
         iter2 != iter->end();
         ++iter2)
    {
      std::cout << prefix << *iter2;
      prefix = ", ";
    }
    std::cout << " }\n";
  }
}


BEGIN {
    O = ".06 .11 .16 .21 .26 .31 .36 .41 .46 .51 .56 .61 .66 .71 .76 .81 .86 .91 .96 1.01"
    N = ".10 .18 .26 .32 .38 .44 .50 .54 .58 .62 .66 .70 .74 .78 .82 .86 .90 .94 .98 1.00"
    fields = split(O,Oarr," ") # original values
    split(N,Narr," ") # replacement values
    for (i=-.01; i<=1.02; i+=.01) { # test
      printf("%5.2f = %4.2f\n",i,lookup(i))
    }
}
function lookup(n,  i) {
    if (n < 0 || n > 1.01) {
      return(0) # when input is out of range
    }
    for (i=1; i<=fields; i++) {
      # +10 is used because .11 returned .18 instead of .26
      # under AWK95, GAWK, and MAWK; Thompson Automation's TAWK worked correctly
      if (n+10 < Oarr[i]+10) {
        return(Narr[i])
      }
    }
}


DECLARE FUNCTION PriceFraction! (price AS SINGLE)

RANDOMIZE TIMER
DIM x AS SINGLE
x = RND
PRINT x, PriceFraction(x)

FUNCTION PriceFraction! (price AS SINGLE)
    'returns price unchanged if invalid value
    SELECT CASE price
        CASE IS < 0!
            PriceFraction! = price
        CASE IS < .06
            PriceFraction! = .1
        CASE IS < .11
            PriceFraction! = .18
        CASE IS < .16
            PriceFraction! = .26
        CASE IS < .21
            PriceFraction! = .32
        CASE IS < .26
            PriceFraction! = .38
        CASE IS < .31
            PriceFraction! = .44
        CASE IS < .36
            PriceFraction! = .5
        CASE IS < .41
            PriceFraction! = .54
        CASE IS < .46
            PriceFraction! = .58
        CASE IS < .51
            PriceFraction! = .62
        CASE IS < .56
            PriceFraction! = .66
        CASE IS < .61
            PriceFraction! = .7
        CASE IS < .66
            PriceFraction! = .74
        CASE IS < .71
            PriceFraction! = .78
        CASE IS < .76
            PriceFraction! = .82
        CASE IS < .81
            PriceFraction! = .86
        CASE IS < .86
            PriceFraction! = .9
        CASE IS < .91
            PriceFraction! = .94
        CASE IS < .96
            PriceFraction! = .98
        CASE IS < 1.01
            PriceFraction! = 1!
        CASE ELSE
            PriceFraction! = price
    END SELECT
END FUNCTION


package main

import (
	"fmt"
	"sort"
)

func sieve(limit uint64) []bool {
	limit++
	// True denotes composite, false denotes prime.
	// We don't bother filling in the even composites.
	c := make([]bool, limit)
	c[0] = true
	c[1] = true
	p := uint64(3) // Start from 3.
	for {
		p2 := p * p
		if p2 >= limit {
			break
		}
		for i := p2; i < limit; i += 2 * p {
			c[i] = true
		}
		for {
			p += 2
			if !c[p] {
				break
			}
		}
	}
	return c
}

func main() {
	// sieve up to the 100 millionth prime
	sieved := sieve(2038074743)

	transMap := make(map[int]int, 19)
	i := 2            // last digit of first prime
	p := int64(3 - 2) // next prime, -2 since we +=2 first
	n := 1
	for _, num := range [...]int{1e4, 1e6, 1e8} {
		for ; n < num; n++ {
			// Set p to next prime by skipping composites.
			p += 2
			for sieved[p] {
				p += 2
			}
			// Count transition of i -> j.
			j := int(p % 10)
			transMap[i*10+j]++
			i = j
		}
		reportTransitions(transMap, n)
	}
}

func reportTransitions(transMap map[int]int, num int) {
	keys := make([]int, 0, len(transMap))
	for k := range transMap {
		keys = append(keys, k)
	}
	sort.Ints(keys)
	fmt.Println("First", num, "primes. Transitions prime % 10 -> next-prime % 10.")
	for _, key := range keys {
		count := transMap[key]
		freq := float64(count) / float64(num) * 100
		fmt.Printf("%d -> %d  count: %7d", key/10, key%10, count)
		fmt.Printf("  frequency: %4.2f%%\n", freq)
	}
	fmt.Println()
}


print_power_set = (arr) ->
  console.log "POWER SET of #{arr}"
  for subset in power_set(arr)
    console.log subset

power_set = (arr) ->
  result = []
  binary = (false for elem in arr)
  n = arr.length
  while binary.length <= n
    result.push bin_to_arr binary, arr
    i = 0
    while true
      if binary[i]
        binary[i] = false
        i += 1
      else
        binary[i] = true
        break
    binary[i] = true
  result

bin_to_arr = (binary, arr) ->
  (arr[i] for i of binary when binary[arr.length - i  - 1])

print_power_set []
print_power_set [4, 2, 1]
print_power_set ['dog', 'c', 'b', 'a']


arraybase 1
dim byValue = {10, 18, 26, 32, 38, 44, 50, 54, 58, 62, 66, 70, 74, 78, 82, 86, 90, 94, 98, 100}
dim byLimit = {6, 11, 16, 21, 26, 31, 36, 41, 46, 51, 56, 61, 66, 71, 76, 81, 86, 91, 96}

for byCount = 1 to 100
    for byCheck = 0 to byLimit[?]
	if byCount < byLimit[byCheck] then exit for
    next byCheck
    print ljust((byCount/100),4," "); " -> "; ljust((byValue[byCheck]/100),4," "); chr(9);
    if byCount mod 5 = 0 then print
next byCount
end


import Data.List (group, sort)
import Text.Printf (printf)
import Data.Numbers.Primes (primes)

freq :: [(Int, Int)] -> Float
freq xs = realToFrac (length xs) / 100

line :: [(Int, Int)] -> IO ()
line t@((n1, n2):xs) = printf "%d -> %d count: %5d frequency: %2.2f %%\n" n1 n2 (length t) (freq t)

main :: IO ()
main = mapM_ line $ groups primes
  where groups = tail . group . sort . (\n -> zip (0: n) n) . fmap (`mod` 10) . take 10000


public array function powerset(required array data)
{
  var ps = [""];
  var d = arguments.data;
  var lenData = arrayLen(d);
  var lenPS = 0;
  for (var i=1; i LTE lenData; i++)
  {
    lenPS = arrayLen(ps);
    for (var j = 1; j LTE lenPS; j++)
    {
      arrayAppend(ps, listAppend(ps[j], d[i]));
    }
  }
  return ps;
}

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


(defun powerset (s)
  (if s (mapcan (lambda (x) (list (cons (car s) x) x))
                (powerset (cdr s)))
      '(())))


public class PrimeConspiracy {

    public static void main(String[] args) {
        final int limit = 1000_000;
        final int sieveLimit = 15_500_000;

        int[][] buckets = new int[10][10];
        int prevDigit = 2;
        boolean[] notPrime = sieve(sieveLimit);

        for (int n = 3, primeCount = 1; primeCount < limit; n++) {
            if (notPrime[n])
                continue;

            int digit = n % 10;
            buckets[prevDigit][digit]++;
            prevDigit = digit;
            primeCount++;
        }

        for (int i = 0; i < 10; i++) {
            for (int j = 0; j < 10; j++) {
                if (buckets[i][j] != 0) {
                    System.out.printf("%d -> %d : %2f%n", i,
                            j, buckets[i][j] / (limit / 100.0));
                }
            }
        }
    }

    public static boolean[] sieve(int limit) {
        boolean[] composite = new boolean[limit];
        composite[0] = composite[1] = true;

        int max = (int) Math.sqrt(limit);
        for (int n = 2; n <= max; n++) {
            if (!composite[n]) {
                for (int k = n * n; k < limit; k += n) {
                    composite[k] = true;
                }
            }
        }
        return composite;
    }
}


import std.algorithm;
import std.range;

auto powerSet(R)(R r)
{
	return
		(1L<<r.length)
		.iota
		.map!(i =>
			r.enumerate
			.filter!(t => (1<<t[0]) & i)
			.map!(t => t[1])
		);
}

unittest
{
	int[] emptyArr;
	assert(emptyArr.powerSet.equal!equal([emptyArr]));
	assert(emptyArr.powerSet.powerSet.equal!(equal!equal)([[], [emptyArr]]));
}

void main(string[] args)
{
	import std.stdio;
	args[1..$].powerSet.each!writeln;
}


powerset s:
	local :out [ set{ } ]
	for value in keys s:
		for subset in copy out:
			local :subset+1 copy subset
			set-to subset+1 value true
			push-to out subset+1
	out

!. powerset set{ 1 2 3 4 }


using Printf, Primes
using DataStructures

function counttransitions(upto::Integer)
    cnt = counter(Pair{Int,Int})
    tot = 0
    prv, nxt = 2, 3
    while nxt ≤ upto
        push!(cnt, prv % 10 => nxt % 10)
        prv = nxt
        nxt = nextprime(nxt + 1)
        tot += 1
    end
    return sort(Dict(cnt)), tot - 1
end

trans, tot = counttransitions(100_000_000)

println("First 100_000_000 primes, last digit transitions:")
for ((i, j), fr) in trans
    @printf("%i → %i: freq. %3.4f%%\n", i, j, 100fr / tot)
end


// version 1.1.2
// compiled with flag -Xcoroutines=enable to suppress 'experimental' warning

import kotlin.coroutines.experimental.*

typealias Transition = Pair<Int, Int>

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

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

fun main(args: Array<String>) {
    val primes = generatePrimes().take(1_000_000).toList()
    val transMap = mutableMapOf<Transition, Int>()
    for (i in 0 until primes.size - 1) {
        val transition = primes[i] % 10 to primes[i + 1] % 10
        if (transMap.containsKey(transition))
            transMap[transition] = transMap[transition]!! + 1
        else
            transMap.put(transition, 1)
    }
    val sortedTransitions = transMap.keys.sortedBy { it.second }.sortedBy { it.first }
    println("First 1,000,000 primes. Transitions prime % 10 -> next-prime % 10.")
    for (trans in sortedTransitions) {
        print("${trans.first} -> ${trans.second}  count: ${"%5d".format(transMap[trans])}")
        println("  frequency: ${"%4.2f".format(transMap[trans]!! / 10000.0)}%")
    }
}


program Power_set;

{$APPTYPE CONSOLE}

uses
  System.SysUtils;

const
  n = 4;

var
  buf: TArray<Integer>;

procedure rec(ind, bg: Integer);
begin
  for var i := bg to n - 1 do
  begin
    buf[ind] := i;
    for var j := 0 to ind do
      write(buf[j]: 2);
    writeln;
    rec(ind + 1, buf[ind] + 1);
  end;
end;

begin
  SetLength(buf, n);
  rec(0,0);
  {$IFNDEF UNIX}readln;{$ENDIF}
end.


let n = 4
let buf = Array.Empty(n)

func rec(idx, begin) {
    for i in begin..<n {
        buf[idx] = i
        for j in 0..idx {
            print("{0, 2}".Format(buf[j]), terminator: "")
        }
        print("")
        rec(idx + 1, buf[idx] + 1)
    }
}

rec(0, 0)


F is_prime(n)
   I n < 2
      R 0B
   L(i) 2..Int(sqrt(n))
      I n % i == 0
         R 0B
   R 1B


namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            for (int x = 0; x < 10; x++)
            {
                Console.WriteLine("In: {0:0.00}, Out: {1:0.00}", ((double)x) / 10, SpecialRound(((double)x) / 10));
            }

            Console.WriteLine();

            for (int x = 0; x < 10; x++)
            {
                Console.WriteLine("In: {0:0.00}, Out: {1:0.00}", ((double)x) / 10 + 0.05, SpecialRound(((double)x) / 10 + 0.05));
            }

            Console.WriteLine();
            Console.WriteLine("In: {0:0.00}, Out: {1:0.00}", 1.01, SpecialRound(1.01));

            Console.Read();
        }

        private static double SpecialRound(double inValue)
        {
            if (inValue > 1) return 1;

            double[] Splitters = new double[] {
                   0.00 , 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 };

            double[] replacements = new double[] {
                    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 (int x = 0; x < Splitters.Length - 1; x++)
            {
                if (inValue >= Splitters[x] &&
                    inValue < Splitters[x + 1])
                {
                    return replacements[x];
                }
            }

            return inValue;
        }
    }
}


-- Return boolean indicating whether or not n is prime
function isPrime (n)
    if n <= 1 then return false end
    if n <= 3 then return true end
    if n % 2 == 0 or n % 3 == 0 then return false end
    local i = 5
    while i * i <= n do
        if n % i == 0 or n % (i + 2) == 0 then return false end
        i = i + 6
    end
    return true
end

-- Return table of frequencies for final digits of consecutive primes
function primeCon (limit)
    local count, x, last, ending = 2, 3, 3
    local freqList = {
        [1] = {},
        [2] = {[3] = 1},
        [3] = {},
        [5] = {},
        [7] = {},
        [9] = {}
    }
    repeat
        x = x + 2
        if isPrime(x) then
            ending = x % 10
            if freqList[last][ending] then
                freqList[last][ending] = freqList[last][ending] + 1
            else
                freqList[last][ending] = 1
            end
            last = ending
            count = count + 1
        end
    until count == limit
    return freqList
end

-- Main procedure
local limit = 10^6
local t = primeCon(limit)
for a = 1, 9 do
    for b = 1, 9 do
        if t[a] and t[a][b] then
            io.write(a .. " -> " .. b .. "\tcount: " .. t[a][b])
            print("\tfrequency: " .. t[a][b] / limit * 100 .. " %")
        end
    end
end


pragma.enable("accumulator")

def powerset(s) {
  return accum [].asSet() for k in 0..!2**s.size() {
    _.with(accum [].asSet() for i ? ((2**i & k) > 0) => elem in s {
      _.with(elem)
    })
  }
}


(define (set-cons a A)
    (make-set (cons a A)))

(define (power-set e)
    (cond ((null? e)
       (make-set (list ∅)))
    (else (let [(ps (power-set (cdr e)))]
       (make-set
       (append ps (map set-cons (circular-list (car e)) ps)))))))

(define B (make-set ' ( 🍎 🍇 🎂 🎄 )))
(power-set B)
    → { ∅ { 🍇 } { 🍇 🍎 } { 🍇 🍎 🎂 } { 🍇 🍎 🎂 🎄 } { 🍇 🍎 🎄 } { 🍇 🎂 } { 🍇 🎂 🎄 }
      { 🍇 🎄 } { 🍎 } { 🍎 🎂 } { 🍎 🎂 🎄 } { 🍎 🎄 } { 🎂 } { 🎂 🎄 } { 🎄 } }

;; The Von Neumann universe

(define V0 (power-set null)) ;; null and ∅ are the same
       → { ∅ }
(define V1 (power-set V0))
       → { ∅ { ∅ } }
(define V2 (power-set V1))
       → { ∅ { ∅ } { ∅ { ∅ } } { { ∅ } } }
(define V3 (power-set V2))
       → { ∅ { ∅ } { ∅ { ∅ } } …🔃 )
(length V3) → 16
(define V4 (power-set V3))
(length V4)  → 65536
;; length V5 = 2^65536 : out of bounds