program cyclops;
{$IFDEF FPC}
  {$MODE DELPHI}
  {$OPTIMIZATION ON,ALL}
  {$CodeAlign proc=32,loop=1}
{$ENDIF}
//extra https://oeis.org/A136098/b136098.txt take ~37 s( TIO.RUN )
uses
  sysutils;
const
  BIGLIMIT = 10*1000*1000;

type
  //number in base 9
  tnumdgts = array[0..10] of byte;
  tpnumdgts = pByte;
  tnum9 = packed record
           nmdgts : tnumdgts;
           nmMaxDgtIdx :byte;
           nmNum  : uint32;
         end;
  tCN = record
          cnRight,
          cnLeft :  tNum9;
          cnNum  :  Uint64;
          cndigits,
          cnIdx  :  Uint32;
        end;
  tCyclopsList = array of Uint64;

  procedure InitCycNum(var cn:tCN);forward;

var
  cnMin,cnPow10Shift,cnPow9 : array[0..15] of Uint64;
  Cyclops :tCyclopsList;

function IndexToCyclops(n:Uint64):tCN;
//zero-based index
var
  dgtCnt,i,num : UInt32;
  q,p9: Uint64;
Begin
  InitCycNum(result);
  if n = 0 then
    EXIT;
  result.cnIdx := n;
  dgtCnt := 0;

  repeat
    p9 := sqr(cnPow9[dgtCnt]);
    if n < p9 then
      break;
    n -= p9;
    inc(dgtCnt)
  until dgtcnt>10;
  dec(dgtCnt);
  with result do
  Begin
    with cnRight do
    Begin
      nmMaxDgtIdx := dgtCnt;
      For i := 0 to dgtCnt do
      begin
        q := n DIV 9;
        nmdgts[i] := n-9*q;
        n := q;
      end;
      num :=0;
      For i := dgtcnt downto 0 do
        num := num*10+nmdgts[i]+1;
      nmNum:= num;
      cnNum := num;
    end;

    with cnLeft do
    Begin
      nmMaxDgtIdx := dgtCnt;
      For i := 0 to dgtCnt do
      begin
        q := n DIV 9;
        nmdgts[i] := n-9*q;
        n := q;
      end;
      num :=0;
      For i := dgtcnt downto 0 do
        num := num*10+nmdgts[i]+1;
      nmNum:= num;
      cnNum += num*cnPow10Shift[dgtCnt];
      cndigits := dgtCnt;
    end;
  end;
end;

procedure Out_Cyclops(const cl:tCyclopsList;colw,colc:NativeInt);
var
  i,n : NativeInt;
Begin
  n := High(cl);
  If n > 100 then
    n := 100;
  For i := 0 to n do
  begin
    write(cl[i]:colw);
    if (i+1) mod colc = 0 then
      writeln;
  end;
  if (i+1) mod colc <> 0 then
    writeln;
  if n< High(cl) then
    writeln(High(cl)+1,' : ',cl[High(cl)]);
end;

procedure InitCnMinPow;
//min = (0,1,11,111,1111,11111,111111,1111111,11111111,...);
var
  i,min,pow,pow9 : Uint64;
begin
  min := 0;
  pow := 100;
  pow9 := 1;
  For i :=0 to High(cnMin) do
  begin
    cnMin[i] := min;
    min := 10*min+1;
    cnPow10Shift[i] := pow;
    pow *= 10;
    cnPow9[i] := pow9;
    pow9 *= 9;
  end;
end;

