import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

public class CyclotomicPolynomial {

    @SuppressWarnings("unused")
    private static int divisions = 0;
    private static int algorithm = 2;

    public static void main(String[] args) throws Exception {
        System.out.println("Task 1:  cyclotomic polynomials for n <= 30:");
        for ( int i = 1 ; i <= 30 ; i++ ) {
            Polynomial p = cyclotomicPolynomial(i);
            System.out.printf("CP[%d] = %s%n", i, p);
        }
        System.out.println("Task 2:  Smallest cyclotomic polynomial with n or -n as a coefficient:");
        int n = 0;
        for ( int i = 1 ; i <= 10 ; i++ ) {
            while ( true ) {
                n++;
                Polynomial cyclo = cyclotomicPolynomial(n);
                if ( cyclo.hasCoefficientAbs(i) ) {
                    System.out.printf("CP[%d] has coefficient with magnitude = %d%n", n, i);
                    n--;
                    break;
                }
            }
        }
    }

    private static final Map<Integer, Polynomial> COMPUTED = new HashMap<>();

    private static Polynomial cyclotomicPolynomial(int n) {
        if ( COMPUTED.containsKey(n) ) {
            return COMPUTED.get(n);
        }

        //System.out.println("COMPUTE:  n = " + n);

        if ( n == 1 ) {
            //  Polynomial:  x - 1
            Polynomial p = new Polynomial(1, 1, -1, 0);
            COMPUTED.put(1, p);
            return p;
        }

        Map<Integer,Integer> factors = getFactors(n);

        if ( factors.containsKey(n) ) {
            //  n prime
            List<Term> termList = new ArrayList<>();
            for ( int index = 0 ; index < n ; index++ ) {
                termList.add(new Term(1, index));
            }

            Polynomial cyclo = new Polynomial(termList);
            COMPUTED.put(n, cyclo);
            return cyclo;
        }
        else if ( factors.size() == 2 && factors.containsKey(2) && factors.get(2) == 1 && factors.containsKey(n/2) && factors.get(n/2) == 1 ) {
            //  n = 2p
            int prime = n/2;
            List<Term> termList = new ArrayList<>();
            int coeff = -1;
            for ( int index = 0 ; index < prime ; index++ ) {
                coeff *= -1;
                termList.add(new Term(coeff, index));
            }

            Polynomial cyclo = new Polynomial(termList);
            COMPUTED.put(n, cyclo);
            return cyclo;
        }
        else if ( factors.size() == 1 && factors.containsKey(2) ) {
            //  n = 2^h
            int h = factors.get(2);
            List<Term> termList = new ArrayList<>();
            termList.add(new Term(1, (int) Math.pow(2, h-1)));
            termList.add(new Term(1, 0));
            Polynomial cyclo = new Polynomial(termList);
            COMPUTED.put(n, cyclo);
            return cyclo;
        }
        else if ( factors.size() == 1 && ! factors.containsKey(n) ) {
            // n = p^k
            int p = 0;
            for ( int prime : factors.keySet() ) {
                p = prime;
            }
            int k = factors.get(p);
            List<Term> termList = new ArrayList<>();
            for ( int index = 0 ; index < p ; index++ ) {
                termList.add(new Term(1, index * (int) Math.pow(p, k-1)));
            }

            Polynomial cyclo = new Polynomial(termList);
            COMPUTED.put(n, cyclo);
            return cyclo;
        }
        else if ( factors.size() == 2 && factors.containsKey(2) ) {
            //  n = 2^h * p^k
            int p = 0;
            for ( int prime : factors.keySet() ) {
                if ( prime != 2 ) {
                    p = prime;
                }
            }
            List<Term> termList = new ArrayList<>();
            int coeff = -1;
            int twoExp = (int) Math.pow(2, factors.get(2)-1);
            int k = factors.get(p);
            for ( int index = 0 ; index < p ; index++ ) {
                coeff *= -1;
                termList.add(new Term(coeff, index * twoExp * (int) Math.pow(p, k-1)));
            }

            Polynomial cyclo = new Polynomial(termList);
            COMPUTED.put(n, cyclo);
            return cyclo;
        }
        else if ( factors.containsKey(2) && ((n/2) % 2 == 1) && (n/2) > 1 ) {
            //  CP(2m)[x] = CP(-m)[x], n odd integer > 1
            Polynomial cycloDiv2 = cyclotomicPolynomial(n/2);
            List<Term> termList = new ArrayList<>();
            for ( Term term : cycloDiv2.polynomialTerms ) {
                termList.add(term.exponent % 2 == 0 ? term : term.negate());
            }
            Polynomial cyclo = new Polynomial(termList);
            COMPUTED.put(n, cyclo);
            return cyclo;
        }

        //  General Case

        if ( algorithm == 0 ) {
            //  Slow - uses basic definition.
            List<Integer> divisors = getDivisors(n);
            //  Polynomial:  ( x^n - 1 )
            Polynomial cyclo = new Polynomial(1, n, -1, 0);
            for ( int i : divisors ) {
                Polynomial p = cyclotomicPolynomial(i);
                cyclo = cyclo.divide(p);
            }

            COMPUTED.put(n, cyclo);
            return cyclo;
        }
        else if ( algorithm == 1 ) {
            //  Faster.  Remove Max divisor (and all divisors of max divisor) - only one divide for all divisors of Max Divisor
            List<Integer> divisors = getDivisors(n);
            int maxDivisor = Integer.MIN_VALUE;
            for ( int div : divisors ) {
                maxDivisor = Math.max(maxDivisor, div);
            }
            List<Integer> divisorsExceptMax = new ArrayList<Integer>();
            for ( int div : divisors ) {
                if ( maxDivisor % div != 0 ) {
                    divisorsExceptMax.add(div);
                }
            }

            //  Polynomial:  ( x^n - 1 ) / ( x^m - 1 ), where m is the max divisor
            Polynomial cyclo = new Polynomial(1, n, -1, 0).divide(new Polynomial(1, maxDivisor, -1, 0));
            for ( int i : divisorsExceptMax ) {
                Polynomial p = cyclotomicPolynomial(i);
                cyclo = cyclo.divide(p);
            }

            COMPUTED.put(n, cyclo);

            return cyclo;
        }
        else if ( algorithm == 2 ) {
            //  Fastest
            //  Let p ; q be primes such that p does not divide n, and q q divides n.
            //  Then CP(np)[x] = CP(n)[x^p] / CP(n)[x]
            int m = 1;
            Polynomial cyclo = cyclotomicPolynomial(m);
            List<Integer> primes = new ArrayList<>(factors.keySet());
            Collections.sort(primes);
            for ( int prime : primes ) {
                //  CP(m)[x]
                Polynomial cycloM = cyclo;
                //  Compute CP(m)[x^p].
                List<Term> termList = new ArrayList<>();
                for ( Term t : cycloM.polynomialTerms ) {
                    termList.add(new Term(t.coefficient, t.exponent * prime));
                }
                cyclo = new Polynomial(termList).divide(cycloM);
                m = m * prime;
            }
            //  Now, m is the largest square free divisor of n
            int s = n / m;
            //  Compute CP(n)[x] = CP(m)[x^s]
            List<Term> termList = new ArrayList<>();
            for ( Term t : cyclo.polynomialTerms ) {
                termList.add(new Term(t.coefficient, t.exponent * s));
            }
            cyclo = new Polynomial(termList);
            COMPUTED.put(n, cyclo);

            return cyclo;
        }
        else {
            throw new RuntimeException("ERROR 103:  Invalid algorithm.");
        }
    }

    private static final List<Integer> getDivisors(int number) {
        List<Integer> divisors = new ArrayList<Integer>();
        long sqrt = (long) Math.sqrt(number);
        for ( int i = 1 ; i <= sqrt ; i++ ) {
            if ( number % i == 0 ) {
                divisors.add(i);
                int div = number / i;
                if ( div != i && div != number ) {
                    divisors.add(div);
                }
            }
        }
        return divisors;
    }

    private static final Map<Integer,Map<Integer,Integer>> allFactors = new TreeMap<Integer,Map<Integer,Integer>>();
    static {
        Map<Integer,Integer> factors = new TreeMap<Integer,Integer>();
        factors.put(2, 1);
        allFactors.put(2, factors);
    }

    public static Integer MAX_ALL_FACTORS = 100000;

    public static final Map<Integer,Integer> getFactors(Integer number) {
        if ( allFactors.containsKey(number) ) {
            return allFactors.get(number);
        }
        Map<Integer,Integer> factors = new TreeMap<Integer,Integer>();
        if ( number % 2 == 0 ) {
            Map<Integer,Integer> factorsdDivTwo = getFactors(number/2);
            factors.putAll(factorsdDivTwo);
            factors.merge(2, 1, (v1, v2) -> v1 + v2);
            if ( number < MAX_ALL_FACTORS )
                allFactors.put(number, factors);
            return factors;
        }
        boolean prime = true;
        long sqrt = (long) Math.sqrt(number);
        for ( int i = 3 ; i <= sqrt ; i += 2 ) {
            if ( number % i == 0 ) {
                prime = false;
                factors.putAll(getFactors(number/i));
                factors.merge(i, 1, (v1, v2) -> v1 + v2);
                if ( number < MAX_ALL_FACTORS )
                    allFactors.put(number, factors);
                return factors;
            }
        }
        if ( prime ) {
            factors.put(number, 1);
            if ( number < MAX_ALL_FACTORS )
                allFactors.put(number, factors);
        }
        return factors;
    }

    private static final class Polynomial {

        private List<Term> polynomialTerms;

        //  Format - coeff, exp, coeff, exp, (repeating in pairs) . . .
        public Polynomial(int ... values) {
            if ( values.length % 2 != 0 ) {
                throw new IllegalArgumentException("ERROR 102:  Polynomial constructor.  Length must be even.  Length = " + values.length);
            }
            polynomialTerms = new ArrayList<>();
            for ( int i = 0 ; i < values.length ; i += 2 ) {
                Term t = new Term(values[i], values[i+1]);
                polynomialTerms.add(t);
            }
            Collections.sort(polynomialTerms, new TermSorter());
        }

        public Polynomial() {
            //  zero
            polynomialTerms = new ArrayList<>();
            polynomialTerms.add(new Term(0,0));
        }

        private boolean hasCoefficientAbs(int coeff) {
            for ( Term term : polynomialTerms ) {
                if ( Math.abs(term.coefficient) == coeff ) {
                    return true;
                }
            }
            return false;
        }

        private Polynomial(List<Term> termList) {
            if ( termList.size() == 0 ) {
                //  zero
                termList.add(new Term(0,0));
            }
            else {
                //  Remove zero terms if needed
                for ( int i = 0 ; i < termList.size() ; i++ ) {
                    if ( termList.get(i).coefficient == 0 ) {
                        termList.remove(i);
                    }
                }
            }
            if ( termList.size() == 0 ) {
                //  zero
                termList.add(new Term(0,0));
            }
            polynomialTerms = termList;
            Collections.sort(polynomialTerms, new TermSorter());
        }

        public Polynomial divide(Polynomial v) {
            //long start = System.currentTimeMillis();
            divisions++;
            Polynomial q = new Polynomial();
            Polynomial r = this;
            long lcv = v.leadingCoefficient();
            long dv = v.degree();
            while ( r.degree() >= v.degree() ) {
                long lcr = r.leadingCoefficient();
                long s = lcr / lcv;  //  Integer division
                Term term = new Term(s, r.degree() - dv);
                q = q.add(term);
                r = r.add(v.multiply(term.negate()));
            }
            //long end = System.currentTimeMillis();
            //System.out.printf("Divide:  Elapsed = %d, Degree 1 = %d, Degree 2 = %d%n", (end-start), this.degree(), v.degree());
            return q;
        }

        public Polynomial add(Polynomial polynomial) {
            List<Term> termList = new ArrayList<>();
            int thisCount = polynomialTerms.size();
            int polyCount = polynomial.polynomialTerms.size();
            while ( thisCount > 0 || polyCount > 0 ) {
                Term thisTerm = thisCount == 0 ? null : polynomialTerms.get(thisCount-1);
                Term polyTerm = polyCount == 0 ? null : polynomial.polynomialTerms.get(polyCount-1);
                if ( thisTerm == null ) {
                    termList.add(polyTerm.clone());
                    polyCount--;
                }
                else if (polyTerm == null ) {
                    termList.add(thisTerm.clone());
                    thisCount--;
                }
                else if ( thisTerm.degree() == polyTerm.degree() ) {
                    Term t = thisTerm.add(polyTerm);
                    if ( t.coefficient != 0 ) {
                        termList.add(t);
                    }
                    thisCount--;
                    polyCount--;
                }
                else if ( thisTerm.degree() < polyTerm.degree() ) {
                    termList.add(thisTerm.clone());
                    thisCount--;
                }
                else {
                    termList.add(polyTerm.clone());
                    polyCount--;
                }
            }
            return new Polynomial(termList);
        }

        public Polynomial add(Term term) {
            List<Term> termList = new ArrayList<>();
            boolean added = false;
            for ( int index = 0 ; index < polynomialTerms.size() ; index++ ) {
                Term currentTerm = polynomialTerms.get(index);
                if ( currentTerm.exponent == term.exponent ) {
                    added = true;
                    if ( currentTerm.coefficient + term.coefficient != 0 ) {
                        termList.add(currentTerm.add(term));
                    }
                }
                else {
                    termList.add(currentTerm.clone());
                }
            }
            if ( ! added ) {
                termList.add(term.clone());
            }
            return new Polynomial(termList);
        }

        public Polynomial multiply(Term term) {
            List<Term> termList = new ArrayList<>();
            for ( int index = 0 ; index < polynomialTerms.size() ; index++ ) {
                Term currentTerm = polynomialTerms.get(index);
                termList.add(currentTerm.clone().multiply(term));
            }
            return new Polynomial(termList);
        }

        public Polynomial clone() {
            List<Term> clone = new ArrayList<>();
            for ( Term t : polynomialTerms ) {
                clone.add(new Term(t.coefficient, t.exponent));
            }
            return new Polynomial(clone);
        }

        public long leadingCoefficient() {
//            long coefficient = 0;
//            long degree = Integer.MIN_VALUE;
//            for ( Term t : polynomialTerms ) {
//                if ( t.degree() > degree ) {
//                    coefficient = t.coefficient;
//                    degree = t.degree();
//                }
//            }
            return polynomialTerms.get(0).coefficient;
        }

        public long degree() {
//            long degree = Integer.MIN_VALUE;
//            for ( Term t : polynomialTerms ) {
//                if ( t.degree() > degree ) {
//                    degree = t.degree();
//                }
//            }
            return polynomialTerms.get(0).exponent;
        }

        @Override
        public String toString() {
            StringBuilder sb = new StringBuilder();
            boolean first = true;
            for ( Term term : polynomialTerms ) {
                if ( first ) {
                    sb.append(term);
                    first = false;
                }
                else {
                    sb.append(" ");
                    if ( term.coefficient > 0 ) {
                        sb.append("+ ");
                        sb.append(term);
                    }
                    else {
                        sb.append("- ");
                        sb.append(term.negate());
                    }
                }
            }
            return sb.toString();
        }
    }

    private static final class TermSorter implements Comparator<Term> {
        @Override
        public int compare(Term o1, Term o2) {
            return (int) (o2.exponent - o1.exponent);
        }
    }

    //  Note:  Cyclotomic Polynomials have small coefficients.  Not appropriate for general polynomial usage.
    private static final class Term {
        long coefficient;
        long exponent;

        public Term(long c, long e) {
            coefficient = c;
            exponent = e;
        }

        public Term clone() {
            return new Term(coefficient, exponent);
        }

        public Term multiply(Term term) {
            return new Term(coefficient * term.coefficient, exponent + term.exponent);
        }

        public Term add(Term term) {
            if ( exponent != term.exponent ) {
                throw new RuntimeException("ERROR 102:  Exponents not equal.");
            }
            return new Term(coefficient + term.coefficient, exponent);
        }

        public Term negate() {
            return new Term(-coefficient, exponent);
        }

        public long degree() {
            return exponent;
        }

        @Override
        public String toString() {
            if ( coefficient == 0 ) {
                return "0";
            }
            if ( exponent == 0 ) {
                return "" + coefficient;
            }
            if ( coefficient == 1 ) {
                if ( exponent == 1 ) {
                    return "x";
                }
                else {
                    return "x^" + exponent;
                }
            }
            if ( exponent == 1 ) {
                return coefficient + "x";
            }
            return coefficient + "x^" + exponent;
        }
    }

}


ClearAll[Cusip]
rules = Thread[(ToString /@ Range[0, 9]) -> Range[0, 9]]~Join~
   Thread[CharacterRange["A", "Z"] -> Range[26] + 9]~Join~
   Thread[Characters["*@#"] -> {36, 37, 38}];
Cusip[cusip_String] := Module[{s = cusip, sum = 0, c, value, check},
  If[StringLength[s] != 9,
   Print["Cusip must be 9 characters!"];
   False
   ,
   s = Characters[ToUpperCase[s]];
   Do[
    c = s[[i]];
    value = c /. rules;
    If[EvenQ[i], value *= 2];
    sum += Floor[value/10] + Mod[value, 10];
    ,
    {i, 8}
    ];
   check = Mod[(10 - Mod[sum, 10]), 10];
   s[[-1]] === ToString[check]
   ]
  ]
Cusip /@ {"037833100", "17275R102", "38259P508", "594918104", "68389X106", "68389X105"}


MODULE CUSIP;
FROM FormatString IMPORT FormatString;
FROM Terminal IMPORT WriteString,WriteLn,ReadChar;

PROCEDURE WriteInt(n : INTEGER);
VAR buf : ARRAY[0..10] OF CHAR;
BEGIN
    FormatString("%i", buf, n);
    WriteString(buf)
END WriteInt;

PROCEDURE cusipCheckDigit(cusip : ARRAY OF CHAR) : INTEGER;
VAR
    i,v,sum : INTEGER;
BEGIN
    i := 0;
    sum := 0;
    WHILE cusip[i] # 0C DO
        IF ('0' <= cusip[i]) AND (cusip[i] <= '9') THEN
            v := ORD(cusip[i]) - 48 (* 0 *)
        ELSIF ('A' <= cusip[i]) AND (cusip[i] <= 'Z') THEN
            v := ORD(cusip[i]) - 65 (* A *) + 10
        ELSIF cusip[i] = '*' THEN
            v := 36
        ELSIF cusip[i] = '@' THEN
            v := 37
        ELSIF cusip[i] = '#' THEN
            v := 38
        ELSE
            RETURN -1
        END;
        IF i MOD 2 = 1 THEN v := 2 * v END;
        IF i < 8 THEN
            sum := sum + (v DIV 10) + (v MOD 10);
        END;
        INC(i)
    END;

    IF i # 9 THEN RETURN -1 END;
    RETURN (10 - (sum MOD 10)) MOD 10
END cusipCheckDigit;

PROCEDURE isValidCusip(cusip : ARRAY OF CHAR) : BOOLEAN;
VAR
    check : INTEGER;
BEGIN
    check := cusipCheckDigit(cusip);
    IF check < 0 THEN RETURN FALSE END;
    RETURN cusip[8] = CHR(48 (* 0 *) + check)
END isValidCusip;

PROCEDURE Print(cusip : ARRAY OF CHAR);
BEGIN
    WriteString(cusip);
    IF isValidCusip(cusip) THEN
        WriteString(" : Valid")
    ELSE
        WriteString(" : Invalid")
    END;
    WriteLn
END Print;

(* main *)
BEGIN
    WriteString("CUSIP       Verdict");
    WriteLn;

    Print("037833100");
    Print("17275R102");
    Print("38259P508");
    Print("594918104");
    Print("68389X106");
    Print("68389X105");

    ReadChar
END CUSIP.


cubans[m_Integer] := Block[{n = 1, result = {}, candidate},
  While[Length[result] < m,
   n++;
   candidate = n^3 - (n - 1)^3;
   If[PrimeQ[candidate], AppendTo[result, candidate]]];
  result]
cubans[200]
NumberForm[Last[cubans[100000]], NumberSeparator -> ",", DigitBlock -> 3]


import strformat
import strutils
import math

const cutOff = 200
const bigUn = 100000
const chunks = 50
const little = bigUn div chunks

echo fmt"The first {cutOff} cuban primes"
var primes: seq[int] = @[3, 5]
var c, u = 0
var showEach: bool = true
var v = 1
for i in 1..high(BiggestInt):
  var found: bool
  inc u, 6
  inc v, u
  var mx = int(ceil(sqrt(float(v))))
  for item in primes:
    if item > mx:
      break
    if v mod item == 0:
      found = true
      break
  if not found:
    inc c
    if showEach:
      for z in countup(primes[^1] + 2, v - 2, step=2):
        var fnd: bool = false
        for item in primes:
          if item > mx:
            break
          if z mod item == 0:
            fnd = true
            break
        if not fnd:
          primes.add(z)
      primes.add(v)
      write(stdout, fmt"{insertSep($v, ','):>11}")
      if c mod 10 == 0:
        write(stdout, "\n")
      if c == cutOff:
        showEach = false
        write(stdout, fmt"Progress to the {bigUn}th cuban prime: ")
        stdout.flushFile
    if c mod little == 0:
      write(stdout, ".")
      stdout.flushFile
      if c == bigUn:
        break
write(stdout, "\n")
echo fmt"The {c}th cuban prime is {insertSep($v, ',')}"


program CubanPrimes;
{$IFDEF FPC}
  {$MODE DELPHI}
  {$OPTIMIZATION ON,Regvar,PEEPHOLE,CSE,ASMCSE}
  {$CODEALIGN proc=32}
{$ENDIF}
uses
  primTrial;
const
  COLUMNCOUNT = 10*10;

procedure FormOut(Cuban:Uint64;ColSize:Uint32);
var
  s : String;
  pI,pJ :pChar;
  i,j : NativeInt;
Begin
  str(Cuban,s);
  i := length(s);
  If i>3 then
  Begin
    //extend s by the count of comma to be inserted
    j := i+ (i-1) div 3;
    setlength(s,j);
    pI := @s[i];
    pJ := @s[j];
    while i > 3 do
    Begin
       // copy 3 digits
       pJ^ := pI^;dec(pJ);dec(pI);
       pJ^ := pI^;dec(pJ);dec(pI);
       pJ^ := pI^;dec(pJ);dec(pI);
       // insert comma
       pJ^ := ',';dec(pJ);
       dec(i,3);
    end;
    //the digits in front are in the right place
  end;
  write(s:ColSize);
end;

procedure OutFirstCntCubPrimes(Cnt : Int32;ColCnt : Int32);
var
  cbDelta1,
  cbDelta2  : Uint64;
  ClCnt,ColSize : NativeInt;
Begin
  If Cnt <= 0 then
    EXIT;
  IF ColCnt <= 0 then
    ColCnt := 1;
  ColSize := COLUMNCOUNT DIV ColCnt;
  dec(ColCnt);

  ClCnt := ColCnt;
  cbDelta1 := 0;
  cbDelta2 := 1;

  repeat
    if isPrime(cbDelta2) then
    Begin
      FormOut(cbDelta2,ColSize);
      dec(Cnt);

      dec(ClCnt);
      If ClCnt < 0 then
      Begin
        Writeln;
        ClCnt := ColCnt;
      end;
    end;
    inc(cbDelta1,6);// 0,6,12,18...
    inc(cbDelta2,cbDelta1);//1,7,19,35...
  until Cnt<= 0;

  writeln;
end;

procedure OutNthCubPrime(n : Int32);
var
  cbDelta1,
  cbDelta2  : Uint64;
Begin
  If n <= 0 then
    EXIT;
  cbDelta1 := 0;
  cbDelta2 := 1;

  repeat
    inc(cbDelta1,6);
    inc(cbDelta2,cbDelta1);
    if isPrime(cbDelta2) then
      dec(n);
  until n<=0;

  FormOut(cbDelta2,20);
  writeln;
end;

Begin
  OutFirstCntCubPrimes(200,10);
  OutNthCubPrime(100000);
end.


       IDENTIFICATION DIVISION.
       PROGRAM-ID. object-address-test.
       DATA DIVISION.
       LOCAL-STORAGE SECTION.
       01 int-space.
          05 val PICTURE 9(5) VALUE 12345.
       01 addr BASED.
          05 val PICTURE 9(5) VALUE ZERO.
       01 point USAGE POINTER.
       PROCEDURE DIVISION.
         DISPLAY val OF int-space END-DISPLAY
         SET point TO ADDRESS OF int-space
         DISPLAY point END-DISPLAY
         SET ADDRESS OF addr TO point
         DISPLAY val OF addr END-DISPLAY
         MOVE 65535 TO val OF addr
         DISPLAY val OF addr END-DISPLAY
         DISPLAY val OF int-space END-DISPLAY
         STOP RUN.
       END PROGRAM object-address-test.


10 POKE 50000,(3) REM EQUIVALENT OF LDA #$03 STA 50000
20 PEEK(50000) REM READ THE VALUE AT MEMORY ADDRESS 50000


import std.stdio ;