procedure ClearNum9(var tn:tNum9;idx:Uint32);
begin
  fillchar(tn,SizeOf(tn),#0);
  tn.nmNum := cnMin[idx+1];
end;

Procedure InitCycNum(var cn:tCN);
Begin
  with cn do
  Begin
    cndigits := 0;
    ClearNum9(cnLeft,0);
    ClearNum9(cnRight,0);
    cnNum := 0;
    cnIdx := 0;
  end;
end;

procedure IncNum9(var tn:tNum9);
var
  idx,fac,n: Uint32;
begin
  idx := 0;
  with tn do
  Begin
    fac := 1;
    n := nmdgts[0]+1;
    inc(nmNum);
    repeat
      if n < 9 then
        break;
      inc(nmNum,fac);
      nmdgts[idx] :=0;
      inc(idx);
      fac *= 10;
      n := nmdgts[idx]+1;
    until idx > nmMaxDgtIdx;
    If idx > High(nmdgts) then
      EXIT;
    nmdgts[idx] := n;
    if nmMaxDgtIdx<Idx then
      nmMaxDgtIdx := Idx;
  end;
end;

procedure NextCycNum(var cycnum:tCN);
begin
  with cycnum do
  Begin
    if cnIdx <> 0 then
    begin
      //increment right digits
      IncNum9(cnRight);
      if cnRight.nmMaxDgtIdx > cndigits then
      Begin
        //set right digits to minimum
        ClearNum9(cnRight,cndigits);
        //increment left digits
        IncNum9(cnLeft);
        //One more digit ?
        if cnLeft.nmMaxDgtIdx > cndigits then
        Begin
          inc(cndigits);
          ClearNum9(cnLeft,cndigits);
          ClearNum9(cnRight,cndigits);
          if cndigits>High(tnumdgts) then
            cndigits := High(tnumdgts);
        end;
      end;
      cnNum := cnLeft.nmNum*cnPow10Shift[cndigits]+cnRight.nmNUm;
      inc(cnIdx);
    end
    else
    Begin
      cnNum := 101;
      cnIdx := 1;
    end;
  end;
end;

procedure MakePalinCycNum(var cycnum:tCN);
//make right to be palin of left
var
  n,dgt : Uint32;
  i,j:NativeInt;
Begin
  n := 0;
  with cycnum do
  Begin
    i := 0;
    For j := cnDigits downto 0 do
    begin
      dgt := cnLeft.nmdgts[i];
      cnRight.nmdgts[j] := dgt;
      n := 10*n+(dgt+1);
      inc(i);
    end;
    cnRight.nmNum := n;
    cnNum := cnLeft.nmNum*cnPow10Shift[cndigits]+n;
  end;
end;

procedure IncLeftCn(var cn:tCN);
Begin
  with cn do
  Begin
    //set right digits to minimum
    ClearNum9(cnRight,cndigits);
    //increment left digits
    IncNum9(cnLeft);
    //One more digit ?
    if cnLeft.nmMaxDgtIdx > cndigits then
    Begin
      inc(cndigits);
      ClearNum9(cnLeft,cndigits);
      ClearNum9(cnRight,cndigits);
      if cndigits>High(tnumdgts) then
        cndigits := High(tnumdgts);
    end;
    cnNum := cnLeft.nmNum*cnPow10Shift[cndigits]+cnRight.nmNUm;
  end;
end;

function isPalinCycNum(const cycnum:tCN):boolean;
var
  i,j:NativeInt;
Begin
  with cycnum do
  Begin
    i := cnDigits;
    j := 0;
    repeat
      result := (cnRight.nmdgts[i]=cnLeft.nmdgts[j]);
      if not(result) then
        BREAK;
      dec(i);
      inc(j);
    until i<0;
  end;
end;

function FirstCyclops(cnt:NativeInt):tCN;
var
  i: NativeInt;
begin
  setlength(Cyclops,cnt);
  i := 0;
  InitCycNum(result);
  while i < cnt do
  begin
    Cyclops[i] := result.cnNum;
    inc(i);
    NextCycNum(result);
  end;
  repeat
    NextCycNum(result);
    inc(i);
  until result.cnNum> BIGLIMIT;
end;

function isPrime(n:Uint64):boolean;
var
  p,q : Uint64;
Begin
{
  if n< 4 then
  Begin
    if n < 2 then
      EXIT(false);
    EXIT(true);
  end;
  if n = 5 then
    exit(true);}
  if (n AND 1 = 0) then
    EXIT(false);
  q := n div 3;
  if n - 3*q = 0 then
    EXIT(false);
  p := 5;
  {$CodeAlign loop=1}
  repeat
    q := n div p;
    if n-q*p = 0 then
      EXIT(false);
    p += 2;
    q := n div p;
    if n-q*p = 0 then
      EXIT(false);
    if q < p then
      break;
    p += 4;
  until false;
  EXIT(true);
end;

function FirstPrimeCyclops(cnt:NativeInt):tCN;
var
  i: NativeInt;
begin
  i := 0;
  setlength(Cyclops,cnt);
  InitCycNum(result);
  while i<cnt do
  begin
    if isPrime(result.cnNum) then
    Begin
      Cyclops[i] := result.cnNum;
      inc(i);
    end;
    NextCycNum(result);
  end;
  repeat
    if isPrime(result.cnNum) then
    begin;
      inc(i);
      if result.cnNum > BIGLIMIT then
        BREAK;
    end;
    NextCycNum(result);
  until false;
  result.cnIdx := i;
end;

function FirstBlindPrimeCyclops(cnt:NativeInt):tCN;
var
  n: Uint64;
  i: NativeInt;
  isPr:Boolean;
begin
  i := 0;
  setlength(Cyclops,cnt);
  InitCycNum(result);
  while i< cnt do
  begin
    with result do
      if isPrime(cnNum) then
      Begin
        n:= cnRight.nmNum;
        if cndigits > 0 then
          n += cnLeft.nmNum*cnPow10Shift[cndigits-1]
        else
          n += cnLeft.nmNum*10;
        if isPrime(n) then
        Begin
          Cyclops[i] := cnNum;
          inc(i);
        end;
      end;
    NextCycNum(result);
  end;
  repeat
    with result do
      if isPrime(cnNum) then
      Begin
        n:= cnRight.nmNum;
        if cndigits > 0 then
          n += cnLeft.nmNum*cnPow10Shift[cndigits-1]
        else
          n += cnLeft.nmNum*10;
        isPr:= isPrime(n);
        inc(i,Ord(isPr));
        if isPr AND (cnNum > BIGLIMIT) then
          BREAK;
      end;
    NextCycNum(result);
  until false;
  result.cnIdx := i;
end;

function FirstPalinPrimeCyclops(cnt:NativeInt):tCN;
var
  i: NativeInt;
begin
  i := 0;
  setlength(Cyclops,cnt);
  InitCycNum(result);
  while i< cnt do
  Begin
    MakePalinCycNum(result);
    with result do
      if isPrime(cnNum) then
      Begin
        Cyclops[i] := cnNum;
        inc(i);
      end;
    IncLeftCn(result);
    while Not(result.cnLeft.nmdgts[result.cnDigits]+1 in [1,3,7,9]) do
      IncLeftCn(result);
  end;

  repeat
    MakePalinCycNum(result);
    with result do
      if isPrime(cnNum) then
      begin
        inc(i);
        if cnNum >BIGLIMIT then
          break;
      end;
      IncLeftCn(result);
      while Not(result.cnLeft.nmdgts[result.cnDigits]+1 in [1,3,7,9]) do
        IncLeftCn(result);
  until false;
  result.cnIdx := i;
end;

var
  cycnum:tCN;
  T0 : Int64;
  cnt : NativeUint;
begin
  InitCnMinPow;

  cnt := 50;
  writeln('The first ',cnt,' cyclops numbers are:');
  cycnum := FirstCyclops(cnt);
  Out_Cyclops(Cyclops,5,10);
  writeln('First such number > ',BIGLIMIT,' is ',cycnum.cnNum,
         ' at zero-based index ',cycnum.cnIdx);
  writeln;

  cnt := 50;
  writeln('The first ',cnt,' prime cyclops numbers are:');
  T0 := GetTickCount64;
  cycnum := FirstPrimeCyclops(cnt);
  T0 := GetTickCOunt64-T0;
  Out_Cyclops(Cyclops,7,10);
  writeln('First such number > ',BIGLIMIT,' is ',cycnum.cnNum,
         ' at one-based index ',cycnum.cnIdx);
  writeln(cycnum.cnIdx,'.th = ',cycnum.cnNum,' in  ',T0/1000:6:3,' s');
  writeln;

  cnt := 50;
  writeln('The first ',cnt,' blind prime cyclops numbers are:');
  T0 := GetTickCount64;
  cycnum := FirstBlindPrimeCyclops(cnt);
  T0 := GetTickCOunt64-T0;
  Out_Cyclops(Cyclops,7,10);
  writeln('First such number > ',BIGLIMIT,' is ',cycnum.cnNum,
         ' at one-based index ',cycnum.cnIdx);
  writeln(cycnum.cnIdx,'.th = ',cycnum.cnNum,' in  ',T0/1000:6:3,' s');
  writeln;

  cnt := 50;
  writeln('The first ',cnt,' palindromatic prime cyclops numbers are:');
  cycnum := FirstPalinPrimeCyclops(cnt);
  Out_Cyclops(Cyclops,15,5);
  writeln('First such number > ',BIGLIMIT,' is ',cycnum.cnNum,
       ' at one-based index ',cycnum.cnIdx);
  writeln;

  cnt := 100;
  repeat
    write(cnt:17,'.th = ');
    if cnt <= 10*1000 then
    Begin
      InitCycNum(cycnum);
      repeat
        NextCycNum(cycnum);
      until cycnum.cnIdx = cnt;
      write(cycnum.cnNum);
    end;
    cycnum:= IndexToCyclops(cnt);
    writeln(' calc ',cycnum.cnNum);
    cnt *= 10;
  until cnt >1000*1000*1000*1000*1000;
end.


(let [now (.getTime (java.util.Calendar/getInstance))
      f1  (java.text.SimpleDateFormat. "yyyy-MM-dd")
      f2  (java.text.SimpleDateFormat. "EEEE, MMMM dd, yyyy")]
  (println (.format f1 now))
  (println (.format f2 now)))


       IDENTIFICATION DIVISION.
       PROGRAM-ID. Date-Format.

       DATA DIVISION.
       WORKING-STORAGE SECTION.

       01  Days-Area.
           03  Days-Data.
               05  FILLER PIC X(9) VALUE "Monday".
               05  FILLER PIC X(9) VALUE "Tuesday".
               05  FILLER PIC X(9) VALUE "Wednesday".
               05  FILLER PIC X(9) VALUE "Thursday".
               05  FILLER PIC X(9) VALUE "Friday".
               05  FILLER PIC X(9) VALUE "Saturday".
               05  FILLER PIC X(9) VALUE "Sunday".

           03  Days-Values REDEFINES Days-Data.
               05  Days-Table PIC X(9) OCCURS 7 TIMES.

       01  Months-Area.
           03  Months-Data.
               05  FILLER PIC X(9) VALUE "January".
               05  FILLER PIC X(9) VALUE "February".
               05  FILLER PIC X(9) VALUE "March".
               05  FILLER PIC X(9) VALUE "April".
               05  FILLER PIC X(9) VALUE "May".
               05  FILLER PIC X(9) VALUE "June".
               05  FILLER PIC X(9) VALUE "July".
               05  FILLER PIC X(9) VALUE "August".
               05  FILLER PIC X(9) VALUE "September".
               05  FILLER PIC X(9) VALUE "October".
               05  FILLER PIC X(9) VALUE "November".
               05  FILLER PIC X(9) VALUE "December".

           03  Months-Values REDEFINES Months-Data.
               05  Months-Table PIC X(9) OCCURS 12 TIMES.

       01  Current-Date-Str.
           03  Current-Year     PIC X(4).
           03  Current-Month    PIC X(2).
           03  Current-Day      PIC X(2).

       01  Current-Day-Of-Week  PIC 9.

       PROCEDURE DIVISION.
           MOVE FUNCTION CURRENT-DATE (1:8) TO Current-Date-Str

           DISPLAY Current-Year "-" Current-Month "-" Current-Day

           ACCEPT Current-Day-Of-Week FROM DAY-OF-WEEK
           DISPLAY
               FUNCTION TRIM(
                   Days-Table (FUNCTION NUMVAL(Current-Day-Of-Week)))
               ", "
               FUNCTION TRIM(
                   Months-Table (FUNCTION NUMVAL(Current-Month)))
               " "
               Current-Day
               ", "
               Current-Year
           END-DISPLAY

           GOBACK
           .


table ← >⟨ 0‿3‿1‿7‿5‿9‿8‿6‿4‿2
           7‿0‿9‿2‿1‿5‿4‿8‿6‿3
           4‿2‿0‿6‿8‿7‿1‿3‿5‿9
           1‿7‿5‿0‿9‿8‿3‿4‿2‿6
           6‿1‿2‿3‿0‿4‿5‿9‿7‿8
           3‿6‿7‿4‿2‿0‿9‿5‿8‿1
           5‿8‿6‿9‿7‿2‿0‿1‿3‿4
           8‿9‿4‿5‿3‿6‿2‿0‿1‿7
           9‿4‿3‿8‿6‿1‿7‿2‿0‿5
           2‿5‿8‿1‿4‿3‿6‿7‿9‿0 ⟩

Digits ← 10{⌽𝕗|⌊∘÷⟜𝕗⍟(↕1+·⌊𝕗⋆⁼1⌈⊢)}

Damm ← {0=0(table⊑˜⋈)˜´⌽Digits 𝕩}

Damm¨5724‿5727‿112946


use strict;
use warnings;
use feature 'say';
use ntheory 'is_prime';
use List::AllUtils 'firstidx';

sub comma { reverse ((reverse shift) =~ s/(.{3})/$1,/gr) =~ s/^,//r }

my @cyclops = 0;
for my $exp (0..3) {
    my @oom = grep { ! /0/ } 10**$exp .. 10**($exp+1)-1;
    for my $l (@oom) {
        for my $r (@oom) {
            push @cyclops, $l . '0' . $r;
        }
    }
}

my @prime_cyclops = grep { is_prime $_           } @cyclops;
my @prime_blind   = grep { is_prime $_ =~ s/0//r } @prime_cyclops;
my @prime_palindr = grep { $_ eq reverse $_      } @prime_cyclops;

my $upto = 50;
my $over = 10_000_000;

for (
  ['', @cyclops],
  ['prime', @prime_cyclops],
  ['blind prime', @prime_blind],
  ['palindromic prime', @prime_palindr]) {
    my($text,@values) = @$_;
    my $i = firstidx { $_ > $over } @values;
    say "First $upto $text cyclops numbers:\n" .
        (sprintf "@{['%8d' x $upto]}", @values[0..$upto-1]) =~ s/(.{80})/$1\n/gr;
    printf "First $text number > %s: %s at (zero based) index: %s\n\n", map { comma($_) } $over, $values[$i], $i;
}


date = new Date

console.log date.toLocaleDateString 'en-GB',
    month:  '2-digit'
    day:    '2-digit'
    year:   'numeric'
.split('/').reverse().join '-'

console.log date.toLocaleDateString 'en-US',
    weekday: 'long'
    month:   'long'
    day:  'numeric'
    year: 'numeric'


<cfoutput>
    #dateFormat(Now(), "YYYY-MM-DD")#<br />
    #dateFormat(Now(), "DDDD, MMMM DD, YYYY")#
</cfoutput>


with javascript_semantics
atom t0 = time()
function bump(sequence half)
    -- add a digit to valid halves
    -- eg {0} --> {1..9} (no zeroes)
    --        --> {11..99} ("")
    --        --> {111..999}, etc
    sequence res = {}
    for i=1 to length(half) do
        integer hi = half[i]*10
        for digit=1 to 9 do
            res &= hi+digit
        end for
    end for
    return res
end function

procedure cyclops(string s="")
    sequence res = {},
             half = {0} -- valid digits, see bump()
    integer left = 1,   -- half[] before the 0
            right = 0,  -- half[] after the 0
            hlen = 1,   -- length(half)
            cpow = 10,  -- cyclops power (of 10)
            bcpow = 1,  -- blind cyclops power
            cn = 0      -- cyclops number (scratch)
    bool valid = false,
         bPrime = match("prime",s),
         bBlind = match("blind",s),
         bPalin = match("palindromic",s)
    while length(res)<50 or cn<=1e7 or not valid do
        right += 1
        if right>hlen then
            right = 1
            left += 1
            if left>hlen then
                half = bump(half)
                hlen = length(half)
                cpow *= 10
                bcpow *= 10
                left = 1
            end if
        end if
        integer lh = half[left],
                rh = half[right]
        cn = lh*cpow+rh -- cyclops number
        valid = not bPrime or is_prime(cn)
        if valid and bBlind then
            valid = is_prime(lh*bcpow+rh)
        end if
        if valid and bPalin then
            valid = sprintf("%d",lh) == reverse(sprintf("%d",rh))
        end if
        if valid then
            res = append(res,sprintf("%7d",cn))
        end if
    end while
    printf(1,"First 50 %scyclops numbers:\n%s\n",{s,join_by(res[1..50],1,10)})
    printf(1,"First %scyclops number > 10,000,000: %s at (one based) index: %d\n\n",
             {s,res[$],length(res)})
end procedure

cyclops()
cyclops("prime ")
cyclops("blind prime ")
cyclops("palindromic prime ")
?elapsed(time()-t0)


(defconstant *day-names*
    #("Monday" "Tuesday" "Wednesday" "Thursday" "Friday" "Saturday" "Sunday"))
(defconstant *month-names*
    #(nil "January" "February" "March" "April" "May" "June" "July"
      "August" "September" "October" "November" "December"))

(multiple-value-bind (sec min hour date month year day daylight-p zone) (get-decoded-time)
    (format t "~4d-~2,'0d-~2,'0d~%" year month date)
    (format t "~a, ~a ~d, ~4d~%"
        (aref *day-names* day) (aref *month-names* month) date year))


MODULE DateFormat;
IMPORT StdLog, Dates;

PROCEDURE Do*;
VAR
	d: Dates.Date;
	resp: ARRAY 64 OF CHAR;
BEGIN
	Dates.GetDate(d);
	Dates.DateToString(d,Dates.short,resp);
	StdLog.String(":> " + resp);StdLog.Ln;
	Dates.DateToString(d,Dates.abbreviated,resp);
	StdLog.String(":> " + resp);StdLog.Ln;
	Dates.DateToString(d,Dates.long,resp);
	StdLog.String(":> " + resp);StdLog.Ln;
	Dates.DateToString(d,Dates.plainAbbreviated,resp);
	StdLog.String(":> " + resp);StdLog.Ln;
	Dates.DateToString(d,Dates.plainLong,resp);
	StdLog.String(":> " + resp);StdLog.Ln;
END Do;
END DateFormat.


use Lingua::EN::Numbers;

my @cyclops = 0, |flat lazy ^∞ .map: -> $exp {
      my @oom = (exp($exp, 10) ..^ exp($exp + 1, 10)).grep: { !.contains: 0 }
      |@oom.hyper.map: { $_ ~ 0 «~« @oom }
}

my @prime-cyclops = @cyclops.grep: { .is-prime };

for '',                   @cyclops,
    'prime ',             @prime-cyclops,
    'blind prime ',       @prime-cyclops.grep( { .trans('0' => '').is-prime } ),
    'palindromic prime ', @prime-cyclops.grep( { $_ eq .flip } )
  -> $type, $iterator {
    say "\n\nFirst 50 {$type}cyclops numbers:\n" ~ $iterator[^50].batch(10)».fmt("%7d").join("\n") ~
        "\n\nFirst {$type}cyclops number > 10,000,000: " ~ comma($iterator.first: * > 1e7 ) ~
        " - at (zero based) index: " ~ comma $iterator.first: * > 1e7, :k;
}


/*REXX pgm finds 1st N cyclops (Θ) #s,  Θ primes,  blind Θ primes,  palindromic Θ primes*/
parse arg n cols .                               /*obtain optional argument from the CL.*/
if    n=='' |    n==","  then    n=   50         /*Not specified?  Then use the default.*/
if cols=='' | cols==","  then cols=   10         /* "      "         "   "   "     "    */
call genP                                        /*build array of semaphores for primes.*/
w= max(10, length( commas(@.#) ) )               /*max width of a number in any column. */
pri?= 0; bli?= 0; pal?= 0; call 0 ' first ' commas(n)                   " cyclops numbers"
pri?= 1; bli?= 0; pal?= 0; call 0 ' first ' commas(n)             " prime cyclops numbers"
pri?= 1; bli?= 1; pal?= 0; call 0 ' first ' commas(n)       " blind prime cyclops numbers"
pri?= 1; bli?= 0; pal?= 1; call 0 ' first ' commas(n) " palindromic prime cyclops numbers"
exit 0                                           /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
commas: parse arg ?;  do jc=length(?)-3  to 1  by -3; ?=insert(',', ?, jc); end;  return ?
/*──────────────────────────────────────────────────────────────────────────────────────*/
0: parse arg title;                idx= 1        /*get the title of this output section.*/
   say ' index │'center(title,   1 + cols*(w+1)     )      /*display the output title.  */
   say '───────┼'center(""   ,   1 + cols*(w+1), '─')      /*   "     "     "  separator*/
                   finds= 0;                 $=  /*the number of finds (so far); $ list.*/
     do j=0  until finds== n;      L= length(j)  /*find N cyclops numbers, start at 101.*/
     if L//2==0  then do;    j= left(1, L+1, 0)  /*Is J an even # of digits? Yes, bump J*/
                                        iterate  /*use a new J that has odd # of digits.*/
                      end
     z= pos(0, j);  if z\==(L+1)%2 then iterate  /* "  "    "    " (zero in mid)?    "  */
     if pos(0, j, z+1)>0           then iterate  /* "  "    "    " (has two 0's)?    "  */
     if pri?  then if \!.j         then iterate  /*Need a cyclops prime?      Then skip.*/
     if bli?  then do;   ?= space(translate(j, , 0), 0)   /*Need a blind cyclops prime ?*/
                         if \!.?   then iterate  /*Not a blind cyclops prime? Then skip.*/
                   end
     if pal?  then do;   r= reverse(j)           /*Need a palindromic cyclops prime?    */
                         if r\==j  then iterate  /*Cyclops number not palindromic? Skip.*/
                         if \!.r   then iterate  /*   "    palindrome not prime?     "  */
                   end
     finds= finds + 1                            /*bump the number of palindromic primes*/
     $= $ right( commas(j), w)                   /*add a palindromic prime ──►  $  list.*/
     if finds//cols\==0            then iterate  /*have we populated a line of output?  */
     say center(idx, 7)'│'  substr($, 2);    $=  /*display what we have so far  (cols). */
     idx= idx + cols                             /*bump the  index  count for the output*/
     end   /*j*/
   if $\==''  then say center(idx, 7)"│"  substr($, 2)  /*possible show residual output.*/
   say '───────┴'center(""  ,   1 + cols*(w+1), '─');  say
   return
/*──────────────────────────────────────────────────────────────────────────────────────*/
genP: !.= 0;  hip= 7890987 - 1                   /*placeholders for primes (semaphores).*/
      @.1=2; @.2=3; @.3=5; @.4=7; @.5=11; @.6=13 /*define some low primes.              */
      !.2=1; !.3=1; !.5=1; !.7=1; !.11=1; !.13=1 /*   "     "   "    "     flags.       */
                        #= 6;     sq.#= @.# ** 2 /*number of primes so far; prime square*/
        do [email protected].#+2  by 2  for max(0, hip%[email protected].#%2-1)     /*find odd primes from here on. */
        parse var   j   ''  -1  _                       /*get the last dec. digit of  J.*/
        if     _==5  then iterate;  if j// 3==0  then iterate  /*÷ by 5?  ÷ by 3?  Skip.*/
        if j// 7==0  then iterate;  if j//11==0  then iterate  /*÷  " 7?  ÷ by 11?   "  */
               do k=6  while sq.k<=j             /* [↓]  divide by the known odd primes.*/
               if j // @.k == 0  then iterate j  /*Is  J ÷ X?  Then not prime.     ___  */
               end   /*k*/                       /* [↑]  only process numbers  ≤  √ J   */
        #= #+1;    @.#= j;   sq.#= j*j;   !.j= 1 /*bump # Ps;  assign next P;  P sq; P# */
        end          /*j*/;               return


require "time"

time = Time.local
puts time.to_s("%Y-%m-%d")
puts time.to_s("%A, %B %d, %Y")


module datetimedemo ;

import tango.time.Time ;
import tango.text.locale.Locale ;
import tango.time.chrono.Gregorian ;

import tango.io.Stdout ;

void main() {
    Gregorian g = new Gregorian ;
    Stdout.layout = new Locale; // enable Stdout to handle date/time format
    Time d = g.toTime(2007, 11, 10, 0, 0, 0, 0, g.AD_ERA) ;
    Stdout.format("{:yyy-MM-dd}", d).newline ;
    Stdout.format("{:dddd, MMMM d, yyy}", d).newline ;
    d = g.toTime(2008, 2, 1, 0, 0, 0, 0, g.AD_ERA) ;
    Stdout.format("{:dddd, MMMM d, yyy}", d).newline ;
}


require 'prime'

NONZEROS = %w(1 2 3 4 5 6 7 8 9)

cyclopes = Enumerator.new do |y|
  (0..).each do |n|
    NONZEROS.repeated_permutation(n) do |lside|
      NONZEROS.repeated_permutation(n) do |rside|
        y << (lside.join + "0" + rside.join).to_i
      end
    end
  end
end

prime_cyclopes             = Enumerator.new {|y| cyclopes.each {|c| y << c if c.prime?} }
blind_prime_cyclopes       = Enumerator.new {|y| prime_cyclopes.each {|c| y << c if c.to_s.delete("0").to_i.prime?} }
palindromic_prime_cyclopes = Enumerator.new {|y| prime_cyclopes.each {|c| y << c if c.to_s == c.to_s.reverse} }

n, m = 50, 10_000_000
["cyclopes", "prime cyclopes", "blind prime cyclopes", "palindromic prime cyclopes"].zip(
[cyclopes, prime_cyclopes, blind_prime_cyclopes, palindromic_prime_cyclopes]).each do |name, enum|
  cycl, idx = enum.each_with_index.detect{|n, i| n > m}
  puts "The first #{n} #{name} are: \n#{enum.take(n).to_a}\nFirst #{name} term > #{m}: #{cycl} at index: #{idx}.", ""
end


func cyclops_numbers(base = 10) {
    Enumerator({|callback|

        var digits = @(1 .. base-1)

        for k in (0 .. Inf `by` 2) {
            digits.variations_with_repetition(k, {|*a|
                a = (a.first(a.len>>1) + [0] + a.last(a.len>>1))
                callback(a.flip.digits2num(base))
            })
        }
    })
}

func palindromic_cyclops_numbers(base = 10) {
    Enumerator({|callback|

        var digits = @(1 .. base-1)

        for k in (0..Inf) {
            digits.variations_with_repetition(k, {|*a|
                a = (a + [0] + a.flip)
                callback(a.flip.digits2num(base))
            })
        }
    })
}

func prime_cyclops(base = 10) {
    var iter = cyclops_numbers(base)
    Enumerator({|callback|
        iter.each {|n|
            callback(n) if n.is_prime
        }
    })
}

func blind_prime_cyclops(base = 10) {
    var iter = prime_cyclops(base)
    Enumerator({|callback|
        iter.each {|n|
            var k = (n.len(base)-1)>>1
            var r = ipow(base, k)
            if (r*idiv(n, r*base) + n%r -> is_prime) {
                callback(n)
            }
        }
    })
}

func palindromic_prime_cyclops(base = 10) {
    var iter = palindromic_cyclops_numbers(base)
    Enumerator({|callback|
        iter.each {|n|
            callback(n) if n.is_prime
        }
    })
}

for text,f in ([
    ['', cyclops_numbers],
    ['prime', prime_cyclops],
    ['blind prime', blind_prime_cyclops],
    ['palindromic prime', palindromic_prime_cyclops],
]) {

    with (50) {|k|
        say "First #{k} #{text} cyclops numbers:"
        f().first(k).each_slice(10, {|*a|
            a.map { '%7s' % _ }.join(' ').say
        })
    }

    var min = 10_000_000
    var iter = f()
    var index = 0
    var arr = Enumerator({|callback|
        iter.each {|n|
            callback([index, n]) if (n > min)
            ++index
        }
    }).first(1)[0]
    say "\nFirst #{text} term > #{min.commify}: #{arr[1].commify} at (zero based) index: #{arr[0].commify}\n"
}


ShowMessage(FormatDateTime('yyyy-mm-dd', Now) +#13#10+ FormatDateTime('dddd, mmmm dd, yyyy', Now));


me_lang(en)_cal(gregorian);
me_msg()_now()_format(yyyy-mm-dd);
me_msg()_now()_format(eeee, mmmm dd, yyyy);


// 2012-09-26
SysLib.writeStdout(StrLib.formatDate(DateTimeLib.currentDate(), "yyyy-MM-dd"));
// Wednesday, September 26, 2012
SysLib.setLocale("en", "US");
SysLib.writeStdout(StrLib.formatDate(DateTimeLib.currentDate(), "EEEE, MMMM dd, yyyy"));


% Verify that the Damm check digit of a string of digits is correct.
% Signals 'bad_format' if the string contains non-digits.
damm = proc (s: string) returns (bool) signals (bad_format)
    ai = array[int]
    aai = array[ai]
    own damm_table: aai := aai$[0:
        ai$[0: 0,3,1,7,5,9,8,6,4,2],
        ai$[0: 7,0,9,2,1,5,4,8,6,3],
        ai$[0: 4,2,0,6,8,7,1,3,5,9],
        ai$[0: 1,7,5,0,9,8,3,4,2,6],
        ai$[0: 6,1,2,3,0,4,5,9,7,8],
        ai$[0: 3,6,7,4,2,0,9,5,8,1],
        ai$[0: 5,8,6,9,7,2,0,1,3,4],
        ai$[0: 8,9,4,5,3,6,2,0,1,7],
        ai$[0: 9,4,3,8,6,1,7,2,0,5],
        ai$[0: 2,5,8,1,4,3,6,7,9,0]
    ]

    interim: int := 0
    for c: char in string$chars(s) do
        d: int := int$parse(string$c2s(c)) resignal bad_format
        interim := damm_table[interim][d]
    end

    return(interim = 0)
end damm

% Checks
start_up = proc ()
    po: stream := stream$primary_output()
    tests: sequence[string] := sequence[string]$[
        "5724", "5727", "112946", "112949"
    ]

    for test: string in sequence[string]$elements(tests) do
        stream$puts(po, test || ": ")
        if damm(test) then
            stream$putl(po, "pass")
        else
            stream$putl(po, "fail")
        end
    end
end start_up


import "/math" for Int
import "/seq" for Lst
import "/fmt" for Fmt
import "/str" for Str

var findFirst = Fn.new { |list|
    var i = 0
    for (n in list) {
        if (n > 1e7)  return [n, i]
        i = i + 1
    }
}

var ranges = [0..0, 101..909, 11011..99099, 1110111..9990999, 111101111..119101111]
var cyclops = []
for (r in ranges) {
    var numDigits = r.from.toString.count
    var center = (numDigits / 2).floor
    for (i in r) {
        var digits = Int.digits(i)
        if (digits[center] == 0 && digits.count { |d| d == 0 } == 1) cyclops.add(i)
    }
}

System.print("The first 50 cyclops numbers are:")
var candidates = cyclops[0...50]
var ni = findFirst.call(cyclops)
for (chunk in Lst.chunks(candidates, 10)) Fmt.print("$,6d", chunk)
Fmt.print("\nFirst such number > 10 million is $,d at zero-based index $,d", ni[0], ni[1])

System.print("\n\nThe first 50 prime cyclops numbers are:")
var primes = cyclops.where { |n| Int.isPrime(n) }
candidates = primes.take(50).toList
ni = findFirst.call(primes)
for (chunk in Lst.chunks(candidates, 10)) Fmt.print("$,6d", chunk)
Fmt.print("\nFirst such number > 10 million is $,d at zero-based index $,d", ni[0], ni[1])

System.print("\n\nThe first 50 blind prime cyclops numbers are:")
var bpcyclops = []
var ppcyclops = []
for (p in primes) {
    var ps = p.toString
    var numDigits = ps.count
    var center = (numDigits/2).floor
    var noMiddle = Num.fromString(Str.delete(ps, center))
    if (Int.isPrime(noMiddle)) bpcyclops.add(p)
    if (ps == ps[-1..0]) ppcyclops.add(p)
}
candidates = bpcyclops[0...50]
ni = findFirst.call(bpcyclops)
for (chunk in Lst.chunks(candidates, 10)) Fmt.print("$,6d", chunk)
Fmt.print("\nFirst such number > 10 million is $,d at zero-based index $,d", ni[0], ni[1])

System.print("\n\nThe first 50 palindromic prime cyclops numbers are:")
candidates = ppcyclops[0...50]
ni = findFirst.call(ppcyclops)
for (chunk in Lst.chunks(candidates, 8)) Fmt.print("$,9d", chunk)
Fmt.print("\nFirst such number > 10 million is $,d at zero-based index $,d", ni[0], ni[1])


defmodule Date_format do
  def iso_date, do: Date.utc_today |> Date.to_iso8601

  def iso_date(year, month, day), do: Date.from_erl!({year, month, day}) |> Date.to_iso8601

  def long_date, do: Date.utc_today |> long_date

  def long_date(year, month, day), do: Date.from_erl!({year, month, day}) |> long_date

  @months  Enum.zip(1..12, ~w[January February March April May June July August September October November December])
           |> Map.new
  @weekdays  Enum.zip(1..7, ~w[Monday Tuesday Wednesday Thursday Friday Saturday Sunday])
             |> Map.new
  def long_date(date) do
    weekday = Date.day_of_week(date)
    "#{@weekdays[weekday]}, #{@months[date.month]} #{date.day}, #{date.year}"
  end
end

IO.puts Date_format.iso_date
IO.puts Date_format.long_date
IO.puts Date_format.iso_date(2007,11,10)
IO.puts Date_format.long_date(2007,11,10)


(format-time-string "%Y-%m-%d")
(format-time-string "%F")  ;; new in Emacs 24
;; => "2015-11-08"

(format-time-string "%A, %B %e, %Y")
;; => "Sunday, November  8, 2015"


-module(format_date).
-export([iso_date/0, iso_date/1, iso_date/3, long_date/0, long_date/1, long_date/3]).
-import(calendar,[day_of_the_week/1]).
-import(io,[format/2]).
-import(lists,[append/1]).

iso_date() -> iso_date(date()).
iso_date(Year, Month, Day) -> iso_date({Year, Month, Day}).
iso_date(Date) ->
  format("~4B-~2..0B-~2..0B~n", tuple_to_list(Date)).

long_date() -> long_date(date()).
long_date(Year, Month, Day) -> long_date({Year, Month, Day}).
long_date(Date = {Year, Month, Day}) ->
  Months =   { "January",   "February", "March",    "April",
               "May",       "June",     "July",     "August",
               "September", "October",  "November", "December" },
  Weekdays = { "Monday", "Tuesday",  "Wednesday", "Thursday",
               "Friday", "Saturday", "Sunday" },
  Weekday     = day_of_the_week(Date),
  WeekdayName = element(Weekday, Weekdays),
  MonthName   = element(Month, Months),
  append([WeekdayName, ", ", MonthName, " ", integer_to_list(Day), ", ",
          integer_to_list(Year)]).


func IsCyclops(N);      \Return 'true' if N is a cyclops number
int  N, I, J, K;
char A(9);
[I:= 0;                 \parse digits into array A
repeat  N:= N/10;
        A(I):= rem(0);
        I:= I+1;
until   N=0;
if (I&1) = 0 then return false; \must have odd number of digits
K:= I>>1;
if A(K) # 0 then return false;  \middle digit must be 0
for J:= 0 to I-1 do             \other digits must not be 0
        if A(J)=0 & J#K then return false;
return true;
];

func IsPrime(N);        \Return 'true' if N > 2 is a prime number
int  N, I;
[if (N&1) = 0 \even number\ then return false;
for I:= 3 to sqrt(N) do
    [if rem(N/I) = 0 then return false;
    I:= I+1;
    ];
return true;
];

func Blind(N);          \Return blinded cyclops number
int  N, I, J, K;        \i.e. center zero removed
char A(9);
[I:= 0;                 \parse digits into array A
repeat  N:= N/10;
        A(I):= rem(0);
        I:= I+1;
until   N=0;
N:= A(I-1);             \most significant digit
K:= I>>1;
for J:= I-2 downto 0 do
    if J#K then         \skip middle zero
        N:= N*10 + A(J);
return N;
];

func Reverse(N);        \Return N with its digits reversed
int  N, M;
[M:= 0;
repeat  N:= N/10;
        M:= M*10 + rem(0);
until   N=0;
return M;
];

func    IntLen(N);      \Return number of decimal digits in N
int     N;
int     P, I;
[P:= 10;
for I:= 1 to 9 do       \assumes N is 32-bits
        [if P>N then return I;
        P:= P*10;
        ];
return 10;
];

int Count, N;

func Show;              \Show results and return 'true' when done
[Count:= Count+1;
    if Count <= 50 then
        [IntOut(0, N);
        if rem(Count/10) = 0 then CrLf(0) else ChOut(0, 9\tab\);
        ];
    if N > 10_000_000 then
        [Text(0, "First such number > 10,000,000: ");
        IntOut(0, N);
        Text(0, " at zero based index: ");
        IntOut(0, Count-1);
        CrLf(0);
        return true;
        ];
return false;
];

proc Common(Filter);    \Common code gathered here
int  Filter;
[Count:= 0;
N:= 0;
loop    [if IsCyclops(N) then
           case Filter of
             0: if Show then quit;
             1: if IsPrime(N) then
                    if Show then quit;
             2: if IsPrime(N) then if IsPrime(Blind(N)) then
                    if Show then quit;
             3: if N=Reverse(N) then if IsPrime(N) then
                    if Show then quit
           other        [];
        N:= N+1;
        if (IntLen(N)&1) = 0 then N:= N*10;     \must have odd number of digits
        ];
];

[Text(0, "First 50 cyclops numbers:
");
Common(0);
Text(0, "
First 50 prime cyclops numbers:
");
Common(1);
Text(0, "
First 50 blind prime cyclops numbers:
");
Common(2);
Text(0, "
First 50 palindromic prime cyclops numbers:
");
Common(3);
]


constant days = {"Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"}
constant months = {"January","February","March","April","May","June",
    "July","August","September","October","November","December"}

sequence now

now = date()
now[1] += 1900

printf(1,"%d-%02d-%02d\n",now[1..3])
printf(1,"%s, %s %d, %d\n",{days[now[7]],months[now[2]],now[3],now[1]})


> open System;;
> Console.WriteLine( DateTime.Now.ToString("yyyy-MM-dd") );;
2010-08-13
> Console.WriteLine( "{0:D}", DateTime.Now );;
Friday, August 13, 2010


: newdigit ( col row -- u ) 10 * + C" 0317598642709215486342068713591750983426612304597836742095815869720134894536201794386172052581436790" 1+ + [email protected] 48 - ;
: nextdigit ( addr -- addr+1 u ) dup [email protected] 48 - swap 1+ swap ;

: damm ( c u -- u )
0 rot rot
0 do
  nextdigit
  rot newdigit swap
loop drop
;

: isdamm? damm 0= if ." yes" else ." no" then ;

: .damm
2dup damm
rot rot type 48 + emit
;


      LOGICAL FUNCTION DAMM(DIGIT)	!Check that a sequence of digits checks out..
Calculates according to the method of H. Michael Damm, described in 2004.
       CHARACTER*(*) DIGIT		!A sequence of digits only.
       INTEGER*1 OPTABLE(0:9,0:9)	!The special "Operation table" of the method.
       PARAMETER (OPTABLE = (/		!A set of constants...
     o  0, 3, 1, 7, 5, 9, 8, 6, 4, 2,	!        CAREFUL!
     1  7, 0, 9, 2, 1, 5, 4, 8, 6, 3,	!Fortran stores arrays in column-major order.
     2  4, 2, 0, 6, 8, 7, 1, 3, 5, 9,	!Despite the manifest row and column layout apparent here
     3  1, 7, 5, 0, 9, 8, 3, 4, 2, 6,	!This sequence of consecutive items will go into storage order.
     4  6, 1, 2, 3, 0, 4, 5, 9, 7, 8,	!The table resulting from this sequence of constants
     5  3, 6, 7, 4, 2, 0, 9, 5, 8, 1,	!Will appear to be transposed if referenced as (row,column)
     6  5, 8, 6, 9, 7, 2, 0, 1, 3, 4,	!What appears to be row=6 column=1 (counting from zero)
     7  8, 9, 4, 5, 3, 6, 2, 0, 1, 7,	!is to be accessed as OPTABLE(1,6) = 8, not OPTABLE(6,1)
     8  9, 4, 3, 8, 6, 1, 7, 2, 0, 5,	!Storage order is (0,0), (1,0), (2,0), ... (9,0)
     9  2, 5, 8, 1, 4, 3, 6, 7, 9, 0/))	!Followed by      (0,1), (1,1), (2,1), ... (9,1)
       INTEGER I,D,ID	!Assistants.
        ID = 0		!Here we go.
        DO I = 1,LEN(DIGIT)	!Step through the text.
          D = ICHAR(DIGIT(I:I)) - ICHAR("0")	!Convert to an integer. (ASCII or EBCDIC)
          IF (D.LT.0 .OR. D.GT.9) STOP "DAMM! Not a digit!"	!This shouldn't happen!
          ID = OPTABLE(D,ID)		!Transposed: D is the column index and ID the row.
        END DO			!On to the next.
        DAMM = ID .EQ. 0	!Somewhere, a check digit should ensure this.
      END FUNCTION DAMM	!Simple, fast, and alas, rarely used.

      LOGICAL DAMM	!Not a default type.

      WRITE (6,*) DAMM("5724"),"5724"
      WRITE (6,*) DAMM("5727"),"5727"
      WRITE (6,*) DAMM("112946"),"112946"

      END


USING: formatting calendar io ;

now "%Y-%m-%d" strftime print
now "%A, %B %d, %Y" strftime print


fansh> Date.today.toLocale("YYYY-MM-DD")
2011-02-24
fansh> Date.today.toLocale("WWWW, MMMM DD, YYYY")
Thursday, February 24, 2011


: .-0 ( n -- n )
  [char] - emit
  dup 10 < if [char] 0 emit then ;

: .short-date
  time&date ( s m h D M Y )
  1 u.r .-0 1 u.r .-0 1 u.r
  drop drop drop ;

: str-table
  create ( n -- ) 0 do , loop
  does>  ( n -- str len ) swap cells + @ count ;

 here ," December"
 here ," November"
 here ," October"
 here ," September"
 here ," August"
 here ," July"
 here ," June"
 here ," May"
 here ," April"
 here ," March"
 here ," February"
 here ," January"
12 str-table months

 here ," Sunday"
 here ," Saturday"
 here ," Friday"
 here ," Thursday"
 here ," Wednesday"
 here ," Tuesday"
 here ," Monday"
7 str-table weekdays

\ Zeller's Congruence
: zeller ( m -- days since March 1 )
  9 + 12 mod 1-   26 10 */ 3 + ;

: weekday ( d m y -- 0..6 )   \ Monday..Sunday
  over 3 < if 1- then
  dup    4 /
  over 100 / -
  over 400 / +  +
  swap zeller + +
  1+ 7 mod ;

: 3dup   dup 2over rot ;

: .long-date
  time&date ( s m h D M Y )
  3dup weekday weekdays type ." , "
  >R 1- months type space 1 u.r ." , " R> .
  drop drop drop ;


' version 04-07-2018
' compile with: fbc -s console

Function Damm(digit_str As String) As UInteger

    Dim As UInteger table(10,10) => { { 0, 3, 1, 7, 5, 9, 8, 6, 4, 2 } , _
   { 7, 0, 9, 2, 1, 5, 4, 8, 6, 3 } , { 4, 2, 0, 6, 8, 7, 1, 3, 5, 9 } , _
   { 1, 7, 5, 0, 9, 8, 3, 4, 2, 6 } , { 6, 1, 2, 3, 0, 4, 5, 9, 7, 8 } , _
   { 3, 6, 7, 4, 2, 0, 9, 5, 8, 1 } , { 5, 8, 6, 9, 7, 2, 0, 1, 3, 4 } , _
   { 8, 9, 4, 5, 3, 6, 2, 0, 1, 7 } , { 9, 4, 3, 8, 6, 1, 7, 2, 0, 5 } , _
   { 2, 5, 8, 1, 4, 3, 6, 7, 9, 0 } }

    Dim As UInteger i, col_i, old_row_i, new_row_i

    For i = 0 To Len(digit_str) -1
        col_i = digit_str[i] - Asc("0")
        new_row_i = table(old_row_i, col_i)
        old_row_i = new_row_i
    Next

    Return new_row_i

End Function

' ------=< MAIN >=------

Data "5724", "5727", "112946", ""

Dim As UInteger checksum, t
Dim As String test_string

Do

    Read test_string
    If test_string = "" Then Exit Do
    Print "Checksum test: ";test_string;

    checksum = Damm(test_string)
    If checksum = 0 Then
        Print " is valid"
    Else
        Print " is invalid"
    End If

Loop

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


curzon?: function [n,base]->
    zero? (inc base^n) % inc base*n

first50: function [b][
    result: new []
    i: 1
    while [50 > size result][
        if curzon? i b -> 'result ++ i
        i: i + 1
    ]
    return result
]

oneThousandth: function [b][
    cnt: 0
    i: 1
    while [cnt < 1000][
        if curzon? i b -> cnt: cnt+1
        i: i + 1
    ]
    return dec i
]

loop select 2..10 => even? 'withBase [
    print ["First 50 Curzon numbers with base" withBase]
    loop split.every: 10 first50 withBase 'row [
        print map to [:string] row 'item -> pad item 4
    ]
    print ["\n1000th Curzon with base" withBase "=" oneThousandth withBase]
    print ""
]


#include <iomanip>
#include <iostream>
#include <vector>

#include <gmpxx.h>

bool is_curzon(int n, int k) {
    mpz_class p;
    mpz_ui_pow_ui(p.get_mpz_t(), k, n);
    return (p + 1) % (k * n + 1) == 0;
}

int main() {
    for (int k = 2; k <= 10; k += 2) {
        std::cout << "Curzon numbers with base " << k << ":\n";
        int count = 0, n = 1;
        for (; count < 50; ++n) {
            if (is_curzon(n, k)) {
                std::cout << std::setw(4) << n
                          << (++count % 10 == 0 ? '\n' : ' ');
            }
        }
        for (;;) {
            if (is_curzon(n, k))
                ++count;
            if (count == 1000)
                break;
            ++n;
        }
        std::cout << "1000th Curzon number with base " << k << ": " << n
                  << "\n\n";
    }
    return 0;
}


PROGRAM DATE

  IMPLICIT NONE

  INTEGER :: dateinfo(8), day
  CHARACTER(9) :: month, dayname

  CALL DATE_AND_TIME(VALUES=dateinfo)
  SELECT CASE(dateinfo(2))
    CASE(1)
      month = "January"
    CASE(2)
      month = "February"
    CASE(3)
      month = "March"
    CASE(4)
      month = "April"
    CASE(5)
      month = "May"
    CASE(6)
      month = "June"
    CASE(7)
      month = "July"
    CASE(8)
      month = "August"
    CASE(9)
      month = "September"
    CASE(10)
      month = "October"
    CASE(11)
      month = "November"
    CASE(12)
     month = "December"
  END SELECT

  day = Day_of_week(dateinfo(3), dateinfo(2), dateinfo(1))

  SELECT CASE(day)
    CASE(0)
      dayname = "Saturday"
    CASE(1)
      dayname = "Sunday"
    CASE(2)
      dayname = "Monday"
    CASE(3)
      dayname = "Tuesday"
    CASE(4)
      dayname = "Wednesday"
    CASE(5)
      dayname = "Thursday"
    CASE(6)
      dayname = "Friday"
  END SELECT

  WRITE(*,"(I0,A,I0,A,I0)") dateinfo(1),"-", dateinfo(2),"-", dateinfo(3)
  WRITE(*,"(4(A),I0,A,I0)") trim(dayname), ", ", trim(month), " ", dateinfo(3), ", ", dateinfo(1)

CONTAINS

  FUNCTION Day_of_week(d, m, y)
    INTEGER :: Day_of_week, j, k
    INTEGER, INTENT(IN) :: d, m, y

    j = y / 100
    k = MOD(y, 100)
    Day_of_week = MOD(d + (m+1)*26/10 + k + k/4 + j/4 + 5*j, 7)
  END FUNCTION Day_of_week

END PROGRAM DATE


USING: grouping interpolate io kernel make math math.functions
prettyprint ranges sequences ;

: curzon? ( k n -- ? ) [ ^ 1 + ] 2keep * 1 + divisor? ;

: next ( k n -- k n' ) [ 2dup curzon? ] [ 1 + ] do until ;

: curzon ( k -- seq )
    1 [ 50 [ dup , next ] times ] { } make 2nip ;

: curzon. ( k -- )
    dup [I Curzon numbers with base ${}:I] nl
    curzon 10 group simple-table. ;

2 10 2 <range> [ curzon. nl ] each


' limit: k * n +1 must be smaller then 2^32-1

Function pow_mod(b As ULongInt, power As ULongInt, modulus As ULongInt) As ULongInt
    ' returns b ^ power mod modulus
    Dim As ULongInt x = 1

    While power > 0
        If (power And 1) = 1 Then
            x = (x * b) Mod modulus
        End If
        b = (b * b) Mod modulus
        power = power Shr 1
    Wend

    Return x

End Function

For k As ULongInt= 2 To 10 Step 2
    Print "The first 50 Curzon numbers using a base of "; k; ":"
    Dim As ULongInt count, n = 1, p, m

    Do
        m = k * n +1
        p = pow_mod(k, n ,m) +1
        If p = m Then
            count += 1
            If count <= 50 Then
                Print Using "#####"; n;
                If (count Mod 10) = 0 Then Print
            ElseIf count = 1000 Then
                Print : Print "One thousandth: "; n
                Print : Print
                Exit Do
            End If
        End If
        n += 1
    Loop

Next
Sleep


package main

import (
    "fmt"
    "math/big"
)

func main() {
    zero := big.NewInt(0)
    one := big.NewInt(1)
    for k := int64(2); k <= 10; k += 2 {
        bk := big.NewInt(k)
        fmt.Println("The first 50 Curzon numbers using a base of", k, ":")
        count := 0
        n := int64(1)
        pow := big.NewInt(k)
        z := new(big.Int)
        var curzon50 []int64
        for {
            z.Add(pow, one)
            d := k*n + 1
            bd := big.NewInt(d)
            if z.Rem(z, bd).Cmp(zero) == 0 {
                if count < 50 {
                    curzon50 = append(curzon50, n)
                }
                count++
                if count == 50 {
                    for i := 0; i < len(curzon50); i++ {
                        fmt.Printf("%4d ", curzon50[i])
                        if (i+1)%10 == 0 {
                            fmt.Println()
                        }
                    }
                    fmt.Print("\nOne thousandth: ")
                }
                if count == 1000 {
                    fmt.Println(n)
                    break
                }
            }
            n++
            pow.Mul(pow, bk)
        }
        fmt.Println()
    }
}


' FB 1.05.0 Win64

#Include "vbcompat.bi"

Dim d As Long = Now
Print "This example was created on : "; Format(d, "yyyy-mm-dd")
Print "In other words on : "; Format(d, "dddd, mmmm d, yyyy")
Print
Print "Press any key to quit the program"
Sleep


program Format_Date_Time;
uses
  SysUtils;
begin
  WriteLn(FormatDateTime('yyyy-mm-dd', Now) +#13#10+ FormatDateTime('dddd, mmmm dd, yyyy', Now));
end.


println[now[] -> ### yyyy-MM-dd ###]
println[now[] -> ### EEEE, MMMM d, yyyy ###]


# To take advantage of gojq's arbitrary-precision integer arithmetic:
def power($b): . as $in | reduce range(0;$b) as $i (1; . * $in);

def lpad($len): tostring | ($len - length) as $l | (" " * $l)[:$l] + .;

# gojq does not currently define _nwise
def _nwise($n):
  def n: if length <= $n then . else .[0:$n] , (.[$n:] | n) end;
  n;

def printRows($m): _nwise($m) | map(lpad(5)) | join("");


isCurzon(n, k) = (BigInt(k)^n + 1) % (k * n + 1) == 0

function printcurzons(klow, khigh)
    for k in filter(iseven, klow:khigh)
        n, curzons = 0, Int[]
        while length(curzons) < 1000
            isCurzon(n, k) && push!(curzons, n)
            n += 1
        end
        println("Curzon numbers with k = $k:")
        foreach(p -> print(lpad(p[2], 5), p[1] % 25 == 0 ? "\n" : ""), enumerate(curzons[1:50]))
        println("    Thousandth Curzon with k = $k: ", curzons[1000])
    end
end

printcurzons(2, 10)


program CurzonNumbers;
uses SysUtils;
const
  MAX_CURZON_MEG = 100;
  RC_LINE_LENGTH = 66;

procedure ListCurzonNumbers( base : integer);
var
  k, n, m, x, testBit, maxCurzon : uint64;
  nrHits : integer;
  lineOut : string;
begin
  maxCurzon := 1000000*MAX_CURZON_MEG;
  k := uint64( base);
  nrHits := 0;
  n := 0;
  WriteLn;
  if Odd( base) then WriteLn( SysUtils.Format(
        'Curzon numbers with base %d up to %d million', [base, MAX_CURZON_MEG]))
  else WriteLn( SysUtils.Format(
        'First 50 Curzon numbers with base %d', [base]));
  lineOut := '';
  repeat
    inc(n); // possible (generalized) Curzon number
    m := k*n + 1; // modulus
    testBit := 1;
    repeat testBit := testBit shl 1 until testBit > n;
    testBit := testBit shr 2;
    // Calculate k^n modulo m
    x := k;
    while testBit > 0 do begin
      x := (x*x) mod m;
      if (testBit and n) <> 0 then x := (x*k) mod m;
      testBit := testBit shr 1;
    end;
    // n is a Curzon number to base k iff k^n + 1 is divisible by m
    if (x + 1) mod m = 0 then begin
      inc( nrHits);
      if Odd( base) then
        lineOut := lineOut + ' ' + SysUtils.IntToStr( n)
      else if (nrHits <= 50) then
        lineOut := lineOut + SysUtils.Format( '%5d', [n]);
      if Length( lineOut) >= RC_LINE_LENGTH then begin
        WriteLn( lineOut); lineOut := '';
      end
      else if (nrHits = 1000) then begin
        if lineOut <> '' then begin
          WriteLn( lineOut); lineOut := '';
        end;
        WriteLn( SysUtils.Format( '1000th = %d', [n]));
      end;
    end;
  until (n = maxCurzon) or (nrHits = 1000);
  if lineOut <> '' then WriteLn( lineOut);
end;

begin
  ListCurzonNumbers( 2);
  ListCurzonNumbers( 4);
  ListCurzonNumbers( 6);
  ListCurzonNumbers( 8);
  ListCurzonNumbers(10);
  ListCurzonNumbers( 3);
  ListCurzonNumbers( 5);
  ListCurzonNumbers( 7);
  ListCurzonNumbers( 9);
  ListCurzonNumbers(11);
end.


println( format('%tF', $date) )
println( format('%1$tA, %1$tB %1$td, %1$tY', $date) )


window 1

print date(@"yyyy-MM-dd")
print date(@"EEEE, MMMM dd, yyyy")

HandleEvents


Public Sub Main()

Print Format(Now, "yyyy - mm - dd")
Print Format(Now, "dddd, mmmm dd, yyyy")

End


ClearAll[CurzonNumberQ]
CurzonNumberQ[b_Integer][n_Integer]:=PowerMod[b,n,b n+1]==b n
val=Select[Range[100000],CurzonNumberQ[2]];
Take[val,50]
val[[1000]]

val=Select[Range[100000],CurzonNumberQ[4]];
Take[val,50]
val[[1000]]

val=Select[Range[100000],CurzonNumberQ[6]];
Take[val,50]
val[[1000]]

val=Select[Range[100000],CurzonNumberQ[8]];
Take[val,50]
val[[1000]]

val=Select[Range[100000],CurzonNumberQ[10]];
Take[val,50]
val[[1000]]


use strict;
use warnings;
use Math::AnyNum 'ipow';

sub curzon {
    my($base,$cnt) = @_;
    my($n,@C) = 0;
    while (++$n) {
        push @C, $n if 0 == (ipow($base,$n) + 1) % ($base * $n + 1);
        return @C if $cnt == @C;
    }
}

my $upto = 50;
for my $k (<2 4 6 8 10>) {
    my @C = curzon($k,1000);
    print "First $upto Curzon numbers using a base of $k:\n" .
    (sprintf "@{['%5d' x $upto]}", @C[0..$upto-1]) =~ s/(.{125})/$1\n/gr;
    print "Thousandth: $C[-1]\n\n";
}


with javascript_semantics
include mpfr.e
mpz {pow,z} = mpz_inits(2)
for base=2 to 10 by 2 do
    printf(1,"The first 50 Curzon numbers using a base of %d:\n",base)
    integer count = 0, n = 1
    mpz_set_si(pow,base)
    while true do
        mpz_add_ui(z,pow,1)
        integer d = base*n + 1
        if mpz_divisible_ui_p(z,d) then
            count = count + 1
            if count<=50 then
                printf(1,"%5d%s",{n,iff(remainder(count,25)=0?"\n":"")})
            elsif count=1000 then
                printf(1,"One thousandth: %d\n\n",n)
                exit
            end if
        end if
        n += 1
        mpz_mul_si(pow,pow,base)
    end while
end for


package main

import "time"
import "fmt"

func main() {
    fmt.Println(time.Now().Format("2006-01-02"))
    fmt.Println(time.Now().Format("Monday, January 2, 2006"))
}


def isoFormat = { date -> date.format("yyyy-MM-dd") }
def longFormat = { date -> date.format("EEEE, MMMM dd, yyyy") }


import Data.Time
       (FormatTime, formatTime, defaultTimeLocale, utcToLocalTime,
        getCurrentTimeZone, getCurrentTime)

formats :: FormatTime t => [t -> String]
formats = (formatTime defaultTimeLocale) <$>  ["%F", "%A, %B %d, %Y"]

main :: IO ()
main = do
  t <- pure utcToLocalTime <*> getCurrentTimeZone <*> getCurrentTime
  putStrLn $ unlines (formats <*> pure t)


  [ number$
    space 4 of swap join
    -5 split nip echo$ ]    is rjust   (   n -->   )

   [ 5 times
       [ 10 times
           [ behead rjust ]
         cr ]
    drop ]                  is display (   [ -->   )

  [ temp take
    over join
    temp put ]              is dax     (   [ -->   )

  [ 2dup ** 1+
    unrot * 1+ mod 0 = ]    is curzon  ( n n --> b )

  5 times
    [ i^ 1+ 2 *
      say "Curzon numbers base "
      dup echo cr
      1
      [] temp put
      [ 2dup curzon if dax
        temp share
        size 1000 < while
        1+ again ]
      2drop
      temp take
      50 split swap display
      say "  ... "
      -1 peek echo cr cr ]


sub curzon ($base) { lazy (1..∞).hyper.map: { $_ if (exp($_, $base) + 1) %% ($base × $_ + 1) } };

for <2 4 6 8 10> {
    my $curzon = .&curzon;
    say "\nFirst 50 Curzon numbers using a base of $_:\n" ~
      $curzon[^50].batch(25)».fmt("%4s").join("\n") ~
      "\nOne thousandth: " ~ $curzon[999]
}


// [dependencies]
// rug = "1.15.0"

fn is_curzon(n: u32, k: u32) -> bool {
    use rug::{Complete, Integer};
    (Integer::u_pow_u(k, n).complete() + 1) % (k * n + 1) == 0
}

fn main() {
    for k in (2..=10).step_by(2) {
        println!("Curzon numbers with base {k}:");
        let mut count = 0;
        let mut n = 1;
        while count < 50 {
            if is_curzon(n, k) {
                count += 1;
                print!("{:4}{}", n, if count % 10 == 0 { "\n" } else { " " });
            }
            n += 1;
        }
        loop {
            if is_curzon(n, k) {
                count += 1;
                if count == 1000 {
                    break;
                }
            }
            n += 1;
        }
        println!("1000th Curzon number with base {k}: {n}\n");
    }
}


func is_curzon(n, k) {
    powmod(k, n, k*n + 1).is_congruent(-1, k*n + 1) && (n > 0)
}

for k in (2 .. 10 `by` 2) {
    say "\nFirst 50 Curzon numbers using a base of #{k}:"
    say 50.by {|n| is_curzon(n, k) }.join(' ')
    say ("1000th term: ", 1000.th {|n| is_curzon(n,k) })
}


import math.big

fn main() {
    zero := big.zero_int
    one := big.one_int
    for k := i64(2); k <= 10; k += 2 {
        bk := big.integer_from_i64(k)
        println("The first 50 Curzon numbers using a base of $k:")
        mut count := 0
        mut n := i64(1)
        mut pow := big.integer_from_i64(k)
        mut curzon50 := []i64{}
        for {
            z := pow + one
            d := k*n + 1
            bd := big.integer_from_i64(d)
            if z%bd == zero {
                if count < 50 {
                    curzon50 << n
                }
                count++
                if count == 50 {
                    for i in 0..curzon50.len {
                        print("${curzon50[i]:4} ")
                        if (i+1)%10 == 0 {
                            println('')
                        }
                    }
                    print("\nOne thousandth: ")
                }
                if count == 1000 {
                    println(n)
                    break
                }
            }
            n++
            pow *= bk
        }
        println('')
    }
}


/* curzon_numbers.wren */

import "./gmp" for Mpz
import "./seq" for Lst
import "./fmt" for Fmt

for (k in [2, 4, 6, 8, 10]) {
    System.print("The first 50 Curzon numbers using a base of %(k):")
    var count = 0
    var n = 1
    var pow = Mpz.from(k)
    var curzon50 = []
    while (true) {
        var z = pow + Mpz.one
        var d = k*n + 1
        if (z.isDivisibleUi(d)) {
            if (count < 50) curzon50.add(n)
            count = count + 1
            if (count == 50) {
                for (chunk in Lst.chunks(curzon50, 10)) Fmt.print("$4d", chunk)
                System.write("\nOne thousandth: ")
            }
            if (count == 1000) {
                System.print(n)
                break
            }
        }
        n = n + 1
        pow.mul(k)
    }
    System.print()
}


   CHARACTER string*40

   WRITE(Text=string, Format='UCCYY-MM-DD') 0 ! string: 2010-03-13

   ! the U-format to write date and time uses ',' to separate additional output formats
   ! we therefore use ';' in this example and change it to ',' below:
   WRITE(Text=string,Format='UWWWWWWWWW; MM DD; CCYY') 0 ! string = "Saturday ; 03 13; 2010"
   READ(Text=string) month ! first numeric value = 3 (no literal month name available)
   EDIT(Text='January,February,March,April,May,June,July,August,September,October,November,December', ITeM=month, Parse=cMonth) ! cMonth = "March"
   ! change now string = "Saturday ; 03 13; 2010" to "Saturday, March 13, 2010":
   EDIT(Text=string, Right=' ', Mark1, Right=';', Right=3, Mark2, Delete, Insert=', '//cMonth, Right=';', RePLaceby=',')

 END


procedure main()
write(map(&date,"/","-"))
write(&dateline ? tab(find(&date[1:5])+4))
end


import java.util.Calendar;
import java.util.GregorianCalendar;
import java.text.DateFormatSymbols;
import java.text.DateFormat;
public class Dates{
 public static void main(String[] args){
  Calendar now = new GregorianCalendar(); //months are 0 indexed, dates are 1 indexed
  DateFormatSymbols symbols = new DateFormatSymbols(); //names for our months and weekdays

  //plain numbers way
  System.out.println(now.get(Calendar.YEAR)  + "-" + (now.get(Calendar.MONTH) + 1) + "-" + now.get(Calendar.DATE));

  //words way
  System.out.print(symbols.getWeekdays()[now.get(Calendar.DAY_OF_WEEK)] + ", ");
  System.out.print(symbols.getMonths()[now.get(Calendar.MONTH)] + " ");
  System.out.println(now.get(Calendar.DATE) + ", " + now.get(Calendar.YEAR));
 }
}


var now = new Date(),
    weekdays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
    months   = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
    fmt1 = now.getFullYear() + '-' + (1 + now.getMonth()) + '-' + now.getDate(),
    fmt2 = weekdays[now.getDay()] + ', ' + months[now.getMonth()] + ' ' + now.getDate() + ', ' + now.getFullYear();
console.log(fmt1);
console.log(fmt2);


DEFINE weekdays == [ "Monday" "Tuesday" "Wednesday" "Thursday" "Friday" "Saturday" "Sunday" ];
       months   == [ "January" "February" "March" "April" "May" "June" "July" "August"
                     "September" "October" "November" "December" ].

time localtime [ [0 at 'd 4 4 format] ["-"] [1 at 'd 2 2 format] ["-"] [2 at 'd 2 2 format] ]
[i] map [putchars] step '\n putch pop.

time localtime [ [8 at pred weekdays of] [", "] [1 at pred months of] [" "] [2 at 'd 1 1 format]
[", "] [0 at 'd 4 4 format] ] [i] map [putchars] step '\n putch pop.


// version 1.1.2

val table = arrayOf(
    intArrayOf(0, 3, 1,	7, 5, 9, 8, 6, 4, 2),
    intArrayOf(7, 0, 9, 2, 1, 5, 4, 8, 6, 3),
    intArrayOf(4, 2, 0, 6, 8, 7, 1, 3, 5, 9),
    intArrayOf(1, 7, 5, 0, 9, 8, 3, 4, 2, 6),
    intArrayOf(6, 1, 2, 3, 0, 4, 5, 9, 7, 8),
    intArrayOf(3, 6, 7, 4, 2, 0, 9, 5, 8, 1),
    intArrayOf(5, 8, 6, 9, 7, 2, 0, 1, 3, 4),
    intArrayOf(8, 9, 4, 5, 3, 6, 2, 0, 1, 7),
    intArrayOf(9, 4, 3, 8, 6, 1, 7, 2, 0, 5),
    intArrayOf(2, 5, 8, 1, 4, 3, 6, 7, 9, 0)
)

fun damm(s: String): Boolean {
    var interim = 0
    for (c in s) interim = table[interim][c - '0']
    return interim == 0
}

fun main(args: Array<String>) {
    val numbers = intArrayOf(5724, 5727, 112946, 112949)
    for (number in numbers) {
        val isValid = damm(number.toString())
        println("${"%6d".format(number)} is ${if (isValid) "valid" else "invalid"}")
    }
}


ts = Dates.today()

println("Today's date is:")
println("\t$ts")
println("\t", Dates.format(ts, "E, U dd, yyyy"))


// version 1.0.6

import java.util.GregorianCalendar

fun main(args: Array<String>) {
    val now = GregorianCalendar()
    println("%tF".format(now))
    println("%tA, %1\$tB %1\$te, %1\$tY".format(now))
}


var .now = dt//
var .format1 = "2006-01-02"
var .format2 = "Monday, January 2, 2006"
writeln $"\.now:dt.format1;"
writeln $"\.now:dt.format2;"


'Display the current date in the formats of "2007-11-10"
d$=date$("yyyy/mm/dd")
print word$(d$,1,"/")+"-"+word$(d$,2,"/")+"-"+word$(d$,3,"/")

'and "Sunday, November 10, 2007".
day$(0)="Tuesday"
day$(1)="Wednesday"
day$(2)="Thursday"
day$(3)="Friday"
day$(4)="Saturday"
day$(5)="Sunday"
day$(6)="Monday"
theDay = date$("days") mod 7
print day$(theDay);", ";date$()

' month in full
year=val(word$(d$,1,"/"))
month=val(word$(d$,2,"/"))
day=val(word$(d$,3,"/"))
weekDay$="Tuesday Wednesday Thursday Friday Saturday Sunday Monday"
monthLong$="January February March April May June July August September October November December"

print word$(weekDay$,theDay+1);", ";word$(monthLong$,month);" ";day;", ";year


            NORMAL MODE IS INTEGER

          R VERIFY DAMM CHECKSUM OF NUMBER
            INTERNAL FUNCTION(CKNUM)
            VECTOR VALUES DAMMIT =
          0        0,3,1,7,5,9,8,6,4,2
          1     ,  7,0,9,2,1,5,4,8,6,3
          2     ,  4,2,0,6,8,7,1,3,5,9
          3     ,  1,7,5,0,9,8,3,4,2,6
          4     ,  6,1,2,3,0,4,5,9,7,8
          5     ,  3,6,7,4,2,0,9,5,8,1
          6     ,  5,8,6,9,7,2,0,1,3,4
          7     ,  8,9,4,5,3,6,2,0,1,7
          8     ,  9,4,3,8,6,1,7,2,0,5
          9     ,  2,5,8,1,4,3,6,7,9,0
            DIMENSION DAMDGT(10)
            ENTRY TO DAMM.
            TMP=CKNUM
            THROUGH GETDGT, FOR NDGT=0, 1, TMP.E.0
            DAMDGT(NDGT) = TMP-TMP/10*10
GETDGT      TMP = TMP/10
            INTRM = 0
            THROUGH CKDGT, FOR NDGT=NDGT, -1, NDGT.L.0
CKDGT       INTRM = DAMMIT(INTRM*10 + DAMDGT(NDGT))
            FUNCTION RETURN INTRM.E.0
            END OF FUNCTION

          R TEST SOME NUMBERS
            THROUGH TEST, FOR VALUES OF N = 5724,5727,112946,112949
            WHENEVER DAMM.(N)
                PRINT FORMAT VALID,N
            OTHERWISE
                PRINT FORMAT INVAL,N
TEST        END OF CONDITIONAL

            VECTOR VALUES VALID = $I9,S1,5HVALID*$
            VECTOR VALUES INVAL = $I9,S1,7HINVALID*$
            END OF PROGRAM


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

TYPE TA = ARRAY[0..9],[0..9] OF INTEGER;
CONST table = TA{
        {0, 3, 1, 7, 5, 9, 8, 6, 4, 2},
        {7, 0, 9, 2, 1, 5, 4, 8, 6, 3},
        {4, 2, 0, 6, 8, 7, 1, 3, 5, 9},
        {1, 7, 5, 0, 9, 8, 3, 4, 2, 6},
        {6, 1, 2, 3, 0, 4, 5, 9, 7, 8},
        {3, 6, 7, 4, 2, 0, 9, 5, 8, 1},
        {5, 8, 6, 9, 7, 2, 0, 1, 3, 4},
        {8, 9, 4, 5, 3, 6, 2, 0, 1, 7},
        {9, 4, 3, 8, 6, 1, 7, 2, 0, 5},
        {2, 5, 8, 1, 4, 3, 6, 7, 9, 0}
    };

PROCEDURE Damm(s : ARRAY OF CHAR) : BOOLEAN;
VAR interim,i : INTEGER;
BEGIN
    interim := 0;

    i := 0;
    WHILE s[i] # 0C DO
        interim := table[interim,INT(s[i])-INT('0')];
        INC(i);
    END;
    RETURN interim=0;
END Damm;

PROCEDURE Print(number : INTEGER);
VAR
    isValid : BOOLEAN;
    buf : ARRAY[0..16] OF CHAR;
BEGIN
    FormatString("%i", buf, number);
    isValid := Damm(buf);
    WriteString(buf);
    IF isValid THEN
        WriteString(" is valid");
    ELSE
        WriteString(" is invalid");
    END;
    WriteLn;
END Print;

BEGIN
    Print(5724);
    Print(5727);
    Print(112946);
    Print(112949);

    ReadChar;
END DammAlgorithm.


on mouseUp pButtonNumber
   put the date into tDate
   convert tDate to dateItems
   put item 1 of tDate & "-" & item 2 of tDate & "-" & item 3 of tDate & return into tMyFormattedDate
   put tMyFormattedDate & the long date
end mouseUp


print first shell [date +%F]
print first shell [date +"%A, %B %d, %Y"]


from algorithm import reverse

const Table = [[0, 3, 1, 7, 5, 9, 8, 6, 4, 2],
               [7, 0, 9, 2, 1, 5, 4, 8, 6, 3],
               [4, 2, 0, 6, 8, 7, 1, 3, 5, 9],
               [1, 7, 5, 0, 9, 8, 3, 4, 2, 6],
               [6, 1, 2, 3, 0, 4, 5, 9, 7, 8],
               [3, 6, 7, 4, 2, 0, 9, 5, 8, 1],
               [5, 8, 6, 9, 7, 2, 0, 1, 3, 4],
               [8, 9, 4, 5, 3, 6, 2, 0, 1, 7],
               [9, 4, 3, 8, 6, 1, 7, 2, 0, 5],
               [2, 5, 8, 1, 4, 3, 6, 7, 9, 0]]

type Digit = range[0..9]

func isValid(digits: openArray[Digit]): bool =
  ## Apply Damm algorithm to check validity of a digit sequence.
  var interim = 0
  for d in digits:
    interim = Table[interim][d]
  result = interim == 0

proc toDigits(n: int): seq[Digit] =
  ## Return the digits of a number.
  var n = n
  while true:
    result.add(n mod 10)
    n = n div 10
    if n == 0:
      break
  result.reverse()

proc checkData(digits: openArray[Digit]) =
  ## Check if a digit sequence if valid.
  if isValid(digits):
    echo "Sequence ", digits, " is valid."
  else:
    echo "Sequence ", digits, " is invalid."

checkData(5724.toDigits)
checkData(5727.toDigits)
checkData([Digit 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 6, 7, 8, 9, 0, 1])
checkData([Digit 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 6, 7, 8, 9, 0, 8])


print( os.date( "%Y-%m-%d" ) )
print( os.date( "%A, %B %d, %Y" ) )


Print str$(today, "yyyy-mm-dd")
Print str$(today, "dddd, mmm, dd, yyyy")


program DammAlgorithm;
uses
  sysutils;

TYPE TA = ARRAY[0..9,0..9] OF UInt8;
CONST table : TA =
                ((0,3,1,7,5,9,8,6,4,2),
                 (7,0,9,2,1,5,4,8,6,3),
                 (4,2,0,6,8,7,1,3,5,9),
                 (1,7,5,0,9,8,3,4,2,6),
                 (6,1,2,3,0,4,5,9,7,8),
                 (3,6,7,4,2,0,9,5,8,1),
                 (5,8,6,9,7,2,0,1,3,4),
                 (8,9,4,5,3,6,2,0,1,7),
                 (9,4,3,8,6,1,7,2,0,5),
                 (2,5,8,1,4,3,6,7,9,0));

function Damm(s : string) : BOOLEAN;
VAR
  interim,i : UInt8;
BEGIN
  interim := 0;
  i := 1;
  WHILE i <= length(s) DO
  Begin
    interim := table[interim,ORD(s[i])-ORD('0')];
    INC(i);
  END;
  Damm := interim=0;
END;

PROCEDURE Print(number : Uint32);
VAR
    isValid : BOOLEAN;
    buf :string;
BEGIN
    buf := IntToStr(number);
    isValid := Damm(buf);
    Write(buf);
    IF isValid THEN
      Write(' is valid')
    ELSE
      Write(' is invalid');
    WriteLn;
END;

BEGIN
    Print(5724);
    Print(5727);
    Print(112946);
    Print(112949);
    Readln;
END.


DateString[{"Year", "-", "Month", "-", "Day"}]
DateString[{"DayName", ", ", "MonthName", " ", "Day", ", ", "Year"}]


>> datestr(now,'yyyy-mm-dd')

ans =

2010-06-18

>> datestr(now,'dddd, mmmm dd, yyyy')

ans =

Friday, June 18, 2010


("YYYY-MM-dd" "dddd, MMMM dd, YYYY") ('timestamp dip tformat puts!) foreach


echo -ag $time(yyyy-mm-dd)
echo -ag $time(dddd $+ $chr(44) mmmm dd $+ $chr(44) yyyy)


DTZ
 WRITE !,"Date format 3: ",$ZDATE($H,3)
 WRITE !,"Or ",$ZDATE($H,12),", ",$ZDATE($H,9)
 QUIT


import Nanoquery.Util

d = new(Date)
println d.getYear() + "-" + d.getMonth() + "-" + d.getDay()
println d.getDayOfWeek() + ", " + d.getMonthName() + " " + d.getDay() + ", " + d.getYear()


/**
 <doc>

Date format

Neko uses Int32 to store system date/time values.
 And lib C strftime style formatting for converting to string form

 </doc>
*/

var date_now = $loader.loadprim("[email protected]_now", 0)
var date_format = $loader.loadprim("[email protected]_format", 2)

var now = date_now()
$print(date_format(now, "%F"), "\n")
$print(date_format(now, "%A, %B %d, %Y"), "\n")


import java.text.SimpleDateFormat
say SimpleDateFormat("yyyy-MM-dd").format(Date())
say SimpleDateFormat("EEEE, MMMM dd, yyyy").format(Date())


; file:   date-format.lsp
; url:    http://rosettacode.org/wiki/Date_format
; author: oofoe 2012-02-01

; The "now" function returns the current time as a list. A time zone
; offset in minutes can be supplied. The example below is for Eastern
; Standard Time. NewLISP's implicit list indexing is used to extract
; the first three elements of the returned list (year, month and day).

(setq n (now (* -5 60)))
(println "short: " (format "%04d-%02d-%02d" (n 0) (n 1) (n 2)))

; The "date-value" function returns the time in seconds from the epoch
; when used without arguments. The "date" function converts the
; seconds into a time representation specified by the format string at
; the end. The offset argument ("0" in this example) specifies a
; time-zone offset in minutes.

(println "short: " (date (date-value) 0 "%Y-%m-%d"))

; The time formatting is supplied by the underlying C library, so
; there may be differences on certain platforms. Particularly, leading
; zeroes in day numbers can be suppressed with "%-d" on Linux and
; FreeBSD, "%e" on OpenBSD, SunOS/Solaris and Mac OS X. Use "%#d" for
; Windows.

(println "long:  " (date (date-value) 0 "%A, %B %#d, %Y"))

; By setting the locale, the date will be displayed appropriately:

(set-locale "japanese")
(println "long:  " (date (date-value) 0 "%A, %B %#d, %Y"))

(exit)


import times

var t = now()
echo(t.format("yyyy-MM-dd"))
echo(t.format("dddd',' MMMM d',' yyyy"))


use IO;
use Time;

bundle Default {
  class CurrentDate {
    function : Main(args : String[]) ~ Nil {
      t := Date->New();
      Console->Print(t->GetYear())->Print("-")->Print(t->GetMonth())->Print("-")
        ->PrintLine(t->GetDay());
      Console->Print(t->GetDayName())->Print(", ")->Print(t->GetMonthName())
        ->Print(" ")->Print(t->GetDay())->Print(", ")
        ->PrintLine(t->GetYear());
    }
  }
}


100H:

/* DAMM CHECKSUM FOR DECIMAL NUMBER IN GIVEN STRING */
CHECK$DAMM: PROCEDURE (PTR) BYTE;
    DECLARE PTR ADDRESS, CH BASED PTR BYTE;
    DECLARE DAMM DATA
        ( 0,3,1,7,5,9,8,6,4,2,
          7,0,9,2,1,5,4,8,6,3,
          4,2,0,6,8,7,1,3,5,9,
          1,7,5,0,9,8,3,4,2,6,
          6,1,2,3,0,4,5,9,7,8,
          3,6,7,4,2,0,9,5,8,1,
          5,8,6,9,7,2,0,1,3,4,
          8,9,4,5,3,6,2,0,1,7,
          9,4,3,8,6,1,7,2,0,5,
          2,5,8,1,4,3,6,7,9,0 );
    DECLARE I BYTE;
    I = 0;
    DO WHILE CH <> '$';
        I = DAMM((I*10) + (CH-'0'));
        PTR = PTR + 1;
    END;
    RETURN I = 0;
END CHECK$DAMM;

/* CP/M BDOS CALLS */
BDOS: PROCEDURE (FN, ARG);
    DECLARE FN BYTE, ARG ADDRESS;
    GO TO 5;
END BDOS;

PRINT: PROCEDURE (STR);
    DECLARE STR ADDRESS;
    CALL BDOS(9, STR);
END PRINT;

/* TESTS */
DECLARE TEST (4) ADDRESS;
TEST(0) = .'5724$';
TEST(1) = .'5727$';
TEST(2) = .'112946$';
TEST(3) = .'112949$';

DECLARE N BYTE;
DO N = 0 TO LAST(TEST);
    CALL PRINT(TEST(N));
    CALL PRINT(.': $');
    IF CHECK$DAMM(TEST(N)) THEN
        CALL PRINT(.'PASS$');
    ELSE
        CALL PRINT(.'FAIL$');
    CALL PRINT(.(13,10,'$'));
END;

CALL BDOS(0,0);
EOF


NSLog(@"%@", [NSDate date]);
NSLog(@"%@", [[NSDate date] descriptionWithCalendarFormat:@"%Y-%m-%d" timeZone:nil locale:nil]);
NSLog(@"%@", [[NSDate date] descriptionWithCalendarFormat:@"%A, %B %d, %Y" timeZone:nil locale:nil]);


# #load "unix.cma";;
# open Unix;;

# let t = time() ;;
val t : float = 1219997516.

# let gmt = gmtime t ;;
val gmt : Unix.tm =
  {tm_sec = 56; tm_min = 11; tm_hour = 8; tm_mday = 29; tm_mon = 7;
   tm_year = 108; tm_wday = 5; tm_yday = 241; tm_isdst = false}

# Printf.sprintf "%d-%02d-%02d" (1900 + gmt.tm_year) (1 + gmt.tm_mon) gmt.tm_mday ;;
- : string = "2008-08-29"


DataSection
  DT_Start:
        Data.b	0,3,1,7,5,9,8,6,4,2
	Data.b	7,0,9,2,1,5,4,8,6,3
	Data.b	4,2,0,6,8,7,1,3,5,9
	Data.b	1,7,5,0,9,8,3,4,2,6
	Data.b	6,1,2,3,0,4,5,9,7,8
	Data.b	3,6,7,4,2,0,9,5,8,1
	Data.b	5,8,6,9,7,2,0,1,3,4
	Data.b	8,9,4,5,3,6,2,0,1,7
	Data.b	9,4,3,8,6,1,7,2,0,5
	Data.b	2,5,8,1,4,3,6,7,9,0
EndDataSection

Procedure.i Adr(Row,Col) : ProcedureReturn ?DT_Start+Row+10*Col : EndProcedure

Procedure.b CheckDamm(Value.s)
  *ipc.Character=@Value : it=0
  While *ipc\c
    it=PeekB(Adr(*ipc\c-'0',it)) : *ipc+SizeOf(Character)
  Wend
  ProcedureReturn Bool(it)
EndProcedure

If OpenConsole()
  Repeat
    Print("Check Damm: ") : i$=Input()
    If CheckDamm(i$) : PrintN(Space(12)+"FALSE") : Else : PrintN(Space(12)+"TRUE") : EndIf
  Until i$=""
EndIf
End


/* REXX */
dats='20071123'
Say date('I',dats,'S')
Say date('W',dats,'S')',' date('M',dats,'S') substr(dats,7,2)',' left(dats,4)
Say date('W',dats,'S')',' date('M',dats,'S') translate('gh, abcd',dats,'abcdefgh')
dati=date('I')
Say dati
Say date('W',dati,'I')',' date('M',dati,'I') translate('ij, abcd',dati,'abcdefghij')


extern lib "kernel32.dll"

'http://msdn.microsoft.com/en-us/library/windows/desktop/ms724950(v=vs.85).aspx

typedef struct _SYSTEMTIME {
  WORD wYear;
  WORD wMonth;
  WORD wDayOfWeek;
  WORD wDay;
  WORD wHour;
  WORD wMinute;
  WORD wSecond;
  WORD wMilliseconds;
} SYSTEMTIME, *PSYSTEMTIME;

void GetSystemTime(SYSTEMTIME*t);
void GetLocalTime(SYSTEMTIME*t);

end extern

SYSTEMTIME t
'GetSystemTime t 'GMT (Greenwich Mean Time)
GetLocalTime t

String WeekDay[7]={"Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"}
String MonthName[12]={"January","February","March","April","May","June","July","August","September","October","November","December"}
String month=str t.wMonth : if len(month)<2 then month="0"+month
String day=str t.wDay : if len(day)<2 then day="0"+day
'
print "" t.wYear "-" month "-" day
print WeekDay[t.wDayOfWeek+1 and 7 ] " " MonthName[t.wMonth and 31] " " t.wDay " " t.wYear


declare
  WeekDays = unit(0:"Sunday" "Monday" "Tuesday" "Wednesday"
                  "Thursday" "Friday" "Saturday")
  Months = unit(0:"January" "February" "March" "April"
                "May" "June" "July" "August" "September"
                "October" "November" "December")

  fun {DateISO Time}
     Year = 1900 + Time.year
     Month = Time.mon + 1
  in
     Year#"-"#{Align Month}#"-"#{Align Time.mDay}
  end

  fun {DateLong Time}
     Year = 1900 + Time.year
  in
     WeekDays.(Time.wDay)#", "#Months.(Time.mon)#" "#Time.mDay#", "#Year
  end

  fun {Align Num}
     if Num < 10 then "0"#Num else Num end
  end
in
  {System.showInfo {DateISO {OS.localTime}}}
  {System.showInfo {DateLong {OS.localTime}}}


#lang racket/base
(require racket/match)

(define operation-table
  #(#(0 3 1 7 5 9 8 6 4 2)
    #(7 0 9 2 1 5 4 8 6 3)
    #(4 2 0 6 8 7 1 3 5 9)
    #(1 7 5 0 9 8 3 4 2 6)
    #(6 1 2 3 0 4 5 9 7 8)
    #(3 6 7 4 2 0 9 5 8 1)
    #(5 8 6 9 7 2 0 1 3 4)
    #(8 9 4 5 3 6 2 0 1 7)
    #(9 4 3 8 6 1 7 2 0 5)
    #(2 5 8 1 4 3 6 7 9 0)))

(define (integer->digit-list n)
  (let loop ((n n) (a null))
    (if (zero? n) a (let-values (([q r] (quotient/remainder n 10))) (loop q (cons r a))))))

(define/match (check-digit n)
  [((list ds ...))
   (foldl
    (λ (d interim)
      (vector-ref (vector-ref operation-table interim) d))
    0 ds)]
  [((? integer? i))
   (check-digit (integer->digit-list i))])

(define/match (valid-number? n)
  [((? integer? i))
   (valid-number? (integer->digit-list i))]
  [((list ds ...))
   (zero? (check-digit ds))])

(module+ test
  (require rackunit)
  (check-equal? (integer->digit-list 572) '(5 7 2))
  (check-equal? (check-digit 572) 4)
  (check-equal? (check-digit '(5 7 2)) 4)
  (check-true (valid-number? 5724))
  (check-false (valid-number? 5274))
  (check-true (valid-number? 112946)))


program dateform;
uses DOS;

{ Format digit with leading zero }
function lz(w: word): string;
var
  s: string;
begin
  str(w,s);
  if length(s) = 1 then
    s := '0' + s;
  lz := s
end;

function m2s(mon: integer): string;
begin
  case mon of
     1: m2s := 'January';
     2: m2s := 'February';
     3: m2s := 'March';
     4: m2s := 'April';
     5: m2s := 'May';
     6: m2s := 'June';
     7: m2s := 'July';
     8: m2s := 'August';
     9: m2s := 'September';
    10: m2s := 'October';
    11: m2s := 'November';
    12: m2s := 'December'
  end
end;

function d2s(dow: integer): string;
begin
  case dow of
    0: d2s := 'Sunday';
    1: d2s := 'Monday';
    2: d2s := 'Tueday';
    3: d2s := 'Wednesday';
    4: d2s := 'Thursday';
    5: d2s := 'Friday';
    6: d2s := 'Saturday'
  end
end;

var
  yr,mo,dy,dow: word;
  mname,dname: string;

begin
  GetDate(yr,mo,dy,dow);
  writeln(yr,'-',lz(mo),'-',lz(dy));
  mname := m2s(mo); dname := d2s(dow);
  writeln(dname,', ',mname,' ',dy,', ',yr)
end.


/* REXX */
Call init
Call test 5724
Call test 5727
Call test 112946
Call test 112940
Exit

test:
Parse Arg number
int_digit=0
Do p=1 To length(number)
  d=substr(number,p,1)
  int_digit=grid.int_digit.d
  If p<length(number) Then cd=int_digit
  End
If int_digit=0 Then
  Say number 'is ok'
Else
  Say number 'is not ok, check-digit should be' cd '(instead of' d')'
Return

init:
i=-2
Call setup '* 0 1 2 3 4 5 6 7 8 9'
Call setup '0 0 3 1 7 5 9 8 6 4 2'
Call setup '1 7 0 9 2 1 5 4 8 6 3'
Call setup '2 4 2 0 6 8 7 1 3 5 9'
Call setup '3 1 7 5 0 9 8 3 4 2 6'
Call setup '4 6 1 2 3 0 4 5 9 7 8'
Call setup '5 3 6 7 4 2 0 9 5 8 1'
Call setup '6 5 8 6 9 7 2 0 1 3 4'
Call setup '7 8 9 4 5 3 6 2 0 1 7'
Call setup '8 9 4 3 8 6 1 7 2 0 5'
Call setup '9 2 5 8 1 4 3 6 7 9 0'
Return
setup:
  Parse Arg list
  i=i+1
  Do col=-1 To 9
    grid.i.col=word(list,col+2)
    End
  Return


with javascript_semantics
include builtins\timedate.e
?format_timedate(date(),"YYYY-MM-DD")
?format_timedate(date(),"Dddd, Mmmm d, YYYY")


<?php
echo date('Y-m-d', time())."\n";
echo date('l, F j, Y', time())."\n";
?>


(let (Date (date)  Lst (date Date))
   (prinl (dat$ Date "-"))             # 2010-02-19
   (prinl                              # Friday, February 19, 2010
      (day Date)
      ", "
      (get *MonFmt (cadr Lst))
      " "
      (caddr Lst)
      ", "
      (car Lst) ) )


object cal = Calendar.ISO.Day();
write( cal->format_ymd() +"\n" );
string special = sprintf("%s, %s %d, %d",
                         cal->week_day_name(),
                         cal->month_name(),
                         cal->month_day(),
                         cal->year_no());
write( special +"\n" );


Push 0, 3, 1, 7, 5, 9, 8, 6, 4, 2: i = FUNC(_Data(0))
Push 7, 0, 9, 2, 1, 5, 4, 8, 6, 3: i = FUNC(_Data(i))
Push 4, 2, 0, 6, 8, 7, 1, 3, 5, 9: i = FUNC(_Data(i))
Push 1, 7, 5, 0, 9, 8, 3, 4, 2, 6: i = FUNC(_Data(i))
Push 6, 1, 2, 3, 0, 4, 5, 9, 7, 8: i = FUNC(_Data(i))
Push 3, 6, 7, 4, 2, 0, 9, 5, 8, 1: i = FUNC(_Data(i))
Push 5, 8, 6, 9, 7, 2, 0, 1, 3, 4: i = FUNC(_Data(i))
Push 8, 9, 4, 5, 3, 6, 2, 0, 1, 7: i = FUNC(_Data(i))
Push 9, 4, 3, 8, 6, 1, 7, 2, 0, 5: i = FUNC(_Data(i))
Push 2, 5, 8, 1, 4, 3, 6, 7, 9, 0: i = FUNC(_Data(i))
                                       ' Read the table
Push 112949, 112946, 5727, 5724        ' Put numbers on the stack

For i = 1 To Used()                    ' Read up to the number of stack items
  Print Using "______"; Tos();" is ";  ' Print the header
  If FUNC(_Damm (Str(Pop()))) Then Print "in";
  Print "valid"                        ' invalid only if Damm() returns TRUE
Next                                   ' Next stack item

End

_Data Param (1)                        ' Reads data in reverse order,
  Local (2)                            ' starting with [email protected]

  [email protected] = [email protected] + Used()                     ' Calculate next offset

  For [email protected] = [email protected] To [email protected] Step -1          ' Now place the elements
    @([email protected]) = Pop()                      ' that are retrieved from the stack
  Next [email protected]                              ' Next item

Return ([email protected])                            ' Return new offset

_Damm Param (1)                        ' Perform the Damm algorithm
  Local (2)

  [email protected] = 0                               ' Reset the flag
  For [email protected] = 0 To Len([email protected]) - 1            ' Check all characters in the string
    [email protected] = @([email protected]*10 + peek([email protected], [email protected]) - ord("0"))
  Next                                 ' Next character

Return ([email protected])                            ' Return Flag


df: proc Options(main);
 declare day_of_week(7) character (9) varying initial(
    'Sunday','Monday','Tuesday','Wednesday',
    'Thursday','Friday','Saturday');
 declare today character (9);

 today = datetime('YYYYMMDD');
 put edit(substr(today,1,4),'-',substr(today,5,2),'-',substr(today,7))
  (A);

 today = datetime('MmmDDYYYY');
 put skip edit(day_of_week(weekday(days())),', ') (A);
 put edit(substr(today,1,3),' ',substr(today,4,2),', ',
          substr(today,6,4))(A);
 end;


"{0:yyyy-MM-dd}" -f (Get-Date)
"{0:dddd, MMMM d, yyyy}" -f (Get-Date)
# or
(Get-Date).ToString("yyyy-MM-dd")
(Get-Date).ToString("dddd, MMMM d, yyyy")


Module Module1

    ReadOnly table = {
            {0, 3, 1, 7, 5, 9, 8, 6, 4, 2},
            {7, 0, 9, 2, 1, 5, 4, 8, 6, 3},
            {4, 2, 0, 6, 8, 7, 1, 3, 5, 9},
            {1, 7, 5, 0, 9, 8, 3, 4, 2, 6},
            {6, 1, 2, 3, 0, 4, 5, 9, 7, 8},
            {3, 6, 7, 4, 2, 0, 9, 5, 8, 1},
            {5, 8, 6, 9, 7, 2, 0, 1, 3, 4},
            {8, 9, 4, 5, 3, 6, 2, 0, 1, 7},
            {9, 4, 3, 8, 6, 1, 7, 2, 0, 5},
            {2, 5, 8, 1, 4, 3, 6, 7, 9, 0}
        }

    Function Damm(s As String) As Boolean
        Dim interim = 0
        For Each c In s
            interim = table(interim, AscW(c) - AscW("0"))
        Next
        Return interim = 0
    End Function

    Sub Main()
        Dim numbers = {5724, 5727, 112946, 112949}
        For Each number In numbers
            Dim isvalid = Damm(number.ToString())
            If isvalid Then
                Console.WriteLine("{0,6} is valid", number)
            Else
                Console.WriteLine("{0,6} is invalid", number)
            End If
        Next
    End Sub

End Module


display_date :-
    get_time(Time),
    format_time(atom(Short), '%Y-%M-%d',      Time),
    format_time(atom(Long),  '%A, %B %d, %Y', Time),
    format('~w~n~w~n', [Short, Long]).


;Declare Procedures
Declare.s MonthInText()
Declare.s DayInText()

;Output the requested strings
Debug FormatDate("%yyyy-%mm-%dd", Date())
Debug DayInText() + ", " + MonthInText() + FormatDate(" %dd, %yyyy", Date())

;Used procedures
Procedure.s DayInText()
  Protected d$
  Select DayOfWeek(Date())
    Case 1: d$="Monday"
    Case 2: d$="Tuesday"
    Case 3: d$="Wednesday"
    Case 4: d$="Thursday"
    Case 5: d$="Friday"
    Case 6: d$="Saturday"
    Default: d$="Sunday"
  EndSelect
  ProcedureReturn d$
EndProcedure

Procedure.s MonthInText()
  Protected  m$
  Select Month(Date())
    Case 1: m$="January"
    Case 2: m$="February"
    Case 3: m$="March"
    Case 4: m$="April"
    Case 5: m$="May"
    Case 6: m$="June"
    Case 7: m$="July"
    Case 8: m$="August"
    Case 9: m$="September"
    Case 10:m$="October"
    Case 11:m$="November"
    Default:m$="December"
  EndSelect
  ProcedureReturn m$
EndProcedure


import datetime
today = datetime.date.today()
# The first requested format is a method of datetime objects:
today.isoformat()
# For full flexibility, use the strftime formatting codes from the link above:
today.strftime("%A, %B %d, %Y")
# This mechanism is integrated into the general string formatting system.
# You can do this with positional arguments referenced by number
"The date is {0:%A, %B %d, %Y}".format(d)
# Or keyword arguments referenced by name
"The date is {date:%A, %B %d, %Y}".format(date=d)
# Since Python 3.6, f-strings allow the value to be inserted inline
f"The date is {d:%A, %B %d, %Y}"


now <- Sys.time()
strftime(now, "%Y-%m-%d")
strftime(now, "%A, %B %d, %Y")


#lang racket
(require srfi/19)

;;; The first required format is an ISO-8601 year-month-day format, predefined
;;; as ~1 in date->string
(displayln (date->string (current-date) "~1"))

;;; You should be able to see how each of the components of the following format string
;;; work...
;;; ~d is zero padded day of month:
(displayln (date->string (current-date) "~A, ~B ~d, ~Y"))
;;; ~e is space padded day of month:
(displayln (date->string (current-date) "~A, ~B ~e, ~Y"))


use DateTime::Format;

my $dt = DateTime.now;

say strftime('%Y-%m-%d', $dt);
say strftime('%A, %B %d, %Y', $dt);


rebol [
	Title: "Date Formatting"
	URL: http://rosettacode.org/wiki/Date_format
]

; REBOL has no built-in pictured output.

zeropad: func [pad n][
    n: to-string n
    insert/dup n "0" (pad - length? n)
    n
]
d02: func [n][zeropad 2 n]

print now ; Native formatting.

print rejoin [now/year  "-"  d02 now/month  "-"  d02 now/day]

print rejoin [
	pick system/locale/days now/weekday ", "
	pick system/locale/months now/month " "
	now/day ", " now/year
]


Red []
;; zeropad
f2n: func [d] [ if  d > 9 [return d ]   append copy "0" d  ]

d: now/date

print rejoin [d/year "-" f2n d/month "-" f2n d/day]
print rejoin [system/locale/days/(d/weekday) ", " system/locale/months/(d/month) " " f2n d/day ", " d/year]


/*REXX pgm shows current date:  yyyy-mm-dd  &  Dayofweek, Month dd, yyyy*/
   x = date('S')                       /*get current date as  yyyymmdd  */
yyyy = left(x,4)                       /*pick off year         (4 digs).*/
  dd = right(x,2)                      /*pick off day-of-month (2 digs).*/
  mm = substr(x,5,2)                   /*pick off month number (2 digs).*/
say yyyy'-'mm"-"dd                     /*yyyy-mm-dd with leading zeroes.*/

weekday = date('W')                    /*dayofweek (Monday or somesuch).*/
month   = date('M')                    /*Month     (August or somesuch).*/
zdd     = dd+0                         /*remove leading zero from  DD   */
say weekday',' month zdd"," yyyy       /*format date as:  Month dd, yyyy*/
                                       /*stick a fork in it, we're done.*/


dateStr = date()
date1 = timelist()[19] + "-" + timelist()[10] + "-" + timelist()[6]
date2 = timelist()[2] + ", " + timelist()[4] + " " + timelist()[6] + ", " + timelist()[19] + nl
? dateStr
? date1
? date2

/*
timelist() ---> List contains the time and date information.
Index           Value
----------------------------
1 - abbreviated weekday name
2 - full weekday name
3 - abbreviated month name
4 - full month name
5 - Date & Time
6 - Day of the month
7 - Hour (24)
8 - Hour (12)
9 - Day of the year
10 - Month of the year
11 - Minutes after hour
12 - AM or PM
13 - Seconds after the hour
14 - Week of the year (sun-sat)
15 - day of the week
16 - date
17 - time
18 - year of the century
19 - year
20 - time zone
21 - percent sign
*/


puts Time.now
puts Time.now.strftime('%Y-%m-%d')
puts Time.now.strftime('%F')            # same as %Y-%m-%d (ISO 8601 date formats)
puts Time.now.strftime('%A, %B %d, %Y')


'Display the current date in the formats of "2007-11-10" and "Sunday, November 10, 2007".
print date$("yyyy-mm-dd")
print date$("dddd");", ";                     'return full day of the week (eg. Wednesday
print date$("mmmm");" ";                      'return full month name (eg. March)
print date$("dd, yyyy")                       'return day, year


fn main() {
    let now = chrono::Utc::now();
    println!("{}", now.format("%Y-%m-%d"));
    println!("{}", now.format("%A, %B %d, %Y"));
}


val now=new Date()
println("%tF".format(now))
println("%1$tA, %1$tB %1$td, %1$tY".format(now))


(define short-date
  (lambda (lt)
    (strftime "%Y-%m-%d" (localtime lt))))

(define long-date
  (lambda (lt)
    (strftime "%A, %B %d, %Y" (localtime lt))))

(define main
  (lambda (args)
    ;; Current date
    (let ((dt (car (gettimeofday))))
      ;; Short style
      (display (short-date dt))(newline)
      ;; Long style
      (display (long-date dt))(newline))))


$ include "seed7_05.s7i";
  include "time.s7i";

const proc: main is func
  local
    const array string: months is [] ("January", "February", "March", "April", "May", "June",
        "July", "August", "September", "October", "November", "December");
    const array string: days is [] ("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday");
    var time: now is time.value;
  begin
    now := time(NOW);
    writeln(strDate(now));
    writeln(days[dayOfWeek(now)] <& ", " <& months[now.month] <& " " <& now.day <& ", " <& now.year);
  end func;


put formattedTime( "[year]-[month]-[day]", the date)

put formattedTime( "[weekday], [month name] [day], [year]", the date)


say time.format 'Y-m-d' time.now
say time.format 'l, F j, Y' time.now


var time = Time.local;
say time.ctime;
say time.strftime("%Y-%m-%d");
say time.strftime("%A, %B %d, %Y");


| d |
d := Date today.
d printFormat: #(3 2 1 $- 1 1 2).
(d weekday asString), ', ', (d monthName), ' ', (d dayOfMonth asString), ', ', (d year asString)


SELECT to_char(sysdate,'YYYY-MM-DD') date_fmt_1 FROM dual;

SELECT to_char(sysdate,'fmDay, Month DD, YYYY') date_fmt_2 FROM dual;


print (Date.fmt "%Y-%m-%d" (Date.fromTimeLocal (Time.now ())) ^ "\n");
print (Date.fmt "%A, %B %d, %Y" (Date.fromTimeLocal (Time.now ())) ^ "\n");


display %tdCCYY-NN-DD td($S_DATE)
display %tdDayname,_Month_dd,_CCYY td($S_DATE)


Date().Format('yyyy-MM-dd')  -->  "2010-03-16"
Date().LongDate() -->  "Tuesday, March 16, 2010"


import Foundation
extension String {
    func toStandardDateWithDateFormat(format: String) -> String {
        let dateFormatter = NSDateFormatter()
        dateFormatter.dateFormat = format
        dateFormatter.dateStyle = .LongStyle
        return dateFormatter.stringFromDate(dateFormatter.dateFromString(self)!)
    }
}

let date = "2015-08-28".toStandardDateWithDateFormat("yyyy-MM-dd")


set now [clock seconds]
puts [clock format $now -format "%Y-%m-%d"]
puts [clock format $now -format "%A, %B %d, %Y"]


locals {
  today = timestamp()
}

output "iso" {
  value = formatdate("YYYY-MM-DD", local.today)
}

output "us-long" {
  value = formatdate("EEEE, MMMM D, YYYY", local.today)
}


$$ MODE TUSCRIPT
SET dayofweek = DATE (today,day,month,year,number)

SET months=*
DATA January
DATA Februari
DATA March
DATA April
DATA Mai
DATA June
DATA July
DATA August
DATA September
DATA October
DATA November
DATA December

SET days="Monday'Tuesday'Wendsday'Thursday'Fryday'Saturday'Sonday"

SET nameofday  =SELECT (days,#dayofweek)
SET nameofmonth=SELECT (months,#month)

SET format1=JOIN (year,"-",month,day)
SET format2=CONCAT (nameofday,", ",nameofmonth," ",day, ", ",year)

PRINT format1
PRINT format2


cygnus/x ursa v0.78 (default, release 0)
[Oracle Corporation JVM 1.8.0_51 on Mac OS X 10.10.5 x86_64]
> import "java.util.Date"
> import "java.text.SimpleDateFormat"
> decl java.text.SimpleDateFormat sdf
> sdf.applyPattern "yyyy-MM-dd"
> decl java.util.Date d
> out (sdf.format d) endl console
2016-07-23
> sdf.applyPattern "EEEE, MMMM dd, yyyy"
> out (sdf.format d) endl console
Saturday, July 23, 2016
> _


#import std
#import cli

months = ~&p/block3'JanFebMarAprMayJunJulAugSepOctNovDec' block2'010203040506070809101112'

completion =

-:~& ~&pllrTXS/block3'SunMonTueWedThuFriSat'--(~&lS months) -- (
   --','* sep`, 'day,day,sday,nesday,rsday,day,urday',
   sep`, 'uary,ruary,ch,il,,e,y,ust,tember,ober,ember,ember')

text_form    = sep` ; mat` + completion*+ <.~&hy,~&tth,--','@th,~&ttth>
numeric_form = sep` ; mat`-+ <.~&ttth,@tth -: months,~&th>

#show+

main = <.text_form,numeric_form> now0


OPTION EXPLICIT

' Months
DATA "January", "February", "March", "April", "May", "June", "July"
DATA "August", "September", "October", "November", "December"

' Days of week
DATA "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"

' Var
DIM dDate AS DOUBLE, sMonth(1 TO 12) AS STRING, sDay(1 TO 7) AS STRING
DIM i AS INTEGER

' Read Names of months
FOR i = 1 TO 12
  READ sMonth(i)
NEXT i

' Read Names of days
FOR i = 1 TO 7
  READ sDay(i)
NEXT i

' Assign current date to a variable
dDate = NOW

CLS
PRINT "Rosettacode: Display the current date formatted."
PRINT
PRINT "Today's date: "; FORMAT$(dDate, "ddddd")
PRINT
PRINT "Use of values in the lists."
PRINT "Today is "; sDay(WEEKDAY(dDate)); ", "; sMonth(MONTH(dDate)); " "; FORMAT$(DAY(dDate)); ", "; FORMAT$(YEAR(dDate)); "."
PRINT
PRINT "Use of just the FORMAT$() function."
PRINT "Today is "; FORMAT$(dDate, "dddd, mmmm d, yyyy"); "."

END


Function DateFormats()
    Debug.Print Format(Date, "yyyy-mm-dd")
    Debug.Print Format(Date, "dddd, mmmm dd yyyy")
End Function


'YYYY-MM-DD format
WScript.StdOut.WriteLine Year(Date) & "-" & Right("0" & Month(Date),2) & "-" & Right("0" & Day(Date),2)

'Weekday_Name, Month_Name DD, YYYY format
WScript.StdOut.WriteLine FormatDateTime(Now,1)


import time

fn main() {
    println(time.now().custom_format("YYYY-MM-DD"))
    println(time.now().custom_format("dddd, MMMM D, YYYY"))
}


import "os" for Process
import "/date" for Date

var args = Process.arguments
if (args.count != 1) {
    Fiber.abort("Please pass just the current date in yyyy-mm-dd format.")
}
var current = Date.parse(args[0])
System.print(current.format(Date.isoDate))
System.print(current.format("dddd|, |mmmm| |d|, |yyyy"))


include c:\cxpl\codes;
int CpuReg, Year, Month, Day, DName, MName, WDay;
[CpuReg:= GetReg;       \access CPU registers
CpuReg(0):= $2A00;      \DOS system call
SoftInt($21);
Year:= CpuReg(2);
Month:= CpuReg(3) >> 8;
Day:= CpuReg(3) & $FF;
WDay:= CpuReg(0) & $FF;
IntOut(0, Year);  ChOut(0, ^-);
if Month<10 then ChOut(0, ^0);  IntOut(0, Month);  ChOut(0, ^-);
if Day<10 then ChOut(0, ^0);  IntOut(0, Day);  CrLf(0);
DName:= ["Sunday", "Monday", "Tuesday", "Wednesday",
        "Thursday", "Friday", "Saturday"];
MName:= [0, "January", "February", "March", "April", "May", "June", "July",
        "August", "September", "October", "November", "December"];
Text(0, DName(WDay));  Text(0, ", ");  Text(0, MName(Month));  Text(0, " ");
IntOut(0, Day);  Text(0, ", ");  IntOut(0, Year);  CrLf(0);
]


dim n$(1)

n = token(date$, n$(), "-")

print n$(4), "-", n$(2), "-", n$(3)
print nDay$(n$(5)), ", ", nMonth$(n$(6)), " ", n$(3), ", ", n$(4)

sub nDay$(n$)
	switch n$
	case "Mon": case "Fri": case "Sun": break
	case "Tue": n$ = n$ + "s" : break
	case "Wed": n$ = n$ + "nes" : break
	case "Thu": n$ = n$ + "rs" : break
	case "Sat": n$ = n$ + "ur" : break
	default: n$ = "none" : break
	end switch

	return n$ + "day"
end sub

sub nMonth$(n$)
	local month$(1), n

	n = token("January, February, March, April, May, June, July, August, September, October, November, December", month$(), ", ")
	n = instr("JanFebMarAprMayJunJulAugSepOctNovDec", n$)

	return month$(int(n/3) + 1)
end sub


"%d-%02d-%02d".fmt(Time.Clock.localTime.xplode()).println()
//--> "2014-02-28" (ISO format)


module Main;
import System;

var
	now: System.DateTime;
begin
	now := System.DateTime.Now;
	System.Console.WriteLine(now.ToString("yyyy-MM-dd");
	System.Console.WriteLine("{0}, {1}",now.DayOfWeek,now.ToString("MMMM dd, yyyy"));
end Main.


BEGIN # find Cullen and Woodall numbers and determine which are prime #
      # a Cullen number n is n2^2 + 1, Woodall number is n2^n - 1     #
    PR read "primes.incl.a68" PR                  # include prime utilities #
    PR precision 800 PR # set number of digits for Algol 68G LONG LONG INT #
    # returns the nth Cullen number #
    OP CULLEN = ( INT n )LONG LONG INT: n * LONG LONG INT(2)^n + 1;
    # returns the nth Woodall number #
    OP WOODALL = ( INT n )LONG LONG INT: CULLEN n - 2;

    # show the first 20 Cullen numbers #
    print( ( "1st 20 Cullen numbers:" ) );
    FOR n TO 20 DO
        print( ( " ", whole( CULLEN n, 0 ) ) )
    OD;
    print( ( newline ) );
    # show the first 20 Woodall numbers #
    print( ( "1st 20 Woodall numbers:" ) );
    FOR n TO 20 DO
        print( ( " ", whole( WOODALL n, 0 ) ) )
    OD;
    print( ( newline ) );
    BEGIN # first 2 Cullen primes #
        print( ( "Index of the 1st 2 Cullen primes:" ) );
        LONG LONG INT power of 2 := 1;
        INT prime count := 0;
        FOR n WHILE prime count < 2 DO
            power of 2 *:= 2;
            LONG LONG INT c n = ( n * power of 2 ) + 1;
            IF is probably prime( c n ) THEN
                prime count +:= 1;
                print( ( " ", whole( n, 0 ) ) )
            FI
        OD;
        print( ( newline ) )
    END;
    BEGIN # first 12 Woodall primes #
        print( ( "Index of the 1st 12 Woodall primes:" ) );
        LONG LONG INT power of 2 := 1;
        INT prime count := 0;
        FOR n WHILE prime count < 12 DO
            power of 2 *:= 2;
            LONG LONG INT w n = ( n * power of 2 ) - 1;
            IF is probably prime( w n ) THEN
                prime count +:= 1;
                print( ( " ", whole( n, 0 ) ) )
            FI
        OD;
        print( ( newline ) )
    END
END


cullen: function [n]->
    inc n * 2^n

woodall: function [n]->
    dec n * 2^n

print ["First 20 cullen numbers:" join.with:" " to [:string] map 1..20 => cullen]
print ["First 20 woodall numbers:" join.with:" " to [:string] map 1..20 => woodall]


# syntax: GAWK -f CULLEN_AND_WOODALL_NUMBERS.AWK
BEGIN {
    start = 1
    stop = 20
    printf("Cullen %d-%d:",start,stop)
    for (n=start; n<=stop; n++) {
      printf(" %d",n*(2^n)+1)
    }
    printf("\n")
    printf("Woodall %d-%d:",start,stop)
    for (n=start; n<=stop; n++) {
      printf(" %d",n*(2^n)-1)
    }
    printf("\n")
    exit(0)
}


print "First 20 Cullen numbers:"

for n = 1 to 20
	num = n * (2^n)+1
	print int(num); " ";
next

print : print
print "First 20 Woodall numbers:"

for n = 1 to 20
	num = n * (2^n)-1
	print int(num); " ";
next n
end


// Cullen and Woodall numbers. Nigel Galloway: January 14th., 2022
let Cullen,Woodall=let fG n (g:int)=(bigint g)*2I**g+n in fG 1I, fG -1I
Seq.initInfinite((+)1>>Cullen)|>Seq.take 20|>Seq.iter(printf "%A "); printfn ""
Seq.initInfinite((+)1>>Woodall)|>Seq.take 20|>Seq.iter(printf "%A "); printfn ""
Seq.initInfinite((+)1)|>Seq.filter(fun n->let mutable  n=Woodall n in Open.Numeric.Primes.MillerRabin.IsProbablePrime &n)|>Seq.take 12|>Seq.iter(printf "%A "); printfn ""
Seq.initInfinite((+)1)|>Seq.filter(fun n->let mutable  n=Cullen n in Open.Numeric.Primes.MillerRabin.IsProbablePrime &n)|>Seq.take 5|>Seq.iter(printf "%A "); printfn ""


USING: arrays kernel math math.vectors prettyprint ranges
sequences ;

20 [1..b] [ dup 2^ * 1 + ] map dup 2 v-n 2array simple-table.


package main

import (
    "fmt"
    big "github.com/ncw/gmp"
)

func cullen(n uint) *big.Int {
    one := big.NewInt(1)
    bn := big.NewInt(int64(n))
    res := new(big.Int).Lsh(one, n)
    res.Mul(res, bn)
    return res.Add(res, one)
}

func woodall(n uint) *big.Int {
    res := cullen(n)
    return res.Sub(res, big.NewInt(2))
}

func main() {
    fmt.Println("First 20 Cullen numbers (n * 2^n + 1):")
    for n := uint(1); n <= 20; n++ {
        fmt.Printf("%d ", cullen(n))
    }

    fmt.Println("\n\nFirst 20 Woodall numbers (n * 2^n - 1):")
    for n := uint(1); n <= 20; n++ {
        fmt.Printf("%d ", woodall(n))
    }

    fmt.Println("\n\nFirst 5 Cullen primes (in terms of n):")
    count := 0
    for n := uint(1); count < 5; n++ {
        cn := cullen(n)
        if cn.ProbablyPrime(15) {
            fmt.Printf("%d ", n)
            count++
        }
    }

    fmt.Println("\n\nFirst 12 Woodall primes (in terms of n):")
    count = 0
    for n := uint(1); count < 12; n++ {
        cn := woodall(n)
        if cn.ProbablyPrime(15) {
            fmt.Printf("%d ", n)
            count++
        }
    }
    fmt.Println()
}


findCullen :: Int -> Integer
findCullen n = toInteger ( n * 2 ^ n + 1 )

cullens :: [Integer]
cullens = map findCullen [1 .. 20]

woodalls :: [Integer]
woodalls = map (\i -> i - 2 ) cullens

main :: IO ( )
main = do
   putStrLn "First 20 Cullen numbers:"
   print cullens
   putStrLn "First 20 Woodall numbers:"
   print woodalls


using Lazy
using Primes

cullen(n, two = BigInt(2)) = n * two^n + 1
woodall(n, two = BigInt(2)) = n * two^n - 1
primecullens = @>> Lazy.range() filter(n -> isprime(cullen(n)))
primewoodalls = @>> Lazy.range() filter(n -> isprime(woodall(n)))

println("First 20 Cullen numbers: ( n × 2**n + 1)\n", [cullen(n, 2) for n in 1:20]) # A002064
println("First 20 Woodall numbers: ( n × 2**n - 1)\n", [woodall(n, 2) for n in 1:20]) # A003261
println("\nFirst 5 Cullen primes: (in terms of n)\n",  take(5, primecullens))  # A005849
println("\nFirst 12 Woodall primes: (in terms of n)\n", Int.(collect(take(12, primewoodalls)))) # A002234