void main() {
    int[] arr ;
    foreach(i; [0,1,2,3])
        arr ~= i*(1 << 24) + 0x417e7e7e ;

    struct X {
        char[16] msg ;
    }

    X* xPtr ;
    int* iPtr ;
    float* fPtr ;

    int adrSpace = cast(int) arr.ptr ;
    // get address of an existing object arr

    xPtr = cast(X*) adrSpace ;
    // xPtr now point to arr, as a struct X
    writefln("arr(as X)'s msg = '%s' (len %d) @ 0x%08x",
        xPtr.msg, xPtr.msg.length, xPtr) ;

    iPtr = cast(int*) (adrSpace + 1 * 4 /*bytes*/) ;
    fPtr = cast(float*) iPtr ;
    // pointers now point to arr[1]
    writefln("arr[1] = 0x%8x (%9.4f) @ 0x%08X", *iPtr, *fPtr, iPtr) ;
    iPtr = cast(int*) (adrSpace + 3 * 4 /*bytes*/) ;
    fPtr = cast(float*) iPtr ;
    // pointers now point to arr[3]
    writefln("arr[3] = 0x%8x (%9.4f) @ 0x%08X", *iPtr, *fPtr, iPtr) ;
    *fPtr = 0.5f ; // change value
    writefln("arr[3] = 0x%8x (%9.4f) @ 0x%08X", *iPtr, *fPtr, iPtr) ;
}


)abbrev package TESTD TestDomain
TestDomain(T : Join(Field,RadicalCategory)): Exports == Implementation where
  R ==> Record(n : Integer, sum : T, ssq : T)
  Exports == AbelianMonoid with
    _+ : (%,T) -> %
    _+ : (T,%) -> %
    sd : % -> T
  Implementation == R add
    Rep := R   -- similar representation and implementation
    obj : %
    0 == [0,0,0]
    obj + (obj2:%) == [obj.n + obj2.n, obj.sum + obj2.sum, obj.ssq + obj2.ssq]
    obj + (x:T) == obj + [1, x, x*x]
    (x:T) + obj == obj + x
    sd obj ==
      mean : T := obj.sum / (obj.n::T)
      sqrt(obj.ssq / (obj.n::T) - mean*mean)


      MAXITEMS = 100
      FOR i% = 1 TO 8
        READ n
        PRINT "Value = "; n ", running SD = " FNrunningsd(n)
      NEXT
      END

      DATA 2,4,4,4,5,5,7,9

      DEF FNrunningsd(n)
      PRIVATE list(), i%
      DIM list(MAXITEMS)
      i% += 1
      list(i%) = n
      = SQR(MOD(list())^2/i% - (SUM(list())/i%)^2)


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

typedef enum Action { STDDEV, MEAN, VAR, COUNT } Action;

typedef struct stat_obj_struct {
   double sum, sum2;
   size_t num;
   Action action;
} sStatObject, *StatObject;

StatObject NewStatObject( Action action )
{
  StatObject so;

  so = malloc(sizeof(sStatObject));
  so->sum = 0.0;
  so->sum2 = 0.0;
  so->num = 0;
  so->action = action;
  return so;
}
#define FREE_STAT_OBJECT(so) \
   free(so); so = NULL
double stat_obj_value(StatObject so, Action action)
{
  double num, mean, var, stddev;

  if (so->num == 0.0) return 0.0;
  num = so->num;
  if (action==COUNT) return num;
  mean = so->sum/num;
  if (action==MEAN) return mean;
  var = so->sum2/num - mean*mean;
  if (action==VAR) return var;
  stddev = sqrt(var);
  if (action==STDDEV) return stddev;
  return 0;
}

double stat_object_add(StatObject so, double v)
{
  so->num++;
  so->sum += v;
  so->sum2 += v*v;
  return stat_obj_value(so, so->action);
}


using Primes, Polynomials

# memoize cache for recursive calls
const cyclotomics = Dict([1 => Poly([big"-1", big"1"]), 2 => Poly([big"1", big"1"])])

# get all integer divisors of an integer, except itself
function divisors(n::Integer)
    f = [one(n)]
    for (p, e) in factor(n)
        f = reduce(vcat, [f * p^j for j in 1:e], init=f)
    end
    return resize!(f, length(f) - 1)
end

"""
    cyclotomic(n::Integer)

Calculate the n -th cyclotomic polynomial.
See wikipedia article at bottom of section /wiki/Cyclotomic_polynomial#Fundamental_tools
The algorithm is reliable but slow for large n > 1000.
"""
function cyclotomic(n::Integer)
    if haskey(cyclotomics, n)
        c = cyclotomics[n]
    elseif isprime(n)
        c = Poly(ones(BigInt, n))
        cyclotomics[n] = c
    else  # recursive formula seen in wikipedia article
        c = Poly([big"-1"; zeros(BigInt, n - 1); big"1"])
        for d in divisors(n)
            c ÷= cyclotomic(d)
        end
        cyclotomics[n] = c
    end
    return c
end

println("First 30 cyclotomic polynomials:")
for i in 1:30
    println(rpad("$i:  ", 5), cyclotomic(BigInt(i)))
end

const dig = zeros(BigInt, 10)
for i in 1:1000000
    if all(x -> x != 0, dig)
        break
    end
    for coef in coeffs(cyclotomic(i))
        x = abs(coef)
        if 0 < x < 11 && dig[Int(x)] == 0
            dig[Int(x)] = coef < 0 ? -i : i
        end
    end
end
for (i, n) in enumerate(dig)
    println("The cyclotomic polynomial Φ(", abs(n), ") has a coefficient that is ", n < 0 ? -i : i)
end


import java.util.TreeMap
import kotlin.math.abs
import kotlin.math.pow
import kotlin.math.sqrt

private const val algorithm = 2

fun main() {
    println("Task 1:  cyclotomic polynomials for n <= 30:")
    for (i in 1..30) {
        val p = cyclotomicPolynomial(i)
        println("CP[$i] = $p")
    }
    println()

    println("Task 2:  Smallest cyclotomic polynomial with n or -n as a coefficient:")
    var n = 0
    for (i in 1..10) {
        while (true) {
            n++
            val cyclo = cyclotomicPolynomial(n)
            if (cyclo!!.hasCoefficientAbs(i)) {
                println("CP[$n] has coefficient with magnitude = $i")
                n--
                break
            }
        }
    }
}

private val COMPUTED: MutableMap<Int, Polynomial> = HashMap()
private fun cyclotomicPolynomial(n: Int): Polynomial? {
    if (COMPUTED.containsKey(n)) {
        return COMPUTED[n]
    }
    if (n == 1) {
        //  Polynomial:  x - 1
        val p = Polynomial(1, 1, -1, 0)
        COMPUTED[1] = p
        return p
    }
    val factors = getFactors(n)
    if (factors.containsKey(n)) {
        //  n prime
        val termList: MutableList<Term> = ArrayList()
        for (index in 0 until n) {
            termList.add(Term(1, index.toLong()))
        }
        val cyclo = Polynomial(termList)
        COMPUTED[n] = cyclo
        return cyclo
    } else if (factors.size == 2 && factors.containsKey(2) && factors[2] == 1 && factors.containsKey(n / 2) && factors[n / 2] == 1) {
        //  n = 2p
        val prime = n / 2
        val termList: MutableList<Term> = ArrayList()
        var coeff = -1
        for (index in 0 until prime) {
            coeff *= -1
            termList.add(Term(coeff.toLong(), index.toLong()))
        }
        val cyclo = Polynomial(termList)
        COMPUTED[n] = cyclo
        return cyclo
    } else if (factors.size == 1 && factors.containsKey(2)) {
        //  n = 2^h
        val h = factors[2]!!
        val termList: MutableList<Term> = ArrayList()
        termList.add(Term(1, 2.0.pow((h - 1).toDouble()).toLong()))
        termList.add(Term(1, 0))
        val cyclo = Polynomial(termList)
        COMPUTED[n] = cyclo
        return cyclo
    } else if (factors.size == 1 && !factors.containsKey(n)) {
        // n = p^k
        var p = 0
        for (prime in factors.keys) {
            p = prime
        }
        val k = factors[p]!!
        val termList: MutableList<Term> = ArrayList()
        for (index in 0 until p) {
            termList.add(Term(1, (index * p.toDouble().pow(k - 1.toDouble()).toInt()).toLong()))
        }
        val cyclo = Polynomial(termList)
        COMPUTED[n] = cyclo
        return cyclo
    } else if (factors.size == 2 && factors.containsKey(2)) {
        //  n = 2^h * p^k
        var p = 0
        for (prime in factors.keys) {
            if (prime != 2) {
                p = prime
            }
        }
        val termList: MutableList<Term> = ArrayList()
        var coeff = -1
        val twoExp = 2.0.pow((factors[2]!!) - 1.toDouble()).toInt()
        val k = factors[p]!!
        for (index in 0 until p) {
            coeff *= -1
            termList.add(Term(coeff.toLong(), (index * twoExp * p.toDouble().pow(k - 1.toDouble()).toInt()).toLong()))
        }
        val cyclo = Polynomial(termList)
        COMPUTED[n] = cyclo
        return cyclo
    } else if (factors.containsKey(2) && n / 2 % 2 == 1 && n / 2 > 1) {
        //  CP(2m)[x] = CP(-m)[x], n odd integer > 1
        val cycloDiv2 = cyclotomicPolynomial(n / 2)
        val termList: MutableList<Term> = ArrayList()
        for (term in cycloDiv2!!.polynomialTerms) {
            termList.add(if (term.exponent % 2 == 0L) term else term.negate())
        }
        val cyclo = Polynomial(termList)
        COMPUTED[n] = cyclo
        return cyclo
    }

    //  General Case
    return when (algorithm) {
        0 -> {
            //  Slow - uses basic definition.
            val divisors = getDivisors(n)
            //  Polynomial:  ( x^n - 1 )
            var cyclo = Polynomial(1, n, -1, 0)
            for (i in divisors) {
                val p = cyclotomicPolynomial(i)
                cyclo = cyclo.divide(p)
            }
            COMPUTED[n] = cyclo
            cyclo
        }
        1 -> {
            //  Faster.  Remove Max divisor (and all divisors of max divisor) - only one divide for all divisors of Max Divisor
            val divisors = getDivisors(n)
            var maxDivisor = Int.MIN_VALUE
            for (div in divisors) {
                maxDivisor = maxDivisor.coerceAtLeast(div)
            }
            val divisorsExceptMax: MutableList<Int> = ArrayList()
            for (div in divisors) {
                if (maxDivisor % div != 0) {
                    divisorsExceptMax.add(div)
                }
            }

            //  Polynomial:  ( x^n - 1 ) / ( x^m - 1 ), where m is the max divisor
            var cyclo = Polynomial(1, n, -1, 0).divide(Polynomial(1, maxDivisor, -1, 0))
            for (i in divisorsExceptMax) {
                val p = cyclotomicPolynomial(i)
                cyclo = cyclo.divide(p)
            }
            COMPUTED[n] = cyclo
            cyclo
        }
        2 -> {
            //  Fastest
            //  Let p ; q be primes such that p does not divide n, and q q divides n.
            //  Then CP(np)[x] = CP(n)[x^p] / CP(n)[x]
            var m = 1
            var cyclo = cyclotomicPolynomial(m)
            val primes = factors.keys.toMutableList()
            primes.sort()
            for (prime in primes) {
                //  CP(m)[x]
                val cycloM = cyclo
                //  Compute CP(m)[x^p].
                val termList: MutableList<Term> = ArrayList()
                for (t in cycloM!!.polynomialTerms) {
                    termList.add(Term(t.coefficient, t.exponent * prime))
                }
                cyclo = Polynomial(termList).divide(cycloM)
                m *= prime
            }
            //  Now, m is the largest square free divisor of n
            val s = n / m
            //  Compute CP(n)[x] = CP(m)[x^s]
            val termList: MutableList<Term> = ArrayList()
            for (t in cyclo!!.polynomialTerms) {
                termList.add(Term(t.coefficient, t.exponent * s))
            }
            cyclo = Polynomial(termList)
            COMPUTED[n] = cyclo
            cyclo
        }
        else -> {
            throw RuntimeException("ERROR 103:  Invalid algorithm.")
        }
    }
}

private fun getDivisors(number: Int): List<Int> {
    val divisors: MutableList<Int> = ArrayList()
    val sqrt = sqrt(number.toDouble()).toLong()
    for (i in 1..sqrt) {
        if (number % i == 0L) {
            divisors.add(i.toInt())
            val div = (number / i).toInt()
            if (div.toLong() != i && div != number) {
                divisors.add(div)
            }
        }
    }
    return divisors
}

private fun crutch(): MutableMap<Int, Map<Int, Int>> {
    val allFactors: MutableMap<Int, Map<Int, Int>> = TreeMap()

    val factors: MutableMap<Int, Int> = TreeMap()
    factors[2] = 1

    allFactors[2] = factors
    return allFactors
}

private val allFactors = crutch()

var MAX_ALL_FACTORS = 100000

fun getFactors(number: Int): Map<Int, Int> {
    if (allFactors.containsKey(number)) {
        return allFactors[number]!!
    }
    val factors: MutableMap<Int, Int> = TreeMap()
    if (number % 2 == 0) {
        val factorsDivTwo = getFactors(number / 2)
        factors.putAll(factorsDivTwo)
        factors.merge(2, 1) { a: Int?, b: Int? -> Integer.sum(a!!, b!!) }
        if (number < MAX_ALL_FACTORS) allFactors[number] = factors
        return factors
    }
    val sqrt = sqrt(number.toDouble()).toLong()
    var i = 3
    while (i <= sqrt) {
        if (number % i == 0) {
            factors.putAll(getFactors(number / i))
            factors.merge(i, 1) { a: Int?, b: Int? -> Integer.sum(a!!, b!!) }
            if (number < MAX_ALL_FACTORS) {
                allFactors[number] = factors
            }
            return factors
        }
        i += 2
    }
    factors[number] = 1
    if (number < MAX_ALL_FACTORS) {
        allFactors[number] = factors
    }
    return factors
}

private class Polynomial {
    val polynomialTerms: MutableList<Term>

    //  Format - coeff, exp, coeff, exp, (repeating in pairs) . . .
    constructor(vararg values: Int) {
        require(values.size % 2 == 0) { "ERROR 102:  Polynomial constructor.  Length must be even.  Length = " + values.size }
        polynomialTerms = mutableListOf()
        var i = 0
        while (i < values.size) {
            val t = Term(values[i].toLong(), values[i + 1].toLong())
            polynomialTerms.add(t)
            i += 2
        }
        polynomialTerms.sortWith(TermSorter())
    }

    constructor() {
        //  zero
        polynomialTerms = ArrayList()
        polynomialTerms.add(Term(0, 0))
    }

    fun hasCoefficientAbs(coeff: Int): Boolean {
        for (term in polynomialTerms) {
            if (abs(term.coefficient) == coeff.toLong()) {
                return true
            }
        }
        return false
    }

    constructor(termList: MutableList<Term>) {
        if (termList.isEmpty()) {
            //  zero
            termList.add(Term(0, 0))
        } else {
            //  Remove zero terms if needed
            termList.removeIf { t -> t.coefficient == 0L }
        }
        if (termList.size == 0) {
            //  zero
            termList.add(Term(0, 0))
        }
        polynomialTerms = termList
        polynomialTerms.sortWith(TermSorter())
    }

    fun divide(v: Polynomial?): Polynomial {
        var q = Polynomial()
        var r = this
        val lcv = v!!.leadingCoefficient()
        val dv = v.degree()
        while (r.degree() >= v.degree()) {
            val lcr = r.leadingCoefficient()
            val s = lcr / lcv //  Integer division
            val term = Term(s, r.degree() - dv)
            q = q.add(term)
            r = r.add(v.multiply(term.negate()))
        }
        return q
    }

    fun add(polynomial: Polynomial): Polynomial {
        val termList: MutableList<Term> = ArrayList()
        var thisCount = polynomialTerms.size
        var polyCount = polynomial.polynomialTerms.size
        while (thisCount > 0 || polyCount > 0) {
            val thisTerm = if (thisCount == 0) null else polynomialTerms[thisCount - 1]
            val polyTerm = if (polyCount == 0) null else polynomial.polynomialTerms[polyCount - 1]
            when {
                thisTerm == null -> {
                    termList.add(polyTerm!!.clone())
                    polyCount--
                }
                polyTerm == null -> {
                    termList.add(thisTerm.clone())
                    thisCount--
                }
                thisTerm.degree() == polyTerm.degree() -> {
                    val t = thisTerm.add(polyTerm)
                    if (t.coefficient != 0L) {
                        termList.add(t)
                    }
                    thisCount--
                    polyCount--
                }
                thisTerm.degree() < polyTerm.degree() -> {
                    termList.add(thisTerm.clone())
                    thisCount--
                }
                else -> {
                    termList.add(polyTerm.clone())
                    polyCount--
                }
            }
        }
        return Polynomial(termList)
    }

    fun add(term: Term): Polynomial {
        val termList: MutableList<Term> = ArrayList()
        var added = false
        for (currentTerm in polynomialTerms) {
            if (currentTerm.exponent == term.exponent) {
                added = true
                if (currentTerm.coefficient + term.coefficient != 0L) {
                    termList.add(currentTerm.add(term))
                }
            } else {
                termList.add(currentTerm.clone())
            }
        }
        if (!added) {
            termList.add(term.clone())
        }
        return Polynomial(termList)
    }

    fun multiply(term: Term): Polynomial {
        val termList: MutableList<Term> = ArrayList()
        for (currentTerm in polynomialTerms) {
            termList.add(currentTerm.clone().multiply(term))
        }
        return Polynomial(termList)
    }

    fun leadingCoefficient(): Long {
        return polynomialTerms[0].coefficient
    }

    fun degree(): Long {
        return polynomialTerms[0].exponent
    }

    override fun toString(): String {
        val sb = StringBuilder()
        var first = true
        for (term in polynomialTerms) {
            if (first) {
                sb.append(term)
                first = false
            } else {
                sb.append(" ")
                if (term.coefficient > 0) {
                    sb.append("+ ")
                    sb.append(term)
                } else {
                    sb.append("- ")
                    sb.append(term.negate())
                }
            }
        }
        return sb.toString()
    }
}

private class TermSorter : Comparator<Term> {
    override fun compare(o1: Term, o2: Term): Int {
        return (o2.exponent - o1.exponent).toInt()
    }
}

//  Note:  Cyclotomic Polynomials have small coefficients.  Not appropriate for general polynomial usage.
private class Term(var coefficient: Long, var exponent: Long) {
    fun clone(): Term {
        return Term(coefficient, exponent)
    }

    fun multiply(term: Term): Term {
        return Term(coefficient * term.coefficient, exponent + term.exponent)
    }

    fun add(term: Term): Term {
        if (exponent != term.exponent) {
            throw RuntimeException("ERROR 102:  Exponents not equal.")
        }
        return Term(coefficient + term.coefficient, exponent)
    }

    fun negate(): Term {
        return Term(-coefficient, exponent)
    }

    fun degree(): Long {
        return exponent
    }

    override fun toString(): String {
        if (coefficient == 0L) {
            return "0"
        }
        if (exponent == 0L) {
            return "" + coefficient
        }
        if (coefficient == 1L) {
            return if (exponent == 1L) {
                "x"
            } else {
                "x^$exponent"
            }
        }
        return if (exponent == 1L) {
            coefficient.toString() + "x"
        } else coefficient.toString() + "x^" + exponent
    }
}


def cusip_checksum(cusip)
    alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    num   = "0123456789"
    sum   = 0

    for i in range(1, 8)
        c = cusip[i - 1]
        v = 0
        if c in num
            v = int(c)
        else if c in alpha
            p = alpha[c] + 1
            v = p + 9
        else if c in "*@#"
            v = "*@#"[c] + 36
        end
        if (i % 2) = 0
            v *= 2
        end

        sum += int(v / 10) + (v % 10)
    end

    return (10 - (sum % 10)) % 10
end

if main
    codes = {"037833100", "17275R102", "38259P508",\
             "594918104", "68389X106", "68389X105"}

    for code in codes
        if int(code[len(code) - 1]) = cusip_checksum(code)
            println code + " is valid"
        else
            println code + " is invalid"
        end
    end
end


import strutils

proc cusipCheck(cusip: string): bool =
  if cusip.len != 9:
    return false

  var
    sum, v = 0
  for i, c in cusip[0 .. ^2]:
    if c.isDigit:
      v = parseInt($c)
    elif c.isUpperAscii:
      v = ord(c) - ord('A') + 10
    elif c == '*':
      v = 36
    elif c == '@':
      v = 37
    elif c == '#':
      v = 38

    if i mod 2 == 1:
      v *= 2

    sum += v div 10 + v mod 10
  let check = (10 - (sum mod 10)) mod 10
  return $check == $cusip[^1]

proc main =
  let codes = [
    "037833100",
    "17275R102",
    "38259P508",
    "594918104",
    "68389X106",
    "68389X105"
  ]

  for code in codes:
    echo code, ": ", if cusipCheck(code): "Valid" else: "Invalid"

main()


class Cusip {
    function : native : IsCusip(s : String) ~ Bool {
        if(s->Size() <> 9) {
            return false;
        };

        sum := 0;
        for(i := 0; i < 7; i+=1;) {
            c := s->Get(i);

            v : Int;
            if (c >= '0' & c <= '9') {
                v := c - 48;
            } else if (c >= 'A' & c <= 'Z') {
                v := c - 55;  # lower case letters apparently invalid
            } else if (c = '*') {
                v := 36;
            } else if (c = '@') {
                v := 37;
            } else if (c = '#') {
                v := 38;
            } else {
                return false;
            };

            # check if odd as using 0-based indexing
            if(i % 2 = 1) {
                v *= 2;
            };

            sum += v / 10 + v % 10;
        };

        return s->Get(8) - 48 = (10 - (sum % 10)) % 10;
    }

    function : Main(args : String[]) ~ Nil {
        candidates := [
            "037833100",
            "17275R102",
            "38259P508",
            "594918104",
            "68389X106",
            "68389X105"
        ];

        each(i : candidates) {
            candidate := candidates[i];
            "{$candidate} => "->Print();
            if(IsCusip(candidate)) {
                "correct"->PrintLine();
            }
            else {
                "incorrect"->PrintLine();
            };
        };
    }
}


use feature 'say';
use ntheory 'is_prime';

sub cuban_primes {
    my ($n) = @_;

    my @primes;
    for (my $k = 1 ; ; ++$k) {
        my $p = 3 * $k * ($k + 1) + 1;
        if (is_prime($p)) {
            push @primes, $p;
            last if @primes >= $n;
        }
    }

    return @primes;
}

sub commify {
    scalar reverse join ',', unpack '(A3)*', reverse shift;
}

my @c = cuban_primes(200);

while (@c) {
    say join ' ', map { sprintf "%9s", commify $_ } splice(@c, 0, 10);
}

say '';
for my $n (1 .. 6) {
    say "10^$n-th cuban prime is: ", commify((cuban_primes(10**$n))[-1]);
}


with javascript_semantics
include mpfr.e
integer np = 0,
        i = 2
mpz p3 = mpz_init(1*1*1),
    i3 = mpz_init(),
    p = mpz_init(),
    pn = mpz_init()

printf(1,"The first 200 cuban primes are:\n")
sequence first200 = {}
atom t0 = time()
constant lim = iff(platform()=JS?10000:100000)
while np<lim do
    mpz_ui_pow_ui(i3,i,3)
    mpz_sub(p,i3,p3)
    if mpz_prime(p) then
        mpz_set(pn,p)
        np += 1
        if np<=200 then
            first200 = append(first200,sprintf("%,9d",mpz_get_integer(pn)))
            if mod(np,10)=0 then
                printf(1,"%s\n",join(first200[-10..-1]))
            end if
        end if
    end if
    mpz_set(p3,i3)
    i += 1
end while
printf(1,"\nThe %,dth cuban prime is %s\n",{np,mpz_get_str(pn,comma_fill:=true)})
{p3,i3,p} = mpz_free({p3,i3,p})
?elapsed(time()-t0)


program Create_an_object_at_a_given_address;

{$APPTYPE CONSOLE}

var
  origem: Integer;
  copy: Integer absolute origem;   // This is old the trick

begin
  writeln('The "origem" adress is: ', cardinal(@origem));
  writeln('The "copy" adress is: ', cardinal(@copy));
  writeln;

  origem := 10;
  writeln('Assign 10 to "origem" ');
  writeln('The value of "origem" é ', origem);
  writeln('The value of "copy" é ', copy);
  writeln;

  copy := 2;
  writeln('Assign 2 to "copy" ');

  writeln('The value of "origem" é ', origem);
  writeln('The value of "copy" é ', copy);

  Readln;

end.


$3f8 constant LPT1:

LPT1: [email protected] .
$3f LPT1: c!


' FB 1.05.0

Type Person
  As String name
  As Integer age
  Declare Constructor(name As String, age As Integer)
End Type

Constructor Person(name As String, age As Integer)
  This.name = name
  This.age = age
End Constructor

Dim ap As Any Ptr = CAllocate(SizeOf(Person)) ' allocate memory to store a Person object

'create a Person object at the address of the memory we've just allocated

Dim p As Person Ptr = New(ap) Person("Teresa", 60)

'check addresses are same
Print ap, p

'check data is not corrupt
Print p -> name, p -> age

'call implicit destructor
p -> Destructor

'free memory
Deallocate(ap)

Print
Print "Press any key to quit"
Sleep


package main

import(
	"fmt"
	"unsafe"
	"reflect"
)

func pointer() {
	fmt.Printf("Pointer:\n")

	// Create a *int and store the address of 'i' in it. To create a pointer to
	// an arbitrary memory location, use something like the following:
	//    p := (*int)(unsafe.Pointer(uintptr(0x100)))
	// And replace '0x100' with the desired address.
	var i int
	p := &i

	fmt.Printf("Before:\n\t%v: %v, %v\n", p, *p, i)

	*p = 3

	fmt.Printf("After:\n\t%v: %v, %v\n", p, *p, i)
}

func slice() {
	fmt.Printf("Slice:\n")

	var a [10]byte

	// reflect.SliceHeader is a runtime representation of the internal workings
	// of a slice. To make it point to a specific address, use something like
	// the following:
	//    h.Data = uintptr(0x100)
	// And replace '0x100' with the desired address.
	var h reflect.SliceHeader
	h.Data = uintptr(unsafe.Pointer(&a)) // The address of the first element of the underlying array.
	h.Len = len(a)
	h.Cap = len(a)

	// Create an actual slice from the SliceHeader.
	s := *(*[]byte)(unsafe.Pointer(&h))

	fmt.Printf("Before:\n\ts: %v\n\ta: %v\n", s, a)

	// Copy a string into the slice. This fills the underlying array, which in
	// this case has been manually set to 'a'.
	copy(s, "A string.")

	fmt.Printf("After:\n\ts: %v\n\ta: %v\n", s, a)
}

func main() {
	pointer()
	fmt.Println()

	slice()
}


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

namespace standardDeviation
{
    class Program
    {
        static void Main(string[] args)
        {
            List<double> nums = new List<double> { 2, 4, 4, 4, 5, 5, 7, 9 };
            for (int i = 1; i <= nums.Count; i++)
                Console.WriteLine(sdev(nums.GetRange(0, i)));
        }

        static double sdev(List<double> nums)
        {
            List<double> store = new List<double>();
            foreach (double n in nums)
                store.Add((n - nums.Average()) * (n - nums.Average()));

            return Math.Sqrt(store.Sum() / store.Count);
        }
    }
}


#include <assert.h>
#include <cmath>
#include <vector>
#include <iostream>

template<int N> struct MomentsAccumulator_
{
	std::vector<double> m_;
	MomentsAccumulator_() : m_(N + 1, 0.0) {}
	void operator()(double v)
	{
		double inc = 1.0;
		for (auto& mi : m_)
		{
			mi += inc;
			inc *= v;
		}
	}
};

double Stdev(const std::vector<double>& moments)
{
	assert(moments.size() > 2);
	assert(moments[0] > 0.0);
	const double mean = moments[1] / moments[0];
	const double meanSquare = moments[2] / moments[0];
	return sqrt(meanSquare - mean * mean);
}

int main(void)
{
	std::vector<int> data({ 2, 4, 4, 4, 5, 5, 7, 9 });
	MomentsAccumulator_<2> accum;
	for (auto d : data)
	{
		accum(d);
		std::cout << "Running stdev:  " << Stdev(accum.m_) << "\n";
	}
}


Cyclotomic[#, x] & /@ Range[30] // Column
i = 1;
n = 10;
PrintTemporary[Dynamic[{magnitudes, i}]];
magnitudes = ConstantArray[True, n];
While[Or @@ magnitudes,
 coeff = Abs[CoefficientList[Cyclotomic[i, x], x]];
 coeff = Select[coeff, Between[{1, n}]];
 coeff = DeleteDuplicates[coeff];
 If[Or @@ magnitudes[[coeff]],
  Do[
   If[magnitudes[[c]] == True,
    Print["CyclotomicPolynomial(", i,
     ") has coefficient with magnitude ", c]
    ]
   ,
   {c, coeff}
   ];
  magnitudes[[coeff]] = False;
  ];
 i++;
 ]


$cv{$_} = $i++ for '0'..'9', 'A'..'Z', '*', '@', '#';

sub cusip_check_digit {
    my @cusip = split m{}xms, shift;
    my $sum = 0;

    for $i (0..7) {
        return 'Invalid character found' unless $cusip[$i] =~ m{\A [[:digit:][:upper:]*@#] \z}xms;
        $v  = $cv{ $cusip[$i] };
        $v *= 2 if $i%2;
        $sum += int($v/10) + $v%10;
    }

    $check_digit = (10 - ($sum%10)) % 10;
    $check_digit == $cusip[8] ? '' : ' (incorrect)';
}

my %test_data = (
    '037833100' => 'Apple Incorporated',
    '17275R102' => 'Cisco Systems',
    '38259P508' => 'Google Incorporated',
    '594918104' => 'Microsoft Corporation',
    '68389X106' => 'Oracle Corporation',
    '68389X105' => 'Oracle Corporation',
);

print "$_ $test_data{$_}" . cusip_check_digit($_) . "\n" for sort keys %test_data;


sequence cch = {}

function CusipCheckDigit(string cusip)
integer s = 0, c, v
    if length(cch)=0 then
        cch = repeat(-1,256)
        for i='0' to '9' do
            cch[i] = i-'0'
        end for
        for i='A' to 'Z' do
            cch[i] = i-55
        end for
        cch['*'] = 36
        cch['@'] = 37
        cch['#'] = 38
    end if
    if length(cusip)!=9 or find('\0',cusip) then return 0 end if
    for i=1 to 8 do
        c := cusip[i]
        v := cch[c]
        if v=-1 then return 0 end if
        if remainder(i,2)=0 then
            v *= 2
        end if
        s += floor(v/10)+mod(v,10)
    end for
    return cusip[9]=mod(10-mod(s,10),10)+'0'
end function

sequence tests = {"037833100",  -- Apple Incorporated
                  "17275R102",  -- Cisco Systems
                  "38259P508",  -- Google Incorporated
                  "594918104",  -- Microsoft Corporation
                  "68389X106",  -- Oracle Corporation   (incorrect)
                  "68389X105"}  -- Oracle Corporation

for i=1 to length(tests) do
    string ti = tests[i]
    printf(1,"%s : %s\n",{ti,{"invalid","valid"}[CusipCheckDigit(ti)+1]})
end for


import datetime
import math

primes = [ 3, 5 ]

cutOff = 200

bigUn =  100_000
chunks = 50
little = bigUn / chunks

tn = " cuban prime"
print ("The first {:,}{}s:".format(cutOff, tn))

c = 0
showEach = True
u = 0
v = 1
st = datetime.datetime.now()

for i in range(1, int(math.pow(2,20))):
	found = False
	u += 6
	v += u
	mx = int(math.sqrt(v))

	for item in primes:
		if (item > mx):
			break
		if (v % item == 0):
			found = True
			break

	if (found == 0):
		c += 1
		if (showEach):
			z = primes[-1]
			while (z <= v - 2):
				z += 2

				fnd = False
				for item in primes:
					if (item > mx):
						break
					if (z % item == 0):
						fnd = True
						break

				if (not fnd):
					primes.append(z)

			primes.append(v)
			print("{:>11,}".format(v), end='')

			if (c % 10 == 0):
				print("");
			if (c == cutOff):
				showEach = False
				print ("Progress to the {:,}th {}:".format(bigUn, tn), end='')
		if (c % little == 0):
			print('.', end='')
		if (c == bigUn):
			break

print("");
print ("The {:,}th{} is {:,}".format(c, tn, v))
print("Computation time was {} seconds".format((datetime.datetime.now() - st).seconds))


#lang racket

(require math/number-theory
         racket/generator)

(define (make-cuban-prime-generator)
  (generator ()
             (let loop ((y 1) (y3 1))
               (let* ((x (+ y 1))
                      (x3 (expt x 3))
                      (p (quotient (- x3 y3) (- x y))))
                 (when (prime? p) (yield p))
                 (loop x x3)))))

(define (tabulate l (line-width 80))
  (let* ((w (add1 (string-length (argmax string-length (map ~a l)))))
         (cols (quotient line-width w)))
    (for ((n (in-range 1 (add1 (length l))))
          (i l))
      (display (~a i #:width w #:align 'right))
      (when (zero? (modulo n cols)) (newline)))))

(define (progress-report x)
  (when (zero? (modulo x 1000))
    (eprintf (if (zero? (modulo x 10000)) "|" "."))
    (flush-output (current-error-port))))

(let ((200-cuban-primes (for/list ((_ 200)
                                   (p (in-producer (make-cuban-prime-generator))))
                          p)))
  (tabulate 200-cuban-primes))

(begin0
  (for/last ((x 100000)
             (p (in-producer (make-cuban-prime-generator))))
    (progress-report x)
    p)
  (newline))


function unsafepointers()
    intspace = [42]
    address = pointer_from_objref(intspace)
    println("The address of intspace is $address")
    anotherint = unsafe_pointer_to_objref(address)
    println("intspace is $(intspace[1]), memory at $address, reference value $(anotherint[1])")
    intspace[1] = 123456
    println("Now, intspace is $(intspace[1]), memory at $address, reference value $(anotherint[1])")
    anotherint[1] = 7890
    println("Now, intspace is $(intspace[1]), memory at $(pointer_from_objref(anotherint)), reference value $(anotherint[1])")
end

unsafepointers()


// Kotlin/Native Technology Preview

import kotlinx.cinterop.*

fun main(args: Array<String>) {
    val intVar = nativeHeap.alloc<IntVar>().apply { value = 42 }
    with(intVar) { println("Value is $value, address is $rawPtr") }
    intVar.value = 52  // create new value at this address
    with(intVar) { println("Value is $value, address is $rawPtr") }
    nativeHeap.free(intVar)
}


local a = {10}
local b = a

print ("address a:"..tostring(a), "value a:"..a[1])
print ("address b:"..tostring(b), "value b:"..b[1])

b[1] = 42

print ("address a:"..tostring(a), "value a:"..a[1])
print ("address b:"..tostring(b), "value b:"..b[1])


Module CheckIt {
      structure  alfa {
            val as long
      }
      Buffer Clear Beta as alfa*2
      Print Beta(0)  ' return address
      Return Beta, 0!val:=500 ' unsigned integer 32 bit
      Print Eval(Beta, 0!val)=500
      Return Beta, 0!val:=0xFFFFFFFF
      Print Eval(Beta, 0!val)=4294967295
      Buffer Code ExecMem as byte*1024
      Offset=0
      EmbLong(0xb8, 5000) ' mov eax,5100
      EmbByteLong(0x3,0x5, Beta(0)) ' add eax, [Beta(0)]
      EmbLong(0xa3, Beta(1)) ' mov [Beta(1)], eax
      EmbByte(0x31, 0xC0) ' xor eax, eax
      Ret() ' Return
      Execute Code ExecMem, 0
      Print eval(Beta, 1!val)=4999
      Sub Ret()
            Return ExecMem, Offset:=0xC3
            Offset++
      End Sub
      Sub EmbByte()
            Return ExecMem, Offset:=Number, Offset+1:=Number
            Offset+=2
      End Sub
      Sub EmbLong()
            Return ExecMem, Offset:=Number, Offset+1:=Number as Long
            Offset+=5
      End Sub
      Sub EmbByteLong()
            Return ExecMem, Offset:=Number, Offset+1:=Number, Offset+2:=Number as Long
            Offset+=6
      End Sub
}
Checkit


type
  MyObject = object
    x: int
    y: float

var
  mem = alloc(sizeof(MyObject))
  objPtr = cast[ptr MyObject](mem)
echo "object at ", cast[int](mem), ": ", objPtr[]

objPtr[] = MyObject(x: 42, y: 3.1415)
echo "object at ", cast[int](mem), ": ", objPtr[]


program test;
type
  t8Byte =  array[0..7] of byte;
var
  I : integer;
  A : integer absolute I;
  K : t8Byte;
  L : Int64 absolute K;
begin
  I := 0;
  A := 255; writeln(I);
  I := 4711;writeln(A);

  For i in t8Byte do
  Begin
    K[i]:=i;
    write(i:3,' ');
  end;
  writeln(#8#32);
  writeln(L);
end.


(defn stateful-std-deviation[x]
  (letfn [(std-dev[x]
            (let [v (deref (find-var (symbol (str *ns* "/v"))))]
              (swap! v conj x)
              (let [m (/ (reduce + @v) (count @v))]
                (Math/sqrt (/ (reduce + (map #(* (- m %) (- m %)) @v)) (count @v))))))]
    (when (nil? (resolve 'v))
      (intern *ns* 'v (atom [])))
    (std-dev x)))


IDENTIFICATION DIVISION.
PROGRAM-ID. run-stddev.
environment division.
input-output section.
file-control.
  select input-file assign to "input.txt"
    organization is line sequential.
data division.
file section.
fd input-file.
  01  inp-record.
    03  inp-fld  pic 9(03).
working-storage section.
01  filler pic 9(01)   value 0.
  88 no-more-input     value 1.
01  ws-tb-data.
  03  ws-tb-size         pic 9(03).
  03  ws-tb-table.
    05  ws-tb-fld     pic s9(05)v9999 comp-3 occurs 0 to 100 times
        depending on ws-tb-size.
01 ws-stddev       pic s9(05)v9999 comp-3.
PROCEDURE DIVISION.
  move 0 to ws-tb-size
  open  input input-file
    read input-file
    at end
      set no-more-input to true
    end-read
    perform
      test after
    until no-more-input
      add 1 to ws-tb-size
      move inp-fld to ws-tb-fld (ws-tb-size)
      call 'stddev' using  by reference ws-tb-data
         ws-stddev
      display  'inp=' inp-fld ' stddev=' ws-stddev
      read input-file at end set no-more-input to true end-read
    end-perform
  close input-file
  stop run.
end program run-stddev.
IDENTIFICATION DIVISION.
PROGRAM-ID. stddev.
data division.
working-storage section.
01 ws-tbx             pic s9(03) comp.
01 ws-tb-work.
  03  ws-sum          pic s9(05)v9999 comp-3 value +0.
  03  ws-sumsq        pic s9(05)v9999 comp-3 value +0.
  03  ws-avg          pic s9(05)v9999 comp-3 value +0.
linkage section.
01  ws-tb-data.
  03  ws-tb-size         pic 9(03).
  03  ws-tb-table.
    05  ws-tb-fld     pic s9(05)v9999 comp-3 occurs 0 to 100 times
        depending on ws-tb-size.
01  ws-stddev       pic s9(05)v9999 comp-3.
PROCEDURE DIVISION using  ws-tb-data  ws-stddev.
    compute ws-sum = 0
    perform test before varying ws-tbx from 1 by +1 until ws-tbx > ws-tb-size
        compute ws-sum = ws-sum + ws-tb-fld (ws-tbx)
    end-perform
    compute ws-avg rounded = ws-sum / ws-tb-size
    compute ws-sumsq = 0
    perform test before varying ws-tbx from 1 by +1 until ws-tbx > ws-tb-size
        compute ws-sumsq = ws-sumsq
        + (ws-tb-fld (ws-tbx) - ws-avg) ** 2.0
    end-perform
    compute ws-stddev = ( ws-sumsq / ws-tb-size) ** 0.5
    goback.
end program stddev.


import algorithm, math, sequtils, strformat, tables

type

  Term = tuple[coeff: int; exp: Natural]
  Polynomial = seq[Term]

  # Table used to represent the list of factors of a number.
  # If, for a number "n", "k" is present in the table "f" of its factors,
  # "f[k]" contains the exponent of "k" in the prime factor decomposition.
  Factors = Table[int, int]

####################################################################################################
# Miscellaneous.

## Parity tests.
template isOdd(n: int): bool = (n and 1) != 0
template isEven(n: int): bool = (n and 1) == 0

#---------------------------------------------------------------------------------------------------

proc sort(poly: var Polynomial) {.inline.} =
  ## Sort procedure for the terms of a polynomial (high degree first).
  algorithm.sort(poly, proc(x, y: Term): int = cmp(x.exp, y.exp), Descending)

####################################################################################################
# Superscripts.

const Superscripts: array['0'..'9', string] = ["⁰", "¹", "²", "³", "⁴", "⁵", "⁶", "⁷", "⁸", "⁹"]

func superscript(n: Natural): string =
  ## Return the Unicode string to use to represent an exponent.
  if n == 1:
    return ""
  for d in $n:
    result.add(Superscripts[d])

####################################################################################################
# Term operations.

func term(coeff, exp: int): Term =
  ## Create a term.
  if exp < 0:
    raise newException(ValueError, "term exponent cannot be negative")
  (coeff, Natural exp)

#---------------------------------------------------------------------------------------------------

func `*`(a, b: Term): Term =
  ## Multiply two terms.
  (a.coeff * b.coeff, Natural a.exp + b.exp)

#---------------------------------------------------------------------------------------------------

func `+`(a, b: Term): Term =
  ## Add two terms.

  if a.exp != b.exp:
    raise newException(ValueError, "addition of terms with unequal exponents")
  (a.coeff + b.coeff, a.exp)

#---------------------------------------------------------------------------------------------------

func `-`(a: Term): Term =
  ## Return the opposite of a term.
  (-a.coeff, a.exp)

#---------------------------------------------------------------------------------------------------

func `$`(a: Term): string =
  ## Return the string representation of a term.
  if a.coeff == 0: "0"
  elif a.exp == 0: $a.coeff
  elif a.coeff == 1: 'x' & superscript(a.exp)
  elif a.coeff == -1: "-x" & superscript(a.exp)
  else: $a.coeff & 'x' & superscript(a.exp)

####################################################################################################
# Polynomial.

func polynomial(terms: varargs[Term]): Polynomial =
  ## Create a polynomial described by its terms.
  for t in terms:
    if t.coeff != 0:
      result.add(t)
  if result.len == 0:
    return @[term(0, 0)]
  sort(result)

#---------------------------------------------------------------------------------------------------

func hasCoeffAbs(poly: Polynomial; coeff: int): bool =
  ## Return true if the polynomial contains a given coefficient.
  for t in poly:
    if abs(t.coeff) == coeff:
      return true

#---------------------------------------------------------------------------------------------------

func leadingCoeff(poly: Polynomial): int {.inline.} =
  ## Return the coefficient of the term with the highest degree.
  poly[0].coeff

#---------------------------------------------------------------------------------------------------

func degree(poly: Polynomial): int {.inline.} =
  ## Return the degree of the polynomial.
  if poly.len == 0: -1
  else: poly[0].exp

#---------------------------------------------------------------------------------------------------

func `+`(poly: Polynomial; someTerm: Term): Polynomial =
  ## Add a term to a polynomial.

  var added = false
  for currTerm in poly:
    if currterm.exp == someTerm.exp:
      added = true
      if currTerm.coeff + someTerm.coeff != 0:
        result.add(currTerm + someTerm)
    else:
      result.add(currTerm)

  if not added:
    result.add(someTerm)

#---------------------------------------------------------------------------------------------------

func `+`(a, b: Polynomial): Polynomial =
  ## Add two polynomials.

  var aIndex = a.high
  var bIndex = b.high

  while aIndex >= 0 or bIndex >= 0:
    if aIndex < 0:
      result &= b[bIndex]
      dec bIndex
    elif bIndex < 0:
      result &= a[aIndex]
      dec aIndex
    else:
      let t1 = a[aIndex]
      let t2 = b[bIndex]
      if t1.exp == t2.exp:
        let t3 = t1 + t2
        if t3.coeff != 0:
          result.add(t3)
        dec aIndex
        dec bIndex
      elif t1.exp < t2.exp:
        result.add(t1)
        dec aIndex
      else:
        result.add(t2)
        dec bIndex

  sort(result)

#---------------------------------------------------------------------------------------------------

func `*`(poly: Polynomial; someTerm: Term): Polynomial =
  ## Multiply a polynomial by a term.
  for currTerm in poly:
    result.add(currTerm * someTerm)

#---------------------------------------------------------------------------------------------------

func `/`(a, b: Polynomial): Polynomial =
  ## Divide a polynomial by another polynomial.

  var a = a
  let lcb = b.leadingCoeff
  let db = b.degree
  while a.degree >= b.degree:
    let lca = a.leadingCoeff
    let s = lca div lcb
    let t = term(s, a.degree - db)
    result = result + t
    a = a + b * -t

#---------------------------------------------------------------------------------------------------

func `$`(poly: Polynomial): string =
  ## Return the string representation of a polynomial.

  for t in poly:
    if result.len == 0:
      result.add($t)
    else:
      if t.coeff > 0:
        result.add('+')
        result.add($t)
      else:
        result.add('-')
        result.add($(-t))

####################################################################################################
# Cyclotomic polynomial.

var

  # Cache of list of factors.
  factorCache: Table[int, Factors] = {2: {2: 1}.toTable}.toTable

  # Cache of cyclotomic polynomials. Initialized with 1 -> x - 1.
  polyCache: Table[int, Polynomial] = {1: polynomial(term(1, 1), term(-1, 0))}.toTable

#---------------------------------------------------------------------------------------------------

proc getFactors(n: int): Factors =
  ## Return the list of factors of a number.

  if n in factorCache:
    return factorCache[n]

  if n.isEven:
    result = getFactors(n div 2)
    result[2] = result.getOrDefault(2) + 1
    factorCache[n] = result
    return

  var i = 3
  while i * i <= n:
    if n mod i == 0:
      result = getFactors( n div i)
      result[i] = result.getOrDefault(i) + 1
      factorCache[n] = result
      return
    inc i, 2

  result[n] = 1
  factorCache[n] = result

#---------------------------------------------------------------------------------------------------

proc cycloPoly(n: int): Polynomial =
  ## Find the nth cyclotomic polynomial.

  if n in polyCache:
    return polyCache[n]

  let factors = getFactors(n)

  if n in factors:
    # n is prime.
    for i in countdown(n - 1, 0):       # Add the terms by decreasing degrees.
      result.add(term(1, i))

  elif factors.len == 2 and factors.getOrDefault(2) == 1 and factors.getOrDefault(n div 2) == 1:
    # n = 2 x prime.
    let prime = n div 2
    var coeff = -1
    for i in countdown(prime - 1, 0):   # Add the terms by decreasing degrees.
      coeff *= -1
      result.add(term(coeff, i))

  elif factors.len == 1 and 2 in factors:
    # n = 2 ^ h.
    let h = factors[2]
    result.add([term(1, 1 shl (h - 1)), term(1, 0)])

  elif factors.len == 1 and n notin factors:
    # n = prime ^ k.
    var p, k = 0
    for prime, v in factors.pairs:
      if prime > p:
        p = prime
        k = v
    for i in countdown(p - 1, 0):       # Add the terms by decreasing degrees.
      result.add(term(1, i * p^(k-1)))

  elif factors.len == 2 and 2 in factors:
    # n = 2 ^ h x prime ^ k.
    var p, k = 0
    for prime, v in factors.pairs:
      if prime != 2 and prime > p:
        p = prime
        k = v
    var coeff = -1
    let twoExp = 1 shl (factors[2] - 1)
    for i in countdown(p - 1, 0):       # Add the terms by decreasing degrees.
      coeff *= -1
      result.add(term(coeff, i * twoExp * p^(k-1)))

  elif 2 in factors and isOdd(n div 2) and n div 2 > 1:
    # CP(2m)[x] = CP(-m)[x], n odd integer > 1.
    let cycloDiv2 = cycloPoly(n div 2)
    for t in cycloDiv2:
      result.add(if t.exp.isEven: t else: -t)

  else:
    # Let p, q be primes such that p does not divide n, and q divides n.
    # Then CP(np)[x] = CP(n)[x^p] / CP(n)[x].
    var m = 1
    var cyclo = cycloPoly(m)
    let primes = sorted(toSeq(factors.keys))
    for prime in primes:
      # Compute CP(m)[x^p].
      var terms: Polynomial
      for t in cyclo:
        terms.add(term(t.coeff, t.exp * prime))
      cyclo = terms / cyclo
      m *= prime
    # Now, m is the largest square free divisor of n.
    let s = n div m
    # Compute CP(n)[x] = CP(m)[x^s].
    for t in cyclo:
      result.add(term(t.coeff, t.exp * s))

  polyCache[n] = result

#———————————————————————————————————————————————————————————————————————————————————————————————————

echo "Cyclotomic polynomials for n ⩽ 30:"
for i in 1..30:
  echo &"Φ{'(' & $i & ')':4} = {cycloPoly(i)}"

echo ""
echo "Smallest cyclotomic polynomial with n or -n as a coefficient:"
var n = 0
for i in 1..10:
  while true:
    inc n
    if cycloPoly(n).hasCoeffAbs(i):
      echo &"Φ{'(' & $n & ')':7} has coefficient with magnitude = {i}"
      dec n
      break


for(n=1,30,print(n," : ",polcyclo(n)))

contains_coeff(n, d) = p=polcyclo(n);for(k=0,poldegree(p),if(abs(polcoef(p,k))==d,return(1)));return(0)

for(d=1,10,i=1; while(contains_coeff(i,d)==0,i=i+1);print(d," : ",i))


function IsCusip(string $s) {
    if (strlen($s) != 9) return false;
    $sum = 0;
    for ($i = 0; $i <= 7; $i++) {
        $c = $s[$i];
        if (ctype_digit($c)) {
            // if character is numeric, get character's numeric value
            $v = intval($c);
        } elseif (ctype_alpha($c)) {
            // if character is alphabetic, get character's ordinal position in alphabet
            $position = ord(strtoupper($c)) - ord('A') + 1;
            $v = $position + 9;
        } elseif ($c == "*") {
            $v = 36;
        } elseif ($c == "@") {
            $v = 37;
        } elseif ($c == "#") {
            $v = 38;
        } else {
            return false;
        }
        // is this character position even?
        if ($i % 2 == 1) {
            $v *= 2;
        }
        // calculate the checksum digit
        $sum += floor($v / 10 ) + ( $v % 10 );
    }
    return ord($s[8]) - 48 == (10 - ($sum % 10)) % 10;
}

$cusips = array("037833100",
                "17275R102",
                "38259P508",
                "594918104",
                "68389X106",
                "68389X105");

foreach ($cusips as $cusip) echo $cusip . " -> " . (IsCusip($cusip) ? "valid" : "invalid") . "\n";


use Lingua::EN::Numbers;
use ntheory:from<Perl5> <:all>;

my @cubans = lazy (1..Inf).map({ ($_+1)³ - .³ }).grep: *.&is_prime;

put @cubans[^200]».&comma».fmt("%9s").rotor(10).join: "\n";

put '';

put @cubans[99_999]., # zero indexed


/*REXX program finds and displays a number of  cuban  primes  or the  Nth  cuban prime. */
numeric digits 20                                /*ensure enough decimal digits for #s. */
parse arg N .                                    /*obtain optional argument from the CL.*/
if N=='' | N==","  then N= 200                   /*Not specified?  Then use the default.*/
Nth= N<0;               N= abs(N)                /*used for finding the Nth cuban prime.*/
@.=0; @.0=1; @.2=1; @.3=1; @.4=1; @.5=1; @.6=1; @.8=1  /*ending digs that aren't cubans.*/
sw= linesize() - 1;    if sw<1  then sw= 79      /*obtain width of the terminal screen. */
w=12;              #= 1;    $= right(7, w)       /*start with first cuban prime;  count.*/
     do j=1  until #=>N;    x= (j+1)**3 - j**3   /*compute a possible cuban prime.      */
     parse var x '' -1 _;   if @._  then iterate /*check last digit for non─cuban prime.*/
            do k=1  until km*km>x;  km= k*6 + 1  /*cuban primes can't be   ÷   by  6k+1 */
            if x//km==0  then iterate j          /*Divisible?   Then not a cuban prime. */
            end   /*k*/
     #= #+1                                      /*bump the number of cuban primes found*/
     if Nth  then do;  if #==N  then do;  say commas(x);  leave j;  end /*display 1 num.*/
                                else iterate /*j*/                      /*keep searching*/
                  end                            /* [↑]  try to fit as many #s per line.*/
     cx= commas(x);  L= length(cx)               /*insert commas──►X; obtain the length.*/
     cx= right(cx, max(w, L) );   new= $  cx     /*right justify  CX; concat to new list*/
     if length(new)>sw  then do;  say $;  $= cx  /*line is too long, display #'s so far.*/
                             end                 /* [↑]  initialize the (new) next line.*/
                        else              $= new /*start with cuban # that wouldn't fit.*/
     end   /*j*/
                  if \Nth  &  $\==''  then say $ /*check for residual cuban primes in $.*/
exit                                             /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
commas: parse arg _;  do jc=length(_)-3  to 1  by -3; _=insert(',', _, jc); end;  return _


# 20210218 Perl programming solution

use strict;
use warnings;

# create an integer object

print "Here is an integer             : ", my $target = 42, "\n";

# print the machine address of the object

print "And its reference is           : ", my $targetref = \$target, "\n";

# take the address of the object and create another integer object at this address

print "Now assigns a new value to it  : ", $$targetref = 69, "\n";

#  print the value of this object to verify that it is same as one of the origin

print "Then compare with the referent : ", $target, "\n";


poke(0x80,or_bits(peek(0x80),0x40))
#ilASM{ mov al,[0x80]
        or al,0x40
        mov [0x80],al}


: (setq IntSpace 12345)          # Integer
-> 12345

: (setq Address (adr 'IntSpace)) # Encoded machine address
-> -2969166782547

: (set (adr Address) 65535)      # Set this address to a new value
-> 65535

: IntSpace                       # Show the new value
-> 65535


; Allocate a 1Mb memory area work within to avoid conflicts,
; this address could be any number but it may then fail on some systems.
*a=AllocateMemory(1024*1024)

; Write a int wit value "31415" at address +312,
; using pointer '*a' with a displacement.
PokeI(*a+312, 31415)

; Write a float with value Pi at address +316,
; by creating a new pointer '*b' for this address
*b=*a+316
PokeF(*b, #PI)

;Now test it
For i=0 To 1024000 Step 4
  n=PeekI(*a+i)
  If n
    Debug "Int at +"+Str(i)+"  = "+Str(n)
    Debug "Float at +"+Str(i)+"= "+StrF(PeekF(*a+i))
  EndIf
Next


#lang racket
(require ffi/unsafe)

(define x #"Foo")
;; Get the address of the `x' object
(printf "The address of `x' is: ~s\n" (cast x _scheme _long))
(define address (cast x _bytes _long))
(printf "The address of the bytestring it holds: ~s\n" address)
(define y (cast address _long _bytes))
(printf "Converting this back to a bytestring: ~s\n" y)
(bytes-set! y 0 71)
(printf "Changed the converted bytestring: ~s\n" y)
(printf "The original one is now: ~s\n" x)
;; But (bytes-set! x 0 71) will throw an error since `x' is immutable,
;; showing that we've really modifed the memory directly in a way that
;; the runtime doesn't like.

;; Also, the above can fail at any moment if a GC happens, since
;; Racket's GC moves objects.  So a proper way to do this is not to
;; start from an existing object, but allocate one outside of the GC's
;; reach, using raw malloc():
(define buf (malloc 4 'raw))
(make-sized-byte-string buf 4)
;; or start with a given address of something like a memory-mapped IO
;; object


use NativeCall;
use NativeCall::Types;

# bind to basic libc memory management
sub malloc(size_t) returns Pointer[uint8] is native {*};
sub memset(Pointer, uint32, size_t) is native {*};
sub free(Pointer[uint8]) is native {*};

my Pointer[uint8] $base-p = malloc(100);
memset($base-p, 0, 100);

# define object as a C struct that contains a short and an int
class SampleObject is repr('CStruct') {
    has uint16 $.foo is rw;
    has uint8  $.bar is rw;
}

# for arguments sake our object is at byte offset 64 in the
# allocated memory

my $offset-p =  $base-p.clone.add(64);
my $object-p := nativecast(Pointer[SampleObject], $offset-p);
note "creating object at address {+$object-p}";

my $struct := $object-p.deref;

$struct.foo = 41;
$struct.bar = 99;

# check we can update
$struct.foo++; # 42

# Check that we're actually updating the memory
use Test;

# look at the bytes directly to verify we've written to memory. Don't be too exact, as
# the positions may vary on different platforms depending on endianess and field alignment.

my $rec-size = nativesizeof(SampleObject);
my uint8 @bytes-written = (0 ..^ $rec-size).map(-> $i {$base-p[64 + $i]}).grep: * > 0;

# first field 'foo' (amount is small enough to fit in one byte)
is @bytes-written[0], 42, 'object first field';

# second field 'bar'
is @bytes-written[1], 99, 'object second field';

# verify that changing the origin changes the object values
memset($base-p, 1, 100); # set every byte to 1

is $struct.foo, 256 + 1, 'short updated at origin';
is $struct.bar, 1, 'byte updated at origin';

# tidy up
free($base-p);
done-testing;


class StandardDeviation
    constructor: ->
        @sum = 0
        @sumOfSquares = 0
        @values = 0
        @deviation = 0

    include: ( n ) ->
        @values += 1
        @sum += n
        @sumOfSquares += n * n
        mean = @sum / @values
        mean *= mean
        @deviation = Math.sqrt @sumOfSquares / @values - mean

dev = new StandardDeviation
values = [ 2, 4, 4, 4, 5, 5, 7, 9 ]
tmp = []

for value in values
    tmp.push value
    dev.include value
    console.log """
        Values: #{ tmp }
        Standard deviation: #{ dev.deviation }

    """


use feature 'say';
use List::Util qw(first);
use Math::Polynomial::Cyclotomic qw(cyclo_poly_iterate);

say 'First 30 cyclotomic polynomials:';
my $it = cyclo_poly_iterate(1);
say "$_: " . $it->() for 1 .. 30;

say "\nSmallest cyclotomic polynomial with n or -n as a coefficient:";
$it = cyclo_poly_iterate(1);

for (my ($n, $k) = (1, 1) ; $n <= 10 ; ++$k) {
    my $poly = $it->();
    while (my $c = first { abs($_) == $n } $poly->coeff) {
        say "CP $k has coefficient with magnitude = $n";
        $n++;
    }
}


function Get-CheckDigitCUSIP {
    [CmdletBinding()]
    [OutputType([int])]
    Param ( #  Validate input
        [Parameter(Mandatory=$true, Position=0)]
        [ValidatePattern( '^[[email protected]#*]{8}\d$' )] # @#*
        [ValidateScript({$_.Length -eq 9})]
        [string]
        $cusip
    )
    $sum = 0
    0..7 | ForEach { $c = $cusip[$_] ; $v = $null
        if ([Char]::IsDigit($c)) { $v = [char]::GetNumericValue($c) }
        if ([Char]::IsLetter($c)) { $v = [int][char]$c - [int][char]'A' +10 }
        if ($c -eq '*') { $v = 36 }
        if ($c -eq '@') { $v = 37 }
        if ($c -eq '#') { $v = 38 }
        if($_ % 2){ $v += $v }
        $sum += [int][Math]::Floor($v / 10 ) + ($v % 10)
    }
    [int]$checkDigit_calculated = ( 10 - ($sum % 10) ) % 10
    return( $checkDigit_calculated )
}

function Test-IsCUSIP {
    [CmdletBinding()]
    [OutputType([bool])]
    Param (
        [Parameter(Mandatory=$true, Position=0)]
        [ValidatePattern( '^[[email protected]#*]{8}\d$' )]
        [ValidateScript({$_.Length -eq 9})]
        [string]
        $cusip
    )
    [int]$checkDigit_told = $cusip[-1].ToString()
    $checkDigit_calculated = Get-CheckDigitCUSIP $cusip
    ($checkDigit_calculated -eq $checkDigit_told)
}

$data = @"
037833100`tApple Incorporated
17275R102`tCisco Systems
38259P508`tGoogle Incorporated
594918104`tMicrosoft Corporation
68389X106`tOracle Corporation   (incorrect)
68389X105`tOracle Corporation
"@ -split "`n"
$data |%{ Test-IsCUSIP $_.Split("`t")[0] }


load "stdlib.ring"

sum = 0
limit = 1000

see "First 200 cuban primes:" + nl

for n = 1 to limit
    pr = pow(n+1,3) - pow(n,3)
    if isprime(pr)
       sum = sum + 1
       if sum < 201
          see "" + pr + " "
       else
          exit
       ok
    ok
next

see "done..." + nl


require "openssl"

RE = /(\d)(?=(\d\d\d)+(?!\d))/ # Activesupport uses this for commatizing
cuban_primes = Enumerator.new do |y|
  (1..).each do |n|
    cand = 3*n*(n+1) + 1
    y << cand if OpenSSL::BN.new(cand).prime?
  end
end

def commatize(num)
  num.to_s.gsub(RE, "\\1,")
end

cbs = cuban_primes.take(200)
formatted = cbs.map{|cb| commatize(cb).rjust(10) }
puts formatted.each_slice(10).map(&:join)

t0 = Time.now
puts "
100_000th cuban prime is #{commatize( cuban_primes.take(100_000).last)}
which took #{(Time.now-t0).round} seconds to calculate."


use std::time::Instant;
use separator::Separatable;

const NUMBER_OF_CUBAN_PRIMES: usize = 200;
const COLUMNS: usize = 10;
const LAST_CUBAN_PRIME: usize = 100_000;

fn main() {
    println!("Calculating the first {} cuban primes and the {}th cuban prime...", NUMBER_OF_CUBAN_PRIMES, LAST_CUBAN_PRIME);
    let start = Instant::now();

    let mut i: u64 = 0;
    let mut j: u64 = 1;
    let mut index: usize = 0;
    let mut cuban_primes = Vec::new();
    let mut cuban: u64 = 0;
    while index < 100_000 {
        cuban = {j += 1; j}.pow(3) - {i += 1; i}.pow(3);
        if primal::is_prime(cuban) {
            if index < NUMBER_OF_CUBAN_PRIMES {
                cuban_primes.push(cuban);
            }
            index += 1;
        }
    }

    let elapsed = start.elapsed();
    println!("THE {} FIRST CUBAN PRIMES:", NUMBER_OF_CUBAN_PRIMES);
    cuban_primes
        .chunks(COLUMNS)
        .map(|chunk| {
            chunk.iter()
                .map(|item| {
                    print!("{}\t", item)
                })
                .for_each(drop);
            println!("");
        })
        .for_each(drop);
    println!("The {}th cuban prime number is {}", LAST_CUBAN_PRIME, cuban.separated_string());
    println!("Elapsed time: {:?}", elapsed);
}


import spire.math.SafeLong
import spire.implicits._

import scala.annotation.tailrec
import scala.collection.parallel.immutable.ParVector

object CubanPrimes {
  def main(args: Array[String]): Unit = {
    println(formatTable(cubanPrimes.take(200).toVector, 10))
    println(f"The 100,000th cuban prime is: ${getNthCubanPrime(100000).toBigInt}%,d")
  }

  def cubanPrimes: LazyList[SafeLong] = cubans.filter(isPrime)
  def cubans: LazyList[SafeLong] = LazyList.iterate(SafeLong(0))(_ + 1).map(n => (n + 1).pow(3) - n.pow(3))
  def isPrime(num: SafeLong): Boolean = (num > 1) && !(SafeLong(2) #:: LazyList.iterate(SafeLong(3)){n => n + 2}).takeWhile(n => n*n <= num).exists(num%_ == 0)

  def getNthCubanPrime(num: Int): SafeLong = {
    @tailrec
    def nHelper(rem: Int, src: LazyList[SafeLong]): SafeLong = {
      val cprimes = src.take(100000).to(ParVector).filter(isPrime)
      if(cprimes.size < rem) nHelper(rem - cprimes.size, src.drop(100000))
      else cprimes.toVector.sortWith(_<_)(rem - 1)
    }

    nHelper(num, cubans)
  }

  def formatTable(lst: Vector[SafeLong], rlen: Int): String = {
    @tailrec
    def fHelper(ac: Vector[String], src: Vector[String]): String = {
      if(src.nonEmpty) fHelper(ac :+ src.take(rlen).mkString, src.drop(rlen))
      else ac.mkString("\n")
    }

    val maxLen = lst.map(n => f"${n.toBigInt}%,d".length).max
    val formatted = lst.map(n => s"%,${maxLen + 2}d".format(n.toInt))

    fHelper(Vector[String](), formatted)
  }
}


use std::{mem,ptr};

fn main() {
    let mut data: i32;

    // Rust does not allow us to use uninitialized memory but the STL provides an `unsafe`
    // function to override this protection.
    unsafe {data = mem::uninitialized()}

    // Construct a raw pointer (perfectly safe)
    let address = &mut data as *mut _;

    unsafe {ptr::write(address, 5)}
    println!("{0:p}: {0}", &data);

    unsafe {ptr::write(address, 6)}
    println!("{0:p}: {0}", &data);

}


var first, addr = integer
based second = integer

first = 12345
location var addr = first
base second at addr

print "Value of first variable   ="; first
print "Address of first variable = "; hex$(addr)
print "Value of second variable  ="; second

end


package require critcl

# A command to 'make an integer object' and couple it to a Tcl variable
critcl::cproc linkvar {Tcl_Interp* interp char* var1} int {
    int *intPtr = (int *) ckalloc(sizeof(int));

    *intPtr = 0;
    Tcl_LinkVar(interp, var1, (void *) intPtr, TCL_LINK_INT);
    return (int) intPtr;
}

# A command to couple another Tcl variable to an 'integer object'; UNSAFE!
critcl::cproc linkagain(Tcl_Interp* interp int addr char* var2} void {
    int *intPtr = (int *) addr;

    Tcl_LinkVar(interp, var2, (void *) intPtr, TCL_LINK_INT);
}

# Conventionally, programs that use critcl structure in packages
# This is used to prevent recompilation, especially on systems like Windows
package provide machAddrDemo 1


/* create_object_at_given_address.wren */

import "./fmt" for Fmt

foreign class Integer {
    construct new(i) {}

    foreign value

    foreign value=(i)

    foreign address
}

var i = Integer.new(42)
Fmt.print("Integer object with value of:    $d allocated at address $#x.", i.value, i.address)
i.value = 42
Fmt.print("Integer object value reset to:   $d but still at address $#x.", i.value, i.address)
i.value = 43
Fmt.print("Integer object value changed to: $d but still at address $#x.", i.value, i.address)


MODULE StandardDeviation;
IMPORT StdLog, Args,Strings,Math;

PROCEDURE Mean(x: ARRAY OF REAL; n: INTEGER; OUT mean: REAL);
VAR
	i: INTEGER;
	total: REAL;
BEGIN
	total := 0.0;
	FOR i := 0 TO n - 1 DO total := total + x[i] END;
	mean := total /n
END Mean;

PROCEDURE SDeviation(x : ARRAY OF REAL;n: INTEGER): REAL;
VAR
	i: INTEGER;
	mean,sum: REAL;
BEGIN
	Mean(x,n,mean);
	sum := 0.0;
	FOR i := 0 TO n - 1 DO
		sum:= sum +  ((x[i] - mean) * (x[i] - mean));
	END;
	RETURN Math.Sqrt(sum/n);
END SDeviation;

PROCEDURE Do*;
VAR
	p: Args.Params;
	x: POINTER TO ARRAY OF REAL;
	i,done: INTEGER;
BEGIN
	Args.Get(p);
	IF p.argc > 0 THEN
		NEW(x,p.argc);
		FOR i := 0 TO p.argc - 1 DO x[i] := 0.0 END;
		FOR i  := 0 TO p.argc - 1 DO
			Strings.StringToReal(p.args[i],x[i],done);
			StdLog.Int(i + 1);StdLog.String(" :> ");StdLog.Real(SDeviation(x,i + 1));StdLog.Ln
		END
	END
END Do;
END StandardDeviation.


-- demo\rosetta\Cyclotomic_Polynomial.exw
with javascript_semantics
function degree(sequence p)
    for i=length(p) to 1 by -1 do
        if p[i]!=0 then return i end if
    end for
    return -1
end function

function poly_div(sequence n, d)
    while length(d)<length(n) do d &=0 end while
    integer dn = degree(n),
            dd = degree(d)
    if dd<0 then throw("divide by zero") end if
    sequence quot = repeat(0,dn)
    while dn>=dd do
        integer k = dn-dd
        integer qk = n[dn]/d[dd]
        quot[k+1] = qk
        sequence d2 = d[1..length(d)-k]
        for i=1 to length(d2) do
            integer mi = -i
            n[mi] -= d2[mi]*qk
        end for
        dn = degree(n)
    end while
--  return {quot,n} -- (n is now the remainder)
    if n!=repeat(0,length(n)) then ?9/0 end if
    while quot[$]=0 do quot = quot[1..$-1] end while
    return quot
end function

function poly(sequence si)
-- display helper
    string r = ""
    for t=length(si) to 1 by -1 do
        integer sit = si[t]
        if sit!=0 then
            if sit=1 and t>1 then
                r &= iff(r=""? "":" + ")
            elsif sit=-1 and t>1 then
                r &= iff(r=""?"-":" - ")
            else
                if r!="" then
                    r &= iff(sit<0?" - ":" + ")
                    sit = abs(sit)
                end if
                r &= sprintf("%d",sit)
            end if
            r &= iff(t>1?"x"&iff(t>2?sprintf("^%d",t-1):""):"")
        end if
    end for
    if r="" then r="0" end if
    return r
end function
--</Polynomial_long_division.exw>

--# memoize cache for recursive calls
constant cyclotomics = new_dict({{1,{-1,1}},{2,{1,1}}})

function cyclotomic(integer n)
--
-- Calculate the nth cyclotomic polynomial.
-- See wikipedia article at bottom of section /wiki/Cyclotomic_polynomial#Fundamental_tools
-- The algorithm is reliable but slow for large n > 1000.
--
    sequence c
    if getd_index(n,cyclotomics)!=NULL then
        c = getd(n,cyclotomics)
    else
        if is_prime(n) then
            c = repeat(1,n)
        else  -- recursive formula seen in wikipedia article
            c = -1&repeat(0,n-1)&1
            sequence f = factors(n,-1)
            for i=1 to length(f) do
                c = poly_div(c,deep_copy(cyclotomic(f[i])))
            end for
        end if
        setd(n,c,cyclotomics)
    end if
    return c
end function

for i=1 to 30 do
    sequence z = cyclotomic(i)
    string s = poly(z)
    printf(1,"cp(%2d) = %s\n",{i,s})
    if i>1 and z!=reverse(z) then ?9/0 end if -- sanity check
end for

integer found = 0, n = 1, cheat = 0
sequence fn = repeat(false,10),
         nxt = {105,385,1365,1785,2805,3135,6545,6545,10465,10465}
atom t1 = time()+1
puts(1,"\n")
while found<iff(platform()=JS?5:10) do
    sequence z = cyclotomic(n)
    for i=1 to length(z) do
        atom azi = abs(z[i])
        if azi>=1 and azi<=10 and fn[azi]=0 then
            printf(1,"cp(%d) has a coefficient with magnitude %d\n",{n,azi})
            cheat = azi -- (comment this out to prevent cheating!)
            found += 1
            fn[azi] = true
            t1 = time()+1
        end if
    end for
    if cheat then {n,cheat} = {nxt[cheat],0} else n += iff(n=1?4:10) end if
    if time()>t1 and platform()!=JS then
        printf(1,"working (%d) ...\r",n)
        t1 = time()+1
    end if
end while


#!/usr/bin/env python3

import math

def cusip_check(cusip):
    if len(cusip) != 9:
        raise ValueError('CUSIP must be 9 characters')

    cusip = cusip.upper()
    total = 0
    for i in range(8):
        c = cusip[i]
        if c.isdigit():
            v = int(c)
        elif c.isalpha():
            p = ord(c) - ord('A') + 1
            v = p + 9
        elif c == '*':
            v = 36
        elif c == '@':
            v = 37
        elif c == '#':
            v = 38

        if i % 2 != 0:
            v *= 2

        total += int(v / 10) + v % 10
    check = (10 - (total % 10)) % 10
    return str(check) == cusip[-1]

if __name__ == '__main__':
    codes = [
            '037833100',
            '17275R102',
            '38259P508',
            '594918104',
            '68389X106',
            '68389X105'
            ]
    for code in codes:
        print(f'{code} -> {cusip_check(code)}')


  [ -1 split 0 peek char 0 -
    swap 0 swap
    witheach
      [ [ dup char 0 char 9 1+ within iff
            [ char 0 - ] done
          dup char A char Z 1+ within iff
            [ char A - 10 + ] done
          dup char * = iff
            [ drop 36 ] done
          dup char @ = iff
            [ drop 37 ] done
          dup char # = iff
            [ drop 38 ] done
          $ "Unexpected character '" swap
          join $ "' in CUSIP." join fail ]
        i^ 1 & if [ 2 * ]
        10 /mod + + ]
    10 mod 10 swap - 10 mod = ]            is cusip ( $ --> b )

  [ dup echo$ cusip iff
      [ say " is correct." ]
    else [ say " is incorrect." ]
    cr ]                                   is task  ( $ -->   )

  $ "037833100 17275R102 38259P508 594918104 68389X106 68389X105"
  nest$ witheach task


func cuban_primes(n) {
    1..Inf -> lazy.map {|k| 3*k*(k+1) + 1 }\
                  .grep{ .is_prime }\
                  .first(n)
}

cuban_primes(200).slices(10).each {
    say .map { "%9s" % .commify }.join(' ')
}

say ("\n100,000th cuban prime is: ", cuban_primes(1e5).last.commify)


#lang transd

MainModule: {
    primes: Vector<ULong>([3, 5]),
    lim: 200,
    bigUn: 100000,
    chunks: 50,
    little: 0,
    c: 0,
    showEach: true,
    u: ULong(0),
    v: ULong(1),

    _start: (λ found Bool() fnd Bool() mx Int() z ULong()
        (= little (/ bigUn chunks))
        (for i in Range(1 (pow 2 20)) do
            (= found false)
            (+= u 6) (+= v u) (= mx (to-Int (sqrt v) 1))
            (for item in primes do
                (if (> item mx) break)
                (if (not (mod v item)) (= found true)
                    break))
            (if (not found)
                (+= c 1)
                (if showEach
                    (= z (get primes -1))
                    (while (< z (- v 2))
                        (+= z 2) (= fnd false)
                        (for item in primes do
                            (if (> item mx) break)
                            (if (not (mod z item)) (= fnd true)
                                break))
                        (if (not fnd) (append primes z)))
                    (append primes v)
                    (textout :width 11 :group v)
                    (if (not (mod c 10)) (textout :nl))
                    (if (== c lim) (= showEach false)
                        (textout "Progress to the " :group bigUn
                                "'th cuban prime:" ))
                )
                (if (not (mod c little)) (textout "."))
                (if (== c bigUn) break)
            )
        )
        (lout "The " :group c "'th cuban prime is " v )
    )
}


class StdDevAccumulator
  def initialize
    @n, @sum, @sum2 = 0, 0.0, 0.0
  end

  def <<(num)
    @n += 1
    @sum += num
    @sum2 += num**2
    Math.sqrt (@sum2 * @n - @sum**2) / @n**2
  end
end

sd = StdDevAccumulator.new
i = 0
[2,4,4,4,5,5,7,9].each { |n| puts "adding #{n}: stddev of #{i+=1} samples is #{sd << n}" }


import std.stdio, std.math;

struct StdDev {
    real sum = 0.0, sqSum = 0.0;
    long nvalues;

    void addNumber(in real input) pure nothrow {
        nvalues++;
        sum += input;
        sqSum += input ^^ 2;
    }

    real getStdDev() const pure nothrow {
        if (nvalues == 0)
            return 0.0;
        immutable real mean = sum / nvalues;
        return sqrt(sqSum / nvalues - mean ^^ 2);
    }
}

void main() {
    StdDev stdev;

    foreach (el; [2.0, 4, 4, 4, 5, 5, 7, 9]) {
        stdev.addNumber(el);
        writefln("%e", stdev.getStdDev());
    }
}