const stext = ["one", "two", "three", "four", "five", "six", "seven", "eight", "nine"]
const teentext = ["eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen",
    "seventeen", "eighteen", "nineteen"]
const tenstext = ["ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy",
    "eighty", "ninety"]
const ordstext = ["million", "billion", "trillion", "quadrillion", "quintillion", "sextillion",
    "septillion", "octillion", "nonillion", "decillion", "undecillion", "duodecillion",
    "tredecillion", "quattuordecillion", "quindecillion", "sexdecillion", "septendecillion",
    "octodecillion", "novemdecillion", "vigintillion"]

function normalize_digits!(a::Array{T,1}) where T<:Integer
    while 0 < length(a) && a[end] == 0
        pop!(a)
    end
    length(a)
end

function digits2text!(d::Array{T,1}, use_short_scale=true) where T<:Integer
    ndig = normalize_digits!(d)
    0 < ndig || return ""
    if ndig < 7
        s = ""
        if 3 < ndig
            t = digits2text!(d[1:3])
            s = digits2text!(d[4:end]) * " thousand"
            0 < length(t) || return s
            return occursin(t, "and") ? s * " " * t : s * " and " * t
        end
        if ndig == 3
            s *= stext[pop!(d)] * " hundred"
            ndig = normalize_digits!(d)
            0 < ndig || return s
            s *= " and "
        end
        1 < ndig || return s*stext[pop!(d)]
        j, i = d
        j ≠ 0 || return s*tenstext[i]
        i ≠ 1 || return s*teentext[j]
        return s*tenstext[i] * "-" * stext[j]
    end
    s = digits2text!(d[1:6])
    d = d[7:end]
    dgrp = use_short_scale ? 3 : 6
    ord = 0
    while dgrp < length(d)
        ord += 1
        t = digits2text!(d[1:dgrp])
        d = d[(dgrp+1):end]
        0 < length(t) || continue
        t = t * " " * ordstext[ord]
        s = length(s) == 0 ? t : t * " " * s
    end
    ord += 1
    t = digits2text!(d) * " " * ordstext[ord]
    0 < length(s) || return t
    t * " " * s
end

function num2text(n::T, use_short_scale=true) where T<:Integer
    -1 < n || return "minus "*num2text(-n, use_short_scale)
    0 < n || return "zero"
    toobig = use_short_scale ? big(10)^66 : big(10)^126
    n < toobig || return "too big to say"
    digits2text!(digits(n, base=10), use_short_scale)
end


// version 1.1.2

val oneNames = listOf(
        "", "one", "two", "three", "four",
        "five", "six", "seven", "eight", "nine",
        "ten", "eleven", "twelve", "thirteen", "fourteen",
        "fifteen", "sixteen", "seventeen", "eighteen", "nineteen")
val tenNames = listOf(
        "", "", "twenty", "thirty", "forty",
        "fifty", "sixty", "seventy", "eighty", "ninety")
val thousandNames = listOf(
        "", "thousand", "million", "billion", "trillion", "quadrillion",
        "quintillion")

fun numToText(n: Long, uk: Boolean = false): String {
    if (n == 0L) return "zero"
    val neg = n < 0L
    val maxNeg = n == Long.MIN_VALUE
    var nn = if (maxNeg) -(n + 1) else if (neg) -n else n
    val digits3 = IntArray(7)
    for (i in 0..6) {  // split number into groups of 3 digits from the right
        digits3[i] = (nn % 1000).toInt()
        nn /= 1000
    }
    if (maxNeg) digits3[0]++

    fun threeDigitsToText(number: Int): String {
        val sb = StringBuilder()
        if (number == 0) return ""
        val hundreds = number / 100
        val remainder = number % 100
        if (hundreds > 0) {
            sb.append(oneNames[hundreds], " hundred")
            if (remainder > 0) sb.append(if (uk) " and " else " ")
        }
        if (remainder > 0) {
            val tens = remainder / 10
            val units = remainder % 10
            if (tens > 1) {
                sb.append(tenNames[tens])
                if (units > 0) sb.append("-", oneNames[units])
            } else sb.append(oneNames[remainder])
        }
        return sb.toString()
    }

    val triplets = Array(7) { threeDigitsToText(digits3[it]) }
    var text = triplets[0]
    var andNeeded = uk && digits3[0] in 1..99
    for (i in 1..6) {
        if (digits3[i] > 0) {
            var text2 = triplets[i] + " " + thousandNames[i]
            if (text != "") {
                text2 += if (andNeeded) " and " else ", "
                andNeeded = false
            } else andNeeded = uk && digits3[i] in 1..99
            text = text2 + text
        }
    }
    return (if (neg) "minus " else "") + text
}

fun main() {
    val exampleNumbers = longArrayOf(
            0, 1, 7, 10, 18, 22, 67, 99, 100, 105, 999, -1056, 1000005000,
            2074000000, 1234000000745003L, Long.MIN_VALUE
    )
    println("Using US representation:")
    for (i in exampleNumbers) println("${"%20d".format(i)} = ${numToText(i)}")
    println()
    println("Using UK representation:")
    for (i in exampleNumbers) println("${"%20d".format(i)} = ${numToText(i, true)}")
}


global outnum$
dim ones$(20),tens$(9),gr$(5),group(5)
for a = 0 to 19
    read a$:ones$(a)=a$
next a
for a = 1 to 8
    read a$:tens$(a)=a$
next a

[start]
    redim gr$(5)
    redim group(5)

    input "Enter a number (nonzero positive integers only less than 1 quadrillion, no commas): ";num$

    num$=trim$(num$)
    numVal=int(val(num$))
    if numVal=0 or numVal>999999999999999 then print "Ended" : end

    numParse = numVal
    numLen = len(str$(numParse))

    if numLen<=15 then groupCount=5
    if numLen<=12 then groupCount=4
    if numLen<=9 then groupCount=3
    if numLen<=6 then groupCount=2
    if numLen<=3 then groupCount=1

    if numLen>12 and numLen<=15 then
        group(5)=int(numParse/1000000000000)
        call convert group(5)," trillion"
        gr$(5)=outnum$
        numParse=nP(numParse,12)
        numLen=len(str$(numParse))
    end if

    if numLen>9 and numLen<=12 then
        group(4)=int(numParse/1000000000)
        call convert group(4)," billion"
        gr$(4)=outnum$
        numParse=nP(numParse,9)
        numLen=len(str$(numParse))
    end if

    if numLen>6 and numLen<=9 then
        group(3)=int(numParse/1000000)
        call convert group(3)," million"
        gr$(3)=outnum$
        numParse=nP(numParse,6)
        numLen=len(str$(numParse))
    end if

    if numLen>3 and numLen<=6 then
        group(2)=int(numParse/1000)
        call convert group(2)," thousand"
        gr$(2)=outnum$
        numParse=nP(numParse,3)
        numLen=len(str$(numParse))
    end if

    if numLen<=3 then
        group(1)=numParse
        call convert group(1),""
        gr$(1)=outnum$
        numLen=len(str$(numParse))
    end if

    print
    for a=groupCount to 1 step -1
        print gr$(a);" ";
    next a
    print
    print

goto [start]

sub convert num, dem$
    outnum$=""
    for a=len(str$(num)) to 1 step -1
        b$=mid$(str$(num),a,1)
        c=val(b$)
        d=len(str$(num))-a+1
        select case
            case d=1
                outnum$=ones$(c)
            case d=2
                if c<2 then
                    outnum$=ones$(val(right$(str$(num),2)))
                else
                    if c>=2 and val(right$(str$(num),1))<>0 then
                        outnum$=tens$(c-1)+"-"+outnum$
                    else
                        outnum$=tens$(c-1)
                    end if
                end if
            case d=3
                if c<>0 then outnum$=ones$(c)+" hundred "+outnum$
        end select
    next a
    outnum$=outnum$+dem$
end sub

function nP(num,L)
    nP=val(right$(str$(num),L))
end function

data "","one","two","three","four","five","six","seven","eight","nine"
data "ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen"
data "twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety"


make "numbers {one two three four five six seven eight nine ten
     eleven twelve thirteen fourteen fifteen sixteen seventeen eighteen nineteen}

make "tens {twenty thirty forty fifty sixty seventy eighty ninety}@2

make "thou [[] thousand million billion trillion]		; expand as desired

to to.english.thou :n :thou
  if :n = 0    [output []]
  if :n < 20   [output sentence item :n :numbers  first :thou]
  if :n < 100  [output (sentence item int :n/10 :tens
                                 to.english.thou modulo :n 10 [[]]
                                 first :thou)]
  if :n < 1000 [output (sentence item int :n/100 :numbers
                                 "hundred
                                 to.english.thou modulo :n 100 [[]]
                                 first :thou)]
  output (sentence to.english.thou int :n/1000 butfirst :thou
                   to.english.thou modulo :n 1000 :thou)
end

to to.english :n
  if :n = 0 [output "zero]
  if :n > 0 [output to.english.thou :n :thou]
  [output sentence "negative to.english.thou minus :n :thou]
end

print to.english 1234567   ; one million two hundred thirty four thousand five hundred sixty seven


words = {"one ", "two ", "three ", "four ", "five ", "six ", "seven ", "eight ", "nine "}
levels = {"thousand ", "million ", "billion ", "trillion ", "quadrillion ", "quintillion ", "sextillion ", "septillion ", "octillion ", [0] = ""}
iwords = {"ten ", "twenty ", "thirty ", "forty ", "fifty ", "sixty ", "seventy ", "eighty ", "ninety "}
twords = {"eleven ", "twelve ", "thirteen ", "fourteen ", "fifteen ", "sixteen ", "seventeen ", "eighteen ", "nineteen "}

function digits(n)
  local i, ret = -1
  return function()
    i, ret = i + 1, n % 10
	if n > 0 then
      n = math.floor(n / 10)
	  return i, ret
	end
  end
end

level = false
function getname(pos, dig) --stateful, but effective.
  level = level or pos % 3 == 0
  if(dig == 0) then return "" end
  local name = (pos % 3 == 1 and iwords[dig] or words[dig]) .. (pos % 3 == 2 and "hundred " or "")
  if(level) then name, level = name .. levels[math.floor(pos / 3)], false end
  return name
end

local val, vword = io.read() + 0, ""

for i, v in digits(val) do
  vword = getname(i, v) .. vword
end

for i, v in ipairs(words) do
  vword = vword:gsub("ty " .. v, "ty-" .. v)
  vword = vword:gsub("ten " .. v, twords[i])
end

if #vword == 0 then print "zero" else print(vword) end


number_name := n -> convert(n, english)
number_name(2001);
                       "two thousand one"


small = "zero"["one", "two", "three", "four", "five", "six", "seven",
  "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen",
  "fifteen", "sixteen", "seventeen", "eighteen",
  "nineteen"]; tens = # <> "-" & /@ {"twenty", "thirty", "forty",
   "fifty", "sixty", "seventy", "eighty", "ninety"};
big = Prepend[
   " " <> # & /@ {"thousand", "million", "billion", "trillion",
     "quadrillion", "quintillion", "sextillion", "septillion",
     "octillion", "nonillion", "decillion", "undecillion",
     "duodecillion", "tredecillion"}, ""];
name[n_Integer] := "negative " <> name[-n] /; n < 0;
name[n_Integer] := small[[n]] /; 0 <= n < 20;
name[n_Integer] :=
  StringTrim[tens[[#1 - 1]] <> small[[#2]] & @@ IntegerDigits[n],
    "-zero"] /; 10 <= n < 100;
name[n_Integer] :=
 StringTrim[
   small[[#1]] <> " hundred and " <> [email protected]#2 & @@
    IntegerDigits[n, 100], " and zero"] /; 100 <= n < 1000;
name[n_Integer] :=
 [email protected]
  Riffle[Select[
    MapThread[StringJoin, {name /@ #, [email protected][[;; [email protected]#]]}] &@
     IntegerDigits[n, 1000], StringFreeQ[#, "zero"] &], ","];


fn numToEng num =
(
	num = num as integer -- convert to int
	local originalNumber = num -- store the initial value, to check if it was negative afterwards

	num = abs num -- make positive
	local numStr = num as string -- store as string to check the length

	local nonFirstDigits = (if numStr.count > 3 then ((substring numStr ((if mod numStr.count 3 ==0 then 3 else mod numStr.count 3)+1) -1)) else "0") -- this is the string of the number without the beginning, i.e 123456 will give 456, 12035 will give 2035
	local singleDigits = #("One","Two","Three","Four","Five","Six","Seven","Eight","Nine")
	local ElevenTwenty = #("Eleven","Twelve","Thirteen","Fourteen","Fifteen","Sixteen","Seventeen","Eighteen","Nineteen")
	local tens = #("Ten","Twenty","Thirty","Forty","Fifty","Sixty","Seventy","Eighty","Ninety")
	local big = #("Hundred","Thousand","Million","Billion")
	local ret = "" -- this is the value to be returned

	case of
	(
		(num == 0 ): ret += "Zero" -- number is zero
		(num < 10): ret += singleDigits[num] -- number is not and smaller than 10
		(num == 10): ret += tens[1] -- number is 10
		(num < 20): ret += elevenTwenty[abs(10-num)] -- number is between 11 and 19
		(num <= 90 and mod num 10 == 0): ret += tens[num/10] -- number is >= 20 and <= 90 and is dividable by 10
		(num < 100): ret += (numToEng (floor(num/10.0)*10) +" "+ numtoEng (num-(floor(num/10.0))*10)) -- number is >= 20, < 100 and is not dividable by 10
		(num < 1000): ret += (singledigits[floor(num/100) as integer] + " "+big[1]+ (if mod num 100 != 0 then (" and "+numtoeng (num-(floor(num/100.0)*100))) else "")) -- number is >= 100, < 1000
		(num >= 1000): ret += -- number is >= 1000
			(
				numtoeng (substring numStr 1 (if mod numStr.count 3 ==0 then 3 else mod numStr.count 3)) + \
				" " + big[1+((numStr.count-1)/3)] + (if nonFirstDigits as integer == 0 then "" else (if nonFirstDigits as integer < 100 then " and " else ", ")) + \
				(if (mod num 1000 == 0) then "" else (numtoeng nonFirstDigits))

			)
	)

	if originalNumber < 0 and (substring ret 1 8) != "Negative" do ret = ("Negative "+ret) -- if number is negative
	ret = (toupper ret[1]) + (tolower (substring ret 2 -1)) -- make the first char uppercase and rest lowercase
	return ret
)


singles = " one two three four five six seven eight nine ".split
teens = "ten eleven twelve thirteen fourteen fifteen sixteen seventeen eighteen nineteen ".split
tys = "  twenty thirty forty fifty sixty seventy eighty ninety".split
ions = "thousand million billion".split

numberName = function(n)
    if n == 0 then return "zero"
    a = abs(n)
    r = ""  // (result)
    for u in ions
        h = a % 100
        if h > 0 and h < 10 then r = singles[h] + " " + r
        if h > 9 and h < 20 then r = teens[h-10] + " " + r
        if h > 19 and h < 100 then r = tys[h/10] + "-"*(h%10>0) + singles[h%10] + " " + r
        h = floor((a % 1000) / 100)
        if h then r = singles[h] + " hundred " + r
        a = floor(a / 1000)
        if a == 0 then break
        if a % 1000 > 0 then r = u + " " + r
    end for
    if n < 0 then r = "negative " + r
    return r
end function

// Test cases:
for n in [-1234, 0, 7, 42, 4325, 1000004, 214837564]
    print n + ": " + numberName(n)
end for


import strutils, algorithm

const
  tens = ["", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy",
          "eighty", "ninety"]
  small = ["zero", "one", "two", "three", "four", "five", "six", "seven",
           "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen",
           "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"]
  huge = ["", "", "million", "billion", "trillion", "quadrillion",
          "quintillion", "sextillion", "septillion", "octillion", "nonillion",
          "decillion"]

# Forward reference.
proc spellInteger(n: int64): string

proc nonzero(c: string; n: int64; connect = ""): string =
  if n == 0: "" else: connect & c & spellInteger(n)

proc lastAnd(num: string): string =
  if ',' in num:
    let pos =  num.rfind(',')
    var (pre, last) = if pos >= 0: (num[0 ..< pos], num[pos+1 .. num.high])
                      else: ("", num)
    if " and " notin last: last = " and" & last
    result = [pre, ",", last].join()
  else:
    result = num

proc big(e, n: int64): string =
  if e == 0:
    spellInteger(n)
  elif e == 1:
    spellInteger(n) & " thousand"
  else:
    spellInteger(n) & " " & huge[e]

iterator base1000Rev(n: int64): int64 =
  var n = n
  while n != 0:
    let r = n mod 1000
    n = n div 1000
    yield r

proc spellInteger(n: int64): string =
  if n < 0:
    "minus " & spellInteger(-n)
  elif n < 20:
    small[int(n)]
  elif n < 100:
    let a = n div 10
    let b = n mod 10
    tens[int(a)] & nonzero("-", b)
  elif n < 1000:
    let a = n div 100
    let b = n mod 100
    small[int(a)] & " hundred" & nonzero(" ", b, " and")
  else:
    var sq = newSeq[string]()
    var e = 0
    for x in base1000Rev(n):
      if x > 0: sq.add big(e, x)
      inc e
    reverse sq
    lastAnd(sq.join(", "))

for n in [0, -3, 5, -7, 11, -13, 17, -19, 23, -29]:
  echo align($n, 4)," -> ",spellInteger(n)

var n = 201021002001
while n != 0:
  echo align($n, 14)," -> ",spellInteger(n)
  n = n div -10


class NumberNames {
  small : static : String[];
  tens : static : String[];
  big : static : String[];

  function : Main(args : String[]) ~ Nil {
    small := ["one", "two", "three", "four", "five", "six", "seven",
      "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen",
      "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"];
    tens := ["twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"];
    big := ["thousand", "million", "billion", "trillion"];

    Int2Text(900000001)->PrintLine();
    Int2Text(1234567890)->PrintLine();
    Int2Text(-987654321)->PrintLine();
    Int2Text(0)->PrintLine();
  }

  function : native : Int2Text(number : Int) ~ String {
    num := 0;
    outP := "";
          unit := 0;
          tmpLng1 := 0;

    if (number = 0) {
      return "zero";
    };

    num := number->Abs();

    while(true) {
      tmpLng1 := num % 100;
      if (tmpLng1 >= 1 & tmpLng1 <= 19) {
        tmp := String->New();
        tmp->Append(small[tmpLng1 - 1]);
        tmp->Append(" ");
        tmp->Append(outP);
        outP := tmp;
      }
      else if (tmpLng1 >= 20 & tmpLng1 <= 99) {
        if (tmpLng1 % 10 = 0) {
          tmp := String->New();
          tmp->Append(tens[(tmpLng1 / 10) - 2]);
          tmp->Append(" ");
          tmp->Append(outP);
          outP := tmp;
        }
        else {
          tmp := String->New();
          tmp->Append(tens[(tmpLng1 / 10) - 2]);
          tmp->Append( "-");
          tmp->Append(small[(tmpLng1 % 10) - 1]);
          tmp->Append(" ");
          tmp->Append(outP);
          outP := tmp;
        };
      };

      tmpLng1 := (num % 1000) / 100;
      if (tmpLng1 <> 0) {
        tmp := String->New();
        tmp->Append(small[tmpLng1 - 1]);
        tmp->Append(" hundred ");
        tmp->Append(outP);
        outP := tmp;
      };

      num /= 1000;
      if (num = 0) {
        break;
      };

      tmpLng1 := num % 1000;
      if (tmpLng1 <> 0) {
        tmp := String->New();
        tmp->Append(big[unit]);
        tmp->Append(" ");
        tmp->Append(outP);
        outP := tmp;
      };
      unit+=1;
    };

    if (number < 0) {
      tmp := String->New();
      tmp->Append("negative ");
      tmp->Append(outP);
      outP := tmp;
    };

    return outP->Trim();
  }
}


MODE ℵ SIMPLEOUT = UNION (≮ℒ INT≯, ≮ℒ REAL≯, ≮ℒ COMPL≯, BOOL, ≮ℒ BITS≯, CHAR, [ ] CHAR);
PROC ℓ cos = (ℒ REAL x) ℒ REAL: ¢ a ℒ real value close to the cosine of 'x' ¢;

PROC ℓ complex cos = (ℒ COMPL z) ℒ COMPL: ¢ a ℒ complex value close to the cosine of 'z' ¢;

PROC ℓ arccos = (ℒ REAL x) ℒ REAL: ¢ if ABS x ≤ ℒ 1, a ℒ real value close
      to the inverse cosine of 'x', ℒ 0 ≤ ℒ arccos (x) ≤ ℒ pi ¢;


#import <Foundation/Foundation.h>

int main() {
  @autoreleasepool {

    NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
    numberFormatter.numberStyle = NSNumberFormatterSpellOutStyle;
    numberFormatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];

    for (NSNumber *n in @[@900000001, @1234567890, @-987654321, @0, @3.14]) {
      NSLog(@"%@", [numberFormatter stringFromNumber:n]);
    }

  }
  return 0;
}


let div_mod n d = (n / d, n mod d)
let join = String.concat ", " ;;

let rec nonzero = function
  | _, 0 -> ""
  | c, n -> c ^ (spell_integer n)

and tens n =
  [| ""; ""; "twenty"; "thirty"; "forty"; "fifty";
             "sixty"; "seventy"; "eighty"; "ninety" |].(n)

and small n =
  [| "zero"; "one"; "two"; "three"; "four"; "five";
     "six"; "seven"; "eight"; "nine"; "ten"; "eleven";
     "twelve"; "thirteen"; "fourteen"; "fifteen";
     "sixteen";"seventeen"; "eighteen"; "nineteen" |].(n)

and bl = [| ""; ""; "m"; "b"; "tr"; "quadr"; "quint";
                    "sext"; "sept"; "oct"; "non"; "dec" |]

and big = function
  | 0, n -> (spell_integer n)
  | 1, n -> (spell_integer n) ^ " thousand"
  | e, n -> (spell_integer n) ^ " " ^ bl.(e) ^ "illion"

and uff acc = function
  | 0 -> List.rev acc
  | n ->
      let a, b = div_mod n 1000 in
      uff (b::acc) a

and spell_integer = function
  | n when n < 0 -> invalid_arg "spell_integer: negative input"
  | n when n < 20 -> small n
  | n when n < 100 ->
      let a, b = div_mod n 10 in
      (tens a) ^ nonzero("-", b)
  | n when n < 1000 ->
      let a, b = div_mod n 100 in
      (small a) ^ " hundred" ^ nonzero(" ", b)
  | n ->
      let seg = (uff [] n) in
      let _, segn =
        (* just add the index of the item in the list *)
        List.fold_left
          (fun (i,acc) v -> (succ i, (i,v)::acc))
          (0,[])
          seg
      in
      let fsegn =
        (* remove right part "zero" *)
        List.filter
          (function (_,0) -> false | _ -> true)
          segn
      in
      join(List.map big fsegn)
;;


Eng(n:int)={
	my(tmp,s="");
	if (n >= 1000000,
		tmp = n\1000000;
		s = Str(s, Eng(tmp), " million");
		n -= tmp * 1000000;
		if (!n, return(s));
		s = Str(s, " ")
	);
	if (n >= 1000,
		tmp = n\1000;
		s = Str(s, Eng(tmp), " thousand");
		n -= tmp * 1000;
		if (!n, return(s));
		s = Str(s, " ")
	);
	if (n >= 100,
		tmp = n\100;
		s = Str(s, Edigit(tmp), " hundred");
		n -= tmp * 100;
		if (!n, return(s));
		s = Str(s, " ")
	);
	if (n < 20,
		return (Str(s, ["one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "ninteen"][n]))
	);
	tmp = n\10;
	s = Str(s, [0, "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"][tmp]);
	n -= tmp * 10;
	if (n, Str(s, "-", Edigit(n)), s)
};
Edigit(n)={
	["one", "two", "three", "four", "five", "six", "seven", "eight", "nine"][n]
};


# Field names begin with $ so $1 is the first field, $2 the second and $NF the
# last.  $0 references the entire input record.
#
# Function and variable names are case sensitive and begin with an alphabetic
# character or underscore followed by any number of: a-z, A-Z, 0-9, _
#
# The awk language is type less; variables are either string or number
# depending upon usage.  Variables can be coerced to string by concatenating ""
# or to number by adding zero.  For example:
#   str = x ""
#   num = x + 0
#
# Below are the names of the built-in functions, built-in variables and other
# reserved words in the awk language separated into categories.  Also shown are
# the names of gawk's enhancements.
#
# patterns:
#   BEGIN END
#   BEGINFILE ENDFILE (gawk)
# actions:
#   break continue delete do else exit for if in next return while
#   case default switch (gawk)
# arithmetic functions:
#   atan2 cos exp int log rand sin sqrt srand
# bit manipulation functions:
#   and compl lshift or rshift xor (gawk)
# i18n functions:
#   bindtextdomain dcgettext dcngettext (gawk)
# string functions:
#   gsub index length match split sprintf sub substr tolower toupper
#   asort asorti gensub patsplit strtonum (gawk)
# time functions:
#   mktime strftime systime (gawk)
# miscellaneous functions:
#   isarray (gawk)
# variables:
#   ARGC ARGV CONVFMT ENVIRON FILENAME FNR FS NF NR OFMT OFS ORS RLENGTH RS RSTART SUBSEP
#   ARGIND BINMODE ERRNO FIELDWIDTHS FPAT FUNCTAB IGNORECASE LINT PREC PROCINFO ROUNDMODE RT SYMTAB TEXTDOMAIN (gawk)
# function definition:
#   func function
# input-output:
#   close fflush getline nextfile print printf system
# pre-processor directives:
#   @include @load (gawk)
# special files:
#   /dev/stdin /dev/stdout /dev/error


DEF PROC_foo(bar, baz$(), quux%, RETURN fred%, RETURN jim%)


O_RDONLY, O_WRONLY, or O_RDWR. O_CREAT, O_EXCL, O_NOCTTY, and O_TRUNC


public enum Planet {
    Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune
}

[Flags]
public enum Days {
    None = 0,
    Sunday = 1,
    Monday = 2,
    Tuesday = 4,
    Wednesday = 8,
    Thursday = 16,
    Friday = 32,
    Saturday = 64,
    Workdays = Monday | Tuesday | Wednesday | Thursday | Friday
    AllWeek = Sunday | Saturday | Workdays
}


program NumberNames(output);

const
  smallies: array[1..19] of string =
              ('one', 'two', 'three', 'four', 'five', 'six',
               'seven', 'eight', 'nine', 'ten', 'eleven',
      	       'twelve', 'thirteen', 'fourteen', 'fifteen',
	       'sixteen', 'seventeen', 'eighteen', 'nineteen');
  tens: array[2..9] of string =
          ('twenty', 'thirty', 'forty', 'fifty',
           'sixty', 'seventy', 'eighty', 'ninety');

function domaxies(number: int64): string;
  const
    maxies: array[0..5] of string =
              (' thousand', ' million', ' billion',
               ' trillion', ' quadrillion', ' quintillion');
  begin
    domaxies := '';
    if number >= 0 then
      domaxies := maxies[number];
  end;

function doHundreds( number: int64): string;
  begin
    doHundreds := '';
    if number > 99 then
    begin
      doHundreds := smallies[number div 100];
      doHundreds := doHundreds + ' hundred';
      number := number mod 100;
      if number > 0 then
        doHundreds := doHundreds + ' and ';
    end;
    if number >= 20 then
    begin
      doHundreds := doHundreds + tens[number div 10];
      number := number mod 10;
      if number > 0 then
        doHundreds := doHundreds + '-';
    end;
    if (0 < number) and (number < 20) then
      doHundreds := doHundreds + smallies[number];
  end;

function spell(number: int64): string;
  var
    scaleFactor: int64 = 1000000000000000000;
    maxieStart, h: int64;
  begin
    spell := '';
    maxieStart := 5;
    if number < 20 then
      spell := smallies[number];
    while scaleFactor > 0 do
    begin
      if number > scaleFactor then
      begin
	h := number div scaleFactor;
	spell := spell + doHundreds(h) + domaxies(maxieStart);
	number := number mod scaleFactor;
	if number > 0 then
	  spell := spell + ', ';
      end;
      scaleFactor := scaleFactor div 1000;
      dec(maxieStart);
    end;
  end;

begin
  writeln(99, ': ', spell(99));
  writeln(234, ': ', spell(234));
  writeln(7342, ': ', spell(7342));
  writeln(32784, ': ', spell(32784));
  writeln(234345, ': ', spell(234345));
  writeln(2343451, ': ', spell(2343451));
  writeln(23434534, ': ', spell(23434534));
  writeln(234345456, ': ', spell(234345456));
  writeln(2343454569, ': ', spell(2343454569));
  writeln(2343454564356, ': ', spell(2343454564356));
  writeln(2345286538456328, ': ', spell(2345286538456328));
end.


var xs = Array.Empty(10)
var ys = Array(1, 2, 3)
var str = xs.ToString()

type Maybe = Some(x) or None()
var x = Maybe.Some(42)


\ fetch and store usage examples
VARIABLE MYINT1
VARIABLE MYINT2
2VARIABLE DOUBLE1
2VARIABLE DOUBLE2

MYINT1 @  MYINT2 !
MYDOUBLE [email protected] MYDOUBLE 2!

\ record example using this convention

1000000 RECORDS PERSONEL

1 PERSONEL [email protected]  \ read Record 1 and put pointer on data stack

HR_RECORD 992 PERSONEL RECORD! \ store HR_RECORD


// version 1.0.6

const val SOLAR_DIAMETER = 864938

enum class Planet { MERCURY, VENUS, EARTH, MARS, JUPITER, SATURN, URANUS, NEPTUNE, PLUTO } // Yeah, Pluto!

class Star(val name: String) {
    fun showDiameter() {
        println("The diameter of the $name is ${"%,d".format(SOLAR_DIAMETER)} miles")
    }
}

class SolarSystem(val star: Star) {
    private val planets = mutableListOf<Planet>()  // some people might prefer _planets

    init {
       for (planet in Planet.values()) planets.add(planet)
    }

    fun listPlanets() {
       println(planets)
    }
}

fun main(args: Array<String>) {
    val sun = Star("sun")
    val ss = SolarSystem(sun)
    sun.showDiameter()
    println("\nIts planetary system comprises : ")
    ss.listPlanets()
}


use Lingua::EN::Numbers 'num2en';

print num2en(123456789), "\n";


--
-- demo\rosetta\Number_names.exw
-- -----------------------------
--
with javascript_semantics

constant twenties = {"zero","one","two","three","four","five","six","seven","eight","nine","ten",
    "eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen"}

function twenty(integer n)
    return twenties[mod(n,20)+1]
end function

constant decades = {"twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety"}

function decade(integer n)
    return decades[mod(n,10)-1]
end function

function hundred(integer n)
    if n<20 then
        return twenty(n)
    elsif mod(n,10)=0 then
        return decade(mod(floor(n/10),10))
    end if
    return decade(floor(n/10)) & '-' & twenty(mod(n,10))
end function

function thousand(integer n, string withand)
    if n<100 then
        return withand & hundred(n)
    elsif mod(n,100)=0 then
        return withand & twenty(floor(n/100))&" hundred"
    end if
    return twenty(floor(n/100)) & " hundred and " & hundred(mod(n,100))
end function

constant orders = {{power(10,15),"quadrillion"},
                   {power(10,12),"trillion"},
                   {power(10,9),"billion"},
                   {power(10,6),"million"},
                   {power(10,3),"thousand"}}

function triplet(atom n)
    string res = ""
    for i=1 to length(orders) do
        {atom order, string name} = orders[i]
        atom high = floor(n/order),
             low = mod(n,order)
        if high!=0 then
            res &= thousand(high,"")&' '&name
        end if
        n = low
        if low=0 then exit end if
        if length(res) and high!=0 then
            res &= ", "
        end if
    end for
    if n!=0 or res="" then
        res &= thousand(floor(n),iff(res=""?"":"and "))
        n = abs(mod(n,1))
        if n>1e-6 then
            res &= " point"
            for i=1 to 10 do
                integer t = floor(n*10.0000001)
                res &= ' '&twenties[t+1]
                n = n*10-t
                if abs(n)<1e-6 then exit end if
            end for
        end if
    end if
    return res
end function

global
function spell(atom n)
    string res = ""
    if n<0 then
        res = "minus "
        n = -n
    end if
    res &= triplet(n)
    return res
end function

global
constant samples = {99, 300, 310, 417,1_501, 12_609, 200000000000100, 999999999999999,
                    -123456787654321,102003000400005,1020030004,102003,102,1,0,-1,-99,
                    -1501,1234,12.34,10000001.2,1E-3,-2.7182818,
                    201021002001,-20102100200,2010210020,-201021002,20102100,-2010210,
                    201021,-20102,2010,-201,20,-2}

global
function smartp(atom n)
    if n=floor(n) then return sprintf("%d",n) end if
    string res = sprintf("%18.8f",n)
    if find('.',res) then
        res = trim_tail(res,"0")
    end if
    return res
end function

procedure main()
    for i=1 to length(samples) do
        atom si = samples[i]
        printf(1,"%18s %s\n",{smartp(si),spell(si)})
    end for
end procedure

if include_file()=1 then
    main()
    {} = wait_key()
end if


with Ada.Text_IO;procedure Self is Q:Character:='"';A:String:="with Ada.Text_IO;procedure Self is Q:Character:='';A:String:=;B:String:=A(1..49)&Q&A(50..61)&Q&A&Q&A(62..A'Last);C:String:=Ada.Text_IO.Get_Line;begin Ada.Text_IO.Put_Line(Boolean'Image(B=C));end Self;";B:String:=A(1..49)&Q&A(50..61)&Q&A&Q&A(62..A'Last);C:String:=Ada.Text_IO.Get_Line;begin Ada.Text_IO.Put_Line(Boolean'Image(B=C));end Self;


$orderOfMag = array('Hundred', 'Thousand,', 'Million,', 'Billion,', 'Trillion,');
$smallNumbers = array('Zero', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine',
'Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen');
$decades = array('', '', 'Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninety');

function NumberToEnglish($num, $count = 0){
   global $orderOfMag, $smallNumbers, $decades;
   $isLast = true;
   $str = '';

   if ($num < 0){
      $str = 'Negative ';
      $num = abs($num);
   }

   (int) $thisPart = substr((string) $num, -3);

   if (strlen((string) $num) > 3){
      // Number still too big, work on a smaller chunk
      $str .= NumberToEnglish((int) substr((string) $num, 0, strlen((string) $num) - 3), $count + 1);
      $isLast = false;
   }

   // do translation stuff
   if (($count == 0 || $isLast) && ($str == '' || $str == 'Negative '))
      // This is either a very small number or the most significant digits of the number. Either way we don't want a preceeding "and"
      $and = '';
   else
      $and = ' and ';

   if ($thisPart > 99){
      // Hundreds part of the number chunk
      $str .= ($isLast ? '' : ' ') . "{$smallNumbers[$thisPart/100]} {$orderOfMag[0]}";

      if(($thisPart %= 100) == 0){
         // There is nothing else to do for this chunk (was a multiple of 100)
         $str .= " {$orderOfMag[$count]}";
         return $str;
      }
      $and = ' and ';  // Set up our and string to the word "and" since there is something in the hundreds place of this chunk
   }

   if ($thisPart >= 20){
      // Tens part of the number chunk
      $str .= "{$and}{$decades[$thisPart /10]}";
      $and = ' '; // Make sure we don't have any extranious "and"s
      if(($thisPart %= 10) == 0)
         return $str . ($count != 0 ? " {$orderOfMag[$count]}" : '');
   }

   if ($thisPart < 20 && $thisPart > 0)
      // Ones part of the number chunk
      return $str . "{$and}{$smallNumbers[(int) $thisPart]} " . ($count != 0 ? $orderOfMag[$count] : '');
   elseif ($thisPart == 0 && strlen($thisPart) == 1)
      // The number is zero
      return $str . "{$smallNumbers[(int)$thisPart]}";
}


(display dialog "" default answer "")'s text returned = (do shell script ("osadecompile " & (path to me)'s POSIX path's quoted form))


Narcissist(Input) {
	FileRead, Source, % A_ScriptFullPath
	return Input == Source ? "accept" : "reject"
}


INPUT a$:PRINT -(a$=$(PAGE+34)+$(PAGE+33)):REM INPUT a$:PRINT -(a$=$(PAGE+34)+$(PAGE+33)):REM


extern void*stdin;main(){ char*p = "extern void*stdin;main(){ char*p = %c%s%c,a[300],b[300];sprintf(a,p,34,p,34);fgets(b,300,stdin);putchar(48+!strcmp(a,b)); }",a[300],b[300];sprintf(a,p,34,p,34);fgets(b,300,stdin);putchar(48+!strcmp(a,b)); }


using System;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
namespace Narcisisst
{
	class Program
	{
		public static void Main(string[] args)
		{
			const string path = @"E:\Narcisisst";
			string[] thisFile = Directory.GetFiles(path , "Program.cs");
			StringBuilder sb = new StringBuilder();

				foreach (string readLine in File.ReadLines(thisFile[0]))
				{
					sb.Append(readLine);
					sb.Append("\n");
				}

			Console.WriteLine(sb);
			string input =String.Empty;
			       	input = Console.ReadLine();
			       	Console.WriteLine((Regex.IsMatch(sb.ToString(),input))?"accept":"reject");
			       	Console.ReadKey();
			 }
	}
}


(de numName (N)
   (cond
      ((=0 N) "zero")
      ((lt0 N) (pack "minus " (numName (- N))))
      (T (numNm N)) ) )

(de numNm (N)
   (cond
      ((=0 N))
      ((> 14 N)
         (get '("one" "two" "three" "four" "five" "six" "seven" "eight" "nine" "ten" "eleven" "twelve" "thirteen") N) )
      ((= 15 N) "fifteen")
      ((= 18 N) "eighteen")
      ((> 20 N) (pack (numNm (% N 10)) "teen"))
      ((> 100 N)
         (pack
            (get '("twen" "thir" "for" "fif" "six" "seven" "eigh" "nine") (dec (/ N 10)))
            "ty"
            (unless (=0 (% N 10))
               (pack "-" (numNm (% N 10))) ) ) )
      ((rank N '((100 . "hundred") (1000 . "thousand") (1000000 . "million")))
         (pack (numNm (/ N (car @))) " " (cdr @) " " (numNm (% N (car @)))) ) ) )


   declare integer_names (0:20) character (9) varying static initial
      ('zero',  'one',   'two',  'three', 'four',   'five', 'six',
       'seven', 'eight', 'nine', 'ten',   'eleven', 'twelve',
       'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen',
       'eighteen', 'nineteen', 'twenty' );
   declare x(10) character (7) varying static initial
      ('ten', 'twenty', 'thirty', 'fourty', 'fifty',
       'sixty', 'seventy', 'eighty', 'ninety', 'hundred');
   declare y(0:5) character (10) varying static initial
      ('', '', ' thousand ', ' million ', ' billion ', ' trillion ');
   declare (i, j, m, t) fixed binary (31);
   declare (units, tens, hundreds, thousands) fixed binary (7);
   declare (h, v, value) character (200) varying;
   declare (d, k, n) fixed decimal (15);
   declare three_digits fixed decimal (3);

      value = '';
      i = 5;
      k = n;
      do d = 1000000000000 repeat d/1000 while (d > 0);
         i = i - 1;
         three_digits = k/d;
         k = mod(k, d);
         if three_digits = 0 then iterate;

         units = mod(three_digits, 10);
         t = three_digits / 10;
         tens = mod(t, 10);
         hundreds = three_digits / 100;
         m = mod(three_digits, 100);
         if m <= 20 then
            v = integer_names(m);
         else if units = 0 then
            v = '';
         else
            v = integer_names(units);
         if tens >= 2 & units ^= 0 then
            v = x(tens) || v;
         else if tens > 2 & units = 0 then
            v = v || x(tens);

         if units + tens = 0 then
            if n > 0 then  v = '';
         if hundreds > 0 then
            h = integer_names(hundreds) || ' hundred ';
         else
            h = '';
         if three_digits > 100 & (tens + units > 0) then
            v = 'and ' || v;
         if i = 1 & value ^= '' & three_digits <= 9 then
            v = 'and ' || v;
         value = value ||h || v || y(i);
      end;
      put skip edit (trim(N), ' = ', value) (a);


Naming conventions

1) global names

- a name is a group of any character except space and curly braces {}
  for instance "add", "+", "123", "()", "a.b.c", "...", ...

- but giving a variable the name of the 9 special forms (keywords)
    ["lambda", "def", "if", "let", "quote", "macro", "script", "style", "require"]
or of one of the more than 170 primitives
    ["div", ..., "+", ..., "cons", ..., A.new, A.first, A.rest, ..., long_add, ...]
is possible but is obviously strongly discouraged.

- when a function calls an helper function, it's better to prefix the helper function's name
  with the calling function's name. For instance the function "fibonacci" sets
  some initializations and calls the recursive part "fibonacci.rec".

- functions organized into sets (libraries) should be named with a common prefix.
  For instance the set of functions working on complex numbers [ "C.new", "C.x", "C.y", "C.+", "C.*", ...],
  suggesting object-oriented programming.

2) local names

Consider this example:

{def add {lambda {:a :b} :a+:b is equal to {+ :a :b}}}
-> add
{add 3 4}
-> 3+4 is equal to 7

When the add function is called the occurences of arguments {:a :b} are replaced by the given values, [3 4],
in the body of the function ":a+:b is equal to {+ :a :b}", leading to "3+4 is equal to {+ 3 4}" and finally
to "3+4 is equal to 7". Note that the character "a" inside the word "equal" has not been replaced.
So generally speaking:

- inside a function local defined arguments must be prefixed by a colon, ":",
- they must have a null intersection. For instance this arguments list {:a1 :a2} is valid
  because the intersection of :a1 and :a2 is null, but this one {:a :a1} is not,
  because the intersection of :a and :a1 is :a.
- an alternative could be to prefix and postfix names, say :a: and :a1: which have a null intersection.
  It's a matter of choice let to the coder. In all cases naming must be done with the utmost care.


- constants use UPCASE_SNAKE
- variable names use lower_case_snake
- class-like structures use CamelCase
- other functions use smallCamelCase
- Use _ for unneeded variables
- Don't use Hungarian Notation


#1=(PRINT (EQUAL (WRITE-TO-STRING '#1# :CIRCLE 1) (READ-LINE *STANDARD-INPUT*)))


import std.file; import std.stdio; import std.string; void main() { auto source = readText("narcissist.d").chomp; auto input = readln().chomp(); if (source == input) writeln("accept"); else writeln("reject"); }


!. = !prompt "Enter my code: " concat( swap !decode!utf-8 !encode!quoted dup swap ) "!. = !prompt \qEnter my code: \q concat( swap !decode!utf-8 !encode!quoted dup swap ) "


: narcissist  [ source ] sliteral compare 0= ;


Dim As String a, s = "Dim As String a, s = Input a : Print (a = Left(s, 21) + Chr(34) + s + Chr(34) + Mid(s, 47, 3) + Mid(s, 23, 108)) + Mid(s, 54, 3)" : Input a : Print (a = Left(s, 21) + Chr(34) + s + Chr(34) + Mid(s, 47, 3) + Mid(s, 23, 108))


package main; import "os"; import "fmt"; import "bytes"; import "io/ioutil"; func main() {ios := "os"; ifmt := "fmt"; ibytes := "bytes"; iioutil := "io/ioutil"; zero := "Reject"; one := "Accept"; x := "package main; import %q; import %q; import %q; import %q; func main() {ios := %q; ifmt := %q; ibytes := %q; iioutil := %q; zero := %q; one := %q; x := %q; s := fmt.Sprintf(x, ios, ifmt, ibytes, iioutil, ios, ifmt, ibytes, iioutil, zero, one, x); in, _ := ioutil.ReadAll(os.Stdin); if bytes.Equal(in, []byte(s)) {fmt.Println(one);} else {fmt.Println(zero);};}\n"; s := fmt.Sprintf(x, ios, ifmt, ibytes, iioutil, ios, ifmt, ibytes, iioutil, zero, one, x); in, _ := ioutil.ReadAll(os.Stdin); if bytes.Equal(in, []byte(s)) {fmt.Println(one);} else {fmt.Println(zero);};}


100H:
BDOS: PROCEDURE (FN, ARG); DECLARE FN BYTE, ARG ADDRESS; GO TO 5; END BDOS;
EXIT: PROCEDURE; CALL BDOS(0,0); END EXIT;
PRINT: PROCEDURE (S); DECLARE S ADDRESS; CALL BDOS(9,S); END PRINT;

DECLARE FCB$NAME LITERALLY '5DH'; /* CP/M STORES COMMAND ARGUMENT HERE */

/* READ ASCII NUMBER */
READ$NUMBER: PROCEDURE (PTR) ADDRESS;
    DECLARE PTR ADDRESS, C BASED PTR BYTE, RSLT ADDRESS;
    RSLT = 0;
    DO WHILE '0' <= C AND C <= '9';
        RSLT = RSLT * 10 + C - '0';
        PTR = PTR + 1;
    END;
    RETURN RSLT;
END;

/* SPELL 16-BIT NUMBER */
SPELL: PROCEDURE (N);
    DECLARE N ADDRESS;
    IF N=0 THEN DO;
        CALL PRINT(.'ZERO$');
        RETURN;
    END;
    SMALL: PROCEDURE (N) ADDRESS;
        DECLARE N BYTE;
        DO CASE N;
            RETURN .'$';         RETURN .'ONE$';      RETURN .'TWO$';
            RETURN .'THREE$';    RETURN .'FOUR$';     RETURN .'FIVE$';
            RETURN .'SIX$';      RETURN .'SEVEN$';    RETURN .'EIGHT$';
            RETURN .'NINE$';     RETURN .'TEN$';      RETURN .'ELEVEN$';
            RETURN .'TWELVE$';   RETURN .'THIRTEEN$'; RETURN .'FOURTEEN$';
            RETURN .'FIFTEEN$';  RETURN .'SIXTEEN$';  RETURN .'SEVENTEEN$';
            RETURN .'EIGHTEEN$'; RETURN .'NINETEEN$';
        END;
    END SMALL;
    TEENS: PROCEDURE (N) ADDRESS;
        DECLARE N BYTE;
        DO CASE N-2;
            RETURN .'TWENTY$';
            RETURN .'THIRTY$';
            RETURN .'FORTY$';
            RETURN .'FIFTY$';
            RETURN .'SIXTY$';
            RETURN .'SEVENTY$';
            RETURN .'EIGHTY$';
            RETURN .'NINETY$';
        END;
    END TEENS;
    LESS$100: PROCEDURE (N);
        DECLARE N BYTE;
        IF N >= 20 THEN DO;
            CALL PRINT(TEENS(N/10));
            N = N MOD 10;
            IF N > 0 THEN CALL PRINT(.'-$');
        END;
        CALL PRINT(SMALL(N));
    END LESS$100;
    LESS$1000: PROCEDURE (N);
        DECLARE N ADDRESS;
        IF N >= 100 THEN DO;
            CALL LESS$100(N/100);
            CALL PRINT(.' HUNDRED$');
            N = N MOD 100;
            IF N > 0 THEN CALL PRINT(.' $');
        END;
        CALL LESS$100(N);
    END LESS$1000;
    IF N >= 1000 THEN DO;
        CALL LESS$1000(N/1000);
        CALL PRINT(.' THOUSAND$');
        N = N MOD 1000;
        IF N > 0 THEN CALL PRINT(.' $');
    END;
    CALL LESS$1000(N);
END SPELL;

CALL SPELL(READ$NUMBER(FCB$NAME));
CALL EXIT;
EOF


FUNCTION int2Text (number AS QUAD) AS STRING
    IF 0 = number THEN
        FUNCTION = "zero"
        EXIT FUNCTION
    END IF

    DIM num AS QUAD, outP AS STRING, unit AS LONG
    DIM tmpLng1 AS QUAD

    DIM small(1 TO 19) AS STRING, tens(7) AS STRING, big(5) AS STRING

    DIM tmpInt AS LONG, dcnt AS LONG

    ARRAY ASSIGN small() = "one", "two", "three", "four", "five", "six", _
                           "seven", "eight", "nine", "ten", "eleven", _
                           "twelve", "thirteen", "fourteen", "fifteen", _
                           "sixteen", "seventeen", "eighteen", "nineteen"
    ARRAY ASSIGN tens() = "twenty", "thirty", "forty", "fifty", "sixty", _
                          "seventy", "eighty", "ninety"
    ARRAY ASSIGN big() = "thousand", "million", "billion", "trillion", _
                         "quadrillion", "quintillion"

    num = ABS(number)

    DO
        tmpLng1 = num MOD 100
        SELECT CASE tmpLng1
            CASE 1 TO 19
                outP = small(tmpLng1) + " " + outP
            CASE 20 TO 99
                SELECT CASE tmpLng1 MOD 10
                    CASE 0
                        outP = tens((tmpLng1 \ 10) - 2) + " " + outP
                    CASE ELSE
                        outP = tens((tmpLng1 \ 10) - 2) + "-" + small(tmpLng1 MOD 10) + " " + outP
                END SELECT
        END SELECT

        tmpLng1 = (num MOD 1000) \ 100
        IF tmpLng1 THEN
            outP = small(tmpLng1) + " hundred " + outP
        END IF

        num = num \ 1000
        IF num < 1 THEN EXIT DO

        tmpLng1 = num MOD 1000
        IF tmpLng1 THEN outP = big(unit) + " " + outP

        unit = unit + 1
    LOOP

    IF number < 0 THEN outP = "negative " + outP

    FUNCTION = RTRIM$(outP)
END FUNCTION

FUNCTION PBMAIN () AS LONG
    DIM n AS QUAD

    #IF %DEF(%PB_CC32)
        INPUT "Gimme a number! ", n
    #ELSE
        n = VAL(INPUTBOX$("Gimme a number!", "Now!"))
    #ENDIF
    ? int2Text(n)
END FUNCTION


Class Alfa$ {
Private:
            myValue$
Public:
            Set {
                  Read .myValue$
            }
            Value {
                  =.myValue$
            }
            Module Doit {
                  Function TwoChars$(A$) {
                        =Left$(Left$(a$,1)+Right$(a$,1)+"??",2)
                  }
                  Print TwoChars$(.myValue$)
                  Dim A$(3)
                  A$(0)="zero","one","two"
                  Print A$(1)
                  k$=Lambda$ A$() (x) -> {
                        if x>0 and x<3 then {=A$(x)} else =A$(0)
                  }
                  Print k$(2)
                  Dim A$()
                  Print Len(A$())=0
                  Print k$(2)="two"
            }
}
A$=Alfa$()
Module CheckIt(&B$) {
      Input "name:", B$
      B.Doit
}
Checkit &A$
Print A$


# Constants can start with either a lower case or upper case letter.
const aConstant = 42
const FooBar = 4.2

var aVariable = "Meep" # Variables must start with a lowercase letter.

# Types must start with an uppercase letter.
type
  FooBar = object


   $ALL_CAPS_HERE   constants
   $Some_Caps_Here  package-wide global/static
   $no_caps_here    function scope my/our/local variables
   $_internal_use   private


- Global variables start with an asterisk '*'
- Global constants may be written all-uppercase
- Functions and other global symbols start with a lower case letter
- Locally bound symbols start with an upper case letter
- Local functions start with an underscore '_'
- Classes start with a plus-sign '+', where the first letter
   - is in lower case for abstract classes
   - and in upper case for normal classes
- Methods end with a right arrow '>'
- Class variables may be indicated by an upper case letter


main = let fi t e c = if c then t else e in do ct <- getContents; putStrLn $ fi ['a','c','c','e','p','t'] ['r','e','j','e','c','t'] $ take (length ct - 1) ct == let q s = (s ++ show s) in q "main = let fi t e c = if c then t else e in do ct <- getContents; putStrLn $ fi ['a','c','c','e','p','t'] ['r','e','j','e','c','t'] $ take (length ct - 1) ct == let q s = (s ++ show s) in q "


procedure main();yes:="Accept";no:="Reject";pat:="procedure main();yes:=$;no:=$;pat:=$;a:=[yes,no,pat];narc:=char(0)[0:0];pat?{while narc||:=tab(find(char(36))) do{narc||:=image(get(a));move(1)};narc||:=tab(0)};write(if read()==narc then yes else no);end";a:=[yes,no,pat];narc:=char(0)[0:0];pat?{while narc||:=tab(find(char(36))) do{narc||:=image(get(a));move(1)};narc||:=tab(0)};write(if read()==narc then yes else no);end


#!/j602/bin/jconsole
main=:3 : 0
  self=: '#!/j602/bin/jconsole',LF,'main=:',(5!:5<'main'),LF,'main''''',LF
  echo  self -: stdin''
)
main''


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Narcissist {
    private static final String SOURCE = "import java.io.BufferedReader;%nimport java.io.IOException;%nimport java.io.InputStreamReader;%n%npublic class Narcissist {%n    private static final String SOURCE = %c%s%c;%n    private static final char QUOTE = 0x22;%n%n    public static void main(String[] args) throws IOException {%n        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));%n        StringBuilder sb = new StringBuilder();%n%n        while (true) {%n            String line = br.readLine();%n            if (null == line) break;%n            sb.append(line).append(System.lineSeparator());%n        }%n%n        String program = String.format(SOURCE, QUOTE, SOURCE, QUOTE, QUOTE, QUOTE, QUOTE, QUOTE);%n        if (program.equals(sb.toString())) {%n            System.out.println(%caccept%c);%n        } else {%n            System.out.println(%creject%c);%n        }%n    }%n}%n";
    private static final char QUOTE = 0x22;

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringBuilder sb = new StringBuilder();

        while (true) {
            String line = br.readLine();
            if (null == line) break;
            sb.append(line).append(System.lineSeparator());
        }

        String program = String.format(SOURCE, QUOTE, SOURCE, QUOTE, QUOTE, QUOTE, QUOTE, QUOTE);
        if (program.equals(sb.toString())) {
            System.out.println("accept");
        } else {
            System.out.println("reject");
        }
    }
}


function Get-NumberName
{
  <#
    .SYNOPSIS
        Spells out a number in English.
    .DESCRIPTION
        Spells out a number in English in the range of 0 to 999,999,999.
    .NOTES
        The code for this function was copied (almost word for word) from the C#
        example on this page to show how similar Powershell is to C#.
    .PARAMETER Number
        One or more integers in the range of 0 to 999,999,999.
    .EXAMPLE
        Get-NumberName -Number 666
    .EXAMPLE
        Get-NumberName 1, 234, 31337, 987654321
    .EXAMPLE
        1, 234, 31337, 987654321 | Get-NumberName
  #>
    [CmdletBinding()]
    [OutputType([string])]
    Param
    (
        [Parameter(Mandatory=$true, ValueFromPipeline=$true)]
        [ValidateRange(0,999999999)]
        [int[]]
        $Number
    )

    Begin
    {
        [string[]]$incrementsOfOne = "zero",    "one",     "two",       "three",    "four",
                                     "five",    "six",     "seven",     "eight",    "nine",
                                     "ten",     "eleven",  "twelve",    "thirteen", "fourteen",
                                     "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"

        [string[]]$incrementsOfTen = "",      "",      "twenty",  "thirty", "fourty",
                                     "fifty", "sixty", "seventy", "eighty", "ninety"

        [string]$millionName  = "million"
        [string]$thousandName = "thousand"
        [string]$hundredName  = "hundred"
        [string]$andName      = "and"

        function GetName([int]$i)
        {
            [string]$output = ""

            if ($i -ge 1000000)
            {
                $remainder = $null
                $output += (ParseTriplet ([Math]::DivRem($i,1000000,[ref]$remainder))) + " " + $millionName
                $i = $remainder

                if ($i -eq 0) { return $output }
            }

            if ($i -ge 1000)
            {
                if ($output.Length -gt 0)
                {
                    $output += ", "
                }

                $remainder = $null
                $output += (ParseTriplet ([Math]::DivRem($i,1000,[ref]$remainder))) + " " + $thousandName
                $i = $remainder

                if ($i -eq 0) { return $output }
            }

            if ($output.Length -gt 0)
            {
                $output += ", "
            }

            $output += (ParseTriplet $i)

            return $output
        }

        function ParseTriplet([int]$i)
        {
            [string]$output = ""

            if ($i -ge 100)
            {
                $remainder = $null
                $output += $incrementsOfOne[([Math]::DivRem($i,100,[ref]$remainder))] + " " + $hundredName
                $i = $remainder

                if ($i -eq 0) { return $output }
            }

            if ($output.Length -gt 0)
            {
                $output += " " + $andName + " "
            }

            if ($i -ge 20)
            {
                $remainder = $null
                $output += $incrementsOfTen[([Math]::DivRem($i,10,[ref]$remainder))]
                $i = $remainder

                if ($i -eq 0) { return $output }
            }

            if ($output.Length -gt 0)
            {
                $output += " "
            }

            $output += $incrementsOfOne[$i]

            return $output
        }
    }
    Process
    {
        foreach ($n in $Number)
        {
            [PSCustomObject]@{
                Number = $n
                Name   = GetName $n
            }
        }
    }
}

1, 234, 31337, 987654321 | Get-NumberName


#lang racket
render-game-state
send-message-to-client
traverse-forest


{blanks}  {-│+}  {blanks}  {digits}  {.}  {digits}   { {e│E}  {-│+}  exponent }  {blanks}


test_variable = [1, 9, 8, 3]
test_variable.sort    # => [1, 3, 8, 9]
test_variable         # => [1, 9, 8, 3]
test_variable.sort!   # => [1, 3, 8, 9]
test_variable         # => [1, 3, 8, 9]


var code='var q=String.fromCharCode(39);print("var code=" + q + code + q + "; eval(code)" == readline())'; eval(code)


mysource = Base.read(Base.source_path(), String)
println(Int(ARGS[1] == mysource))


// version 1.1.0 (run on Windows 10)

fun main(args: Array<String>) {
    val text = java.io.File("narcissist.kt").readText()
    println("Enter the number of lines to be input followed by those lines:\n")
    val n = readLine()!!.toInt()
    val lines = Array<String>(n) { readLine()!! }
    if (lines.joinToString("\r\n") == text) println("\naccept") else println("\nreject")
}


prog = "prog = ``;\nPrint[InputString[] == \n   ToString[StringForm[prog, ToString[prog, InputForm]]]];";
Print[InputString[] == ToString[StringForm[prog, ToString[prog, InputForm]]]];


:- module(spell, [spell/2]).

%
% spell numbers up to the nonillions.
%

ones(1, "one").  ones(2, "two").    ones(3, "three").  ones(4, "four").  ones( 5, "five").
ones(6, "six").  ones(7, "seven").  ones(8, "eight").  ones(9, "nine").  ones(10, "ten").

ones(11, "eleven").     ones(12, "twelve").    ones(13, "thirteen").
ones(14, "fourteen").   ones(15, "fifteen").   ones(16, "sixteen").
ones(17, "seventeen").  ones(18, "eighteen").  ones(19, "nineteen").

tens(2, "twenty").  tens(3, "thirty").  tens(4, "forty").   tens(5, "fifty").
tens(6, "sixty").   tens(7, "seventy"). tens(8, "eighty").  tens(9, "ninety").

group( 1, "thousand").   group( 2, "million").      group(3, "bilion").
group( 4, "trillion").   group( 5, "quadrillion").  group(6, "quintillion").
group( 7, "sextilion").  group( 8, "septillion").   group(9, "octillion").
group(10, "nonillion").  group(11, "decillion").

spellgroup(N, G) :- G is floor(log10(N) / 3).

spell(N, S) :-
    N < 0, !,
    NegN is -N, spell(NegN, S0),
    string_concat("negative ", S0, S).
spell(0, "zero") :- !.
spell(N, S) :- between(1, 19, N), ones(N, S), !.
spell(N, S) :-
    N < 100, !,
    divmod(N, 10, Tens, Ones),
    tens(Tens, StrTens), ones_part(Ones, StrOnes),
    string_concat(StrTens, StrOnes, S).
spell(N, S) :-
    N < 1000, !,
    divmod(N, 100, Hundreds, Tens),
    ones(Hundreds, H), string_concat(H, " hundred", StrHundreds),
    tens_part(Tens, StrTens),
    string_concat(StrHundreds, StrTens, S).
spell(N, S) :-
    spellgroup(N, G), group(G, StrG),
    M is 10**(3*G), divmod(N, M, Group, Rest),
    spell(Group, S1),
    spell_remaining(Rest, S2),
    format(string(S), "~w ~w~w", [S1, StrG, S2]).

ones_part(0, "") :- !.
ones_part(N, S) :-
    ones(N, StrN),
    string_concat("-", StrN, S).

tens_part(0, "") :- !.
tens_part(N, S) :-
    spell(N, Tens),
    string_concat(" and ", Tens, S).

spell_remaining(0, "") :- !.
spell_remaining(N, S) :-
    spell(N, Rest),
    string_concat(", ", Rest, S).


const namespace_name = @import("dir_name/file_name.zig");
const TypeName = @import("dir_name/TypeName.zig");
var global_var: i32 = undefined;
const const_name = 42;
const primitive_type_alias = f32;
const string_alias = []u8;

const StructName = struct {
    field: i32,
};
const StructAlias = StructName;

fn functionName(param_name: TypeName) void {
    var functionPointer = functionName;
    functionPointer();
    functionPointer = otherFunction;
    functionPointer();
}
const functionAlias = functionName;

fn ListTemplateFunction(comptime ChildType: type, comptime fixed_size: usize) type {
    return List(ChildType, fixed_size);
}

fn ShortList(comptime T: type, comptime n: usize) type {
    return struct {
        field_name: [n]T,
        fn methodName() void {}
    };
}

// The word XML loses its casing when used in Zig identifiers.
const xml_document =
    \\<?xml version="1.0" encoding="UTF-8"?>
    \\<document>
    \\</document>
;
const XmlParser = struct {
    field: i32,
};

// The initials BE (Big Endian) are just another word in Zig identifier names.
fn readU32Be() u32 {}


import Nanoquery.IO

// get a file tied to this program's source
$f = new(File, $args[len($args) - 1])

// get the source and split across lines
$source = split($f.readAll(), "\n")

// read that amount of lines from the console
$in = list(len($source))
for ($i = 0) ($i < len($source)) ($i = $i + 1)
	append $in input()
end

// check line by line
for ($i = 0) ($i < len($in)) ($i = $i + 1)
	// check if the lines are equal
	if ($in[$i] != $source[$i])
		println "Reject"
		exit
	end
end

// if we got here, the lines are the same
println "Accept"


import strutils; let a = "import strutils; let a = $#; echo ord(stdin.readAll == a % (chr(34) & a & chr(34)) & chr(10))"; echo ord(stdin.readAll == a % (chr(34) & a & chr(34)) & chr(10))


# this is file narc.pl
local $/;
print do { open 0; <0> } eq <> ? "accept" : "reject";


without js -- (file i/o)
puts(1,{"\n\ntrue\n\n","\n\nfalse\n\n"}[1+(gets(open(command_line()[2],"r"))!=gets(0))])


(de narcissist (Str)
   (= Str (str narcissist)) )


function Narcissist
{
Param ( [string]$String )
If ( $String -eq $MyInvocation.MyCommand.Definition ) { 'Accept' }
Else { 'Reject' }
}


import sys
with open(sys.argv[0]) as quine:
    code = raw_input("Enter source code: ")
    if code == quine.read():
        print("Accept")
    else:
        print("Reject")


DataSection
  numberNames:
  ;small
  Data.s "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten"
  Data.s "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"
  ;tens
  Data.s "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"
  ;big, non-Chuquet system
  Data.s "thousand", "million", "billion", "trillion", "quadrillion", "quintillion", "sextillion"
  Data.s "septillion", "octillion", "nonillion", "decillion", "undecillion", "duodecillion"
  Data.s "tredecillion"
EndDataSection

Procedure.s numberWords(number.s)
  ;handles integers from -1E45 to +1E45
  Static isInitialized = #False
  Static Dim small.s(19)
  Static Dim tens.s(9)
  Static Dim big.s(14)

  If Not isInitialized
    Restore numberNames
    For i = 1 To 19
      Read.s small(i)
    Next
    For i = 2 To 9
      Read.s tens(i)
    Next
    For i = 1 To 14
      Read.s big(i)
    Next
    isInitialized = #True
  EndIf

  For i = 1 To Len(number)
    If Not FindString("- 0123456789", Mid(number,i,1), 1)
      number = Left(number, i - 1) ;trim number to the last valid character
      Break ;exit loop
    EndIf
  Next

  Protected IsNegative = #False
  number = Trim(number)
  If Left(number,1) = "-"
    IsNegative = #True
    number = Trim(Mid(number, 2))
  EndIf

  If CountString(number, "0") = Len(number)
    ProcedureReturn "zero"
  EndIf

  If Len(number) > 45
    ProcedureReturn "Number is too big!"
  EndIf

  Protected num.s = number, output.s, unit, unitOutput.s, working

  Repeat
    working = Val(Right(num, 2))
    unitOutput = ""
    Select working
      Case 1 To 19
        unitOutput = small(working)
      Case 20 To 99
        If working % 10
          unitOutput = tens(working / 10) + "-" + small(working % 10)
        Else
          unitOutput = tens(working / 10)
        EndIf
    EndSelect

    working = Val(Right(num, 3)) / 100
    If working
      If unitOutput <> ""
        unitOutput = small(working) + " hundred " + unitOutput
      Else
        unitOutput = small(working) + " hundred"
      EndIf
    EndIf

    If unitOutput <> "" And unit > 0
      unitOutput + " " + big(unit)
      If output <> ""
        unitOutput + ", "
      EndIf
    EndIf

    output = unitOutput + output

    If Len(num) > 3
      num = Left(num, Len(num) - 3)
      unit + 1
    Else
      Break ;exit loop
    EndIf
  ForEver

  If IsNegative
    output = "negative " + output
  EndIf

  ProcedureReturn output
EndProcedure

Define n$
If OpenConsole()
  Repeat
    Repeat
      Print("Give me an integer (or q to quit)! ")
      n$ = Input()
    Until n$ <> ""

    If Left(Trim(n$),1) = "q"
      Break ;exit loop
    EndIf
    PrintN(numberWords(n$))
  ForEver
  CloseConsole()
EndIf


Welcome to Quackery.

Enter "leave" to leave the shell.

/O> [ this copy unbuild = ] is narcissist
... $ "[ this copy unbuild = ]" narcissist
...

Stack: 1

/O> drop
... $ "Nothing is more important than my egomania. -- Clara Oswald" narcissist
...

Stack: 0

/O> leave
...

Cheerio.


-> ((lambda (x) (equal? (read) (list x (list 'quote x))))
   '(lambda (x) (equal? (read) (list x (list 'quote x)))))
((lambda (x) (equal? (read) (list x (list 'quote x))))
 '(lambda (x) (equal? (read) (list x (list 'quote x)))))
#t


EVAL my $self = q{say slurp() eq q[EVAL my $self = q{]~$self~q[}]~10.chr ?? q{Beautiful!} !! q{Not my type.}}


s = "s = %s%s%s; puts(gets.chomp == (s %% [34.chr, s, 34.chr]) ? 'accept' : 'reject')"; puts(gets.chomp == (s % [34.chr, s, 34.chr]) ? 'accept' : 'reject')


use std::io::{stdin, prelude::*};
fn main() {
    let src = include_str!("main.rs");
    let mut input = String::new();
    stdin()
        .lock()
        .read_to_string(&mut input)
        .expect("Could not read from STDIN");
    println!("{}", src == input);
}


import scala.io.StdIn

object Narcissist extends App {
  val text = scala.io.Source.fromFile("Narcissist.scala", "UTF-8").toStream
  println("Enter the number of lines to be input followed by those lines:\n")
  val n = StdIn.readInt()
  val lines = Stream {
    StdIn.readLine()
  }
  if (lines.mkString("\r\n") == text) println("\naccept") else println("\nreject")
}


TENS = [None, None, "twenty", "thirty", "forty",
        "fifty", "sixty", "seventy", "eighty", "ninety"]
SMALL = ["zero", "one", "two", "three", "four", "five",
         "six", "seven", "eight", "nine", "ten", "eleven",
         "twelve", "thirteen", "fourteen", "fifteen",
         "sixteen", "seventeen", "eighteen", "nineteen"]
HUGE = [None, None] + [h + "illion"
                       for h in ("m", "b", "tr", "quadr", "quint", "sext",
                                  "sept", "oct", "non", "dec")]

def nonzero(c, n, connect=''):
    return "" if n == 0 else connect + c + spell_integer(n)

def last_and(num):
    if ',' in num:
        pre, last = num.rsplit(',', 1)
        if ' and ' not in last:
            last = ' and' + last
        num = ''.join([pre, ',', last])
    return num

def big(e, n):
    if e == 0:
        return spell_integer(n)
    elif e == 1:
        return spell_integer(n) + " thousand"
    else:
        return spell_integer(n) + " " + HUGE[e]

def base1000_rev(n):
    # generates the value of the digits of n in base 1000
    # (i.e. 3-digit chunks), in reverse.
    while n != 0:
        n, r = divmod(n, 1000)
        yield r

def spell_integer(n):
    if n < 0:
        return "minus " + spell_integer(-n)
    elif n < 20:
        return SMALL[n]
    elif n < 100:
        a, b = divmod(n, 10)
        return TENS[a] + nonzero("-", b)
    elif n < 1000:
        a, b = divmod(n, 100)
        return SMALL[a] + " hundred" + nonzero(" ", b, ' and')
    else:
        num = ", ".join([big(e, x) for e, x in
                         enumerate(base1000_rev(n)) if x][::-1])
        return last_and(num)

if __name__ == '__main__':
    # examples
    for n in (0, -3, 5, -7, 11, -13, 17, -19, 23, -29):
        print('%+4i -> %s' % (n, spell_integer(n)))
    print('')

    n = 201021002001
    while n:
        print('%-12i -> %s' % (n, spell_integer(n)))
        n //= -10
    print('%-12i -> %s' % (n, spell_integer(n)))
    print('')


say (File.new(__FILE__).open_r.slurp == ARGF.slurp);


#! /usr/bin/swift
import Foundation

let script = CommandLine.arguments[0]
print(script)
let mytext = try? String.init(contentsOfFile: script, encoding: .utf8)

var enteredtext = readLine()
if mytext == enteredtext {
    print("Accept")
} else {
    print("Reject")
}


apply {{} {puts [expr {[gets stdin] eq [info level 0]}]}}


@(bind my64 "QChuZXh0IDphcmdzKUBmaWxlbmFtZUAobmV4dCBmaWxlbmFtZSlAZmlyc3RsaW5lQChmcmVlZm9ybSAiIilAcmVzdEAoYmluZCBpbjY0IEAoYmFzZTY0LWVuY29kZSByZXN0KSlAKGNhc2VzKUAgIChiaW5kIGZpcnN0bGluZSBgXEAoYmluZCBteTY0ICJAbXk2NCIpYClAICAoYmluZCBpbjY0IG15NjQpQCAgKGJpbmQgcmVzdWx0ICIxIilAKG9yKUAgIChiaW5kIHJlc3VsdCAiMCIpQChlbmQpQChvdXRwdXQpQHJlc3VsdEAoZW5kKQ==")
@(next :args)
@filename
@(next filename)
@firstline
@(freeform "")
@rest
@(bind in64 @(base64-encode rest))
@(cases)
@  (bind firstline `\@(bind my64 "@my64")`)
@  (bind in64 my64)
@  (bind result "1")
@(or)
@  (bind result "0")
@(end)
@(output)
@result
@(end)


cmp "$0" >/dev/null && echo accept || echo reject


Public Sub narcissist()
    quote = Chr(34)
    comma = Chr(44)
    cont = Chr(32) & Chr(95)
    rparen = Chr(41)
    n = Array( _
"Public Sub narcissist()", _
"    quote = Chr(34)", _
"    comma = Chr(44)", _
"    cont = Chr(32) & Chr(95)", _
"    rparen = Chr(41)", _
"    n = Array( _", _
"How many lines?", _
"Line ", _
"    x = InputBox(n(5))", _
"    flag = True", _
"    For i = 0 To 5", _
"        If InputBox(n(6) & i) <> n(i) Then flag = False", _
"    Next i", _
"    For i = 0 To 20", _
"        If InputBox(n(6) & i + 6) <> quote & n(i) & quote & comma & cont Then flag = False", _
"    Next i", _
"    If InputBox(n(6) & 27) <> quote & n(21) & quote & rparen Then flag = False", _
"    For i = 7 To 21", _
"        If InputBox(n(6) & i + 21) <> n(i) Then flag = False", _
"    Next i", _
"    Debug.Print IIf(flag, 1, 0)", _
"End Sub")
    x = InputBox(n(5))
    flag = True
    For i = 0 To 5
        If InputBox(n(6) & i) <> n(i) Then flag = False
    Next i
    For i = 0 To 20
        If InputBox(n(6) & i + 6) <> quote & n(i) & quote & comma & cont Then flag = False
    Next i
    If InputBox(n(6) & 27) <> quote & n(21) & quote & rparen Then flag = False
    For i = 7 To 21
        If InputBox(n(6) & i + 21) <> n(i) Then flag = False
    Next i
    Debug.Print IIf(flag, 1, 0)
End Sub


import "os" for Process, Platform
import "io" for File, Stdin, Stdout

var args = Process.allArguments
var text = File.read(args[1]).trim()
System.print("Enter the number of lines to be input followed by those lines:\n")
Stdout.flush()
var n = Num.fromString(Stdin.readLine())
var lines = List.filled(n, null)
for (i in 0...n) lines[i] = Stdin.readLine()
var joiner = Platform.isWindows ? "\r\n" : "\n"
var text2 = lines.join(joiner)
System.print()
if (text2 == text) {
    System.print("accept")
} else if (text.startsWith(text2)) {
    System.print("not yet finished")
} else {
    System.print("reject")
}


  [ [ table
      $ "zero"  $ "one"   $ "two"
      $ "three" $ "four"  $ "five"
      $ "six"   $ "seven" $ "eight"
      $ "nine"  $ "ten"   $ "eleven"
      $ "twelve"   $ "thirteen"
      $ "fourteen" $ "fifteen"
      $ "sixteen"  $ "seventeen"
      $ "eighteen" $ "nineteen" ] do ]  is units   ( n --> $ )

  [ [ table
      $ "nonety" $ "tenty"   $ "twenty"
      $ "thirty" $ "fourty"  $ "fifty"
      $ "sixty"  $ "seventy" $ "eighty"
      $ "ninety" ] do ]                 is tens    ( n --> $ )

  [ $ "" swap
    dup 99 > if
      [ 100 /mod swap units
        $ " hundred" join
        swap dip join
        dup 0 = iff drop ]done[ ]
    over size 0 > if
      [ dip [ $ " and " join ] ]
    dup 19 > if
      [ 10 /mod swap tens
        swap dip join
        dup 0 = iff drop ]done[ ]
    over size 0 > if
      [ over -1 peek space != if
          [ dip [ space join ] ] ]
    units join ]                        is triplet ( n --> $ )

  [ $ "" swap
    dup 999999 > if
      [ 1000000 /mod swap triplet
        $ " million" join
        swap dip join
        dup 0 = iff drop ]done[ ]
    dup 999 > if
      [ over size 0 > if
          [ dip [ $ ", " join ] ]
        1000 /mod swap triplet
        $ " thousand" join
        swap dip join
        dup 0 = iff drop ]done[ ]
    over size 0 > if
      [ dip [ $ ", " join ] ]
    triplet join ]                      is name$   ( n --> $ )

   10 times
     [ 10 9 random
       1+ ** random
       dup echo
       say " is:"
       name$ nest$
       60 wrap$ cr cr ]


# Number Names

ones <- c("", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine",
          "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen")
tens <- c("ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety")
mags <- c("", "thousand", "million", "billion", "trillion", "quadrillion", "quintillion")

return_hund <- function(input_number){
  if (input_number == 0) return("")
  num_text <- as.character()
  input_hund <- trunc(input_number / 100)
  input_ten <- trunc((input_number - input_hund * 100) / 10)
  input_one <- input_number %% 10
  if (input_number > 99) num_text <- paste0(ones[trunc(input_number / 100) + 1], "-hundred")
  if (input_ten < 2){
    if (input_ten == 0 & input_one == 0) return(num_text)
    if (input_hund > 0) return(paste0(num_text, " ", ones[input_ten * 10 + input_one + 1]))
    return(paste0(ones[input_ten * 10 + input_one + 1]))
  }
  ifelse(input_hund > 0,
         num_text <- paste0(num_text, " ", tens[input_ten]),
         num_text <- paste0(tens[input_ten])
  )
  if (input_one != 0) num_text <- paste0(num_text, "-", ones[input_one + 1])
  return(num_text)
}

make_number <- function(number){
  if (number == 0) return("zero")
  a <- abs(number)
  num_text <- as.character()
  g <- trunc(log(a, 10)) + 1
  for (i in c(seq(g, 1))){
    b <- floor(a / 1000 ^ (i - 1))
    x <- return_hund(b)
    if (x != "") num_text <- paste0(num_text, return_hund(b), " ", mags[i], " ")
    a <- a - b * 1000 ^ (i - 1)
  }
  return(ifelse(sign(number) > 0, num_text, paste("negative", num_text)))
}

my_num <- data.frame(nums = c(
  0, 1, -11, 13, 99, 100, -101, 113, -120, 450, -999, 1000, 1001, 1017, 3000, 3001,
  9999, 10000, 10001, 10100, 10101, 19000, 20001, 25467, 99999, 100000, 1056012,
  -200000, 200001, -200012, 2012567, -5685436, 5000201, -11627389, 100067652, 456000342)
)

my_num$text <- as.character(lapply(my_num$nums, make_number))
print(my_num, right=F)


stdin:=File.stdin.read();
thisFileSrc:=File(System.argv[1]).read();
println((stdin==thisFileSrc) and "input matches "+System.argv[1] or "No match");


#lang racket

(define smalls
  (map symbol->string
       '(zero one two three four five six seven eight nine ten eleven twelve
         thirteen fourteen fifteen sixteen seventeen eighteen nineteen)))

(define tens
  (map symbol->string
       '(zero ten twenty thirty forty fifty sixty seventy eighty ninety)))

(define larges
  (map symbol->string
       '(thousand million billion trillion quadrillion quintillion sextillion
         septillion octillion nonillion decillion undecillion duodecillion
         tredecillion quattuordecillion quindecillion sexdecillion
         septendecillion octodecillion novemdecillion vigintillion)))

(define (integer->english n)
  (define (step div suffix separator [subformat integer->english])
    (define-values [q r] (quotient/remainder n div))
    (define S (if suffix (~a (subformat q) " " suffix) (subformat q)))
    (if (zero? r) S (~a S separator (integer->english r))))
  (cond [(< n 0) (~a "negative " (integer->english (- n)))]
        [(< n 20) (list-ref smalls n)]
        [(< n 100) (step 10 #f "-" (curry list-ref tens))]
        [(< n 1000) (step 100 "hundred" " and ")]
        [else (let loop ([N 1000000] [D 1000] [unit larges])
                (cond [(null? unit)
                       (error 'integer->english "number too big: ~e" n)]
                      [(< n N) (step D (car unit) ", ")]
                      [else (loop (* 1000 N) (* 1000 D) (cdr unit))]))]))

(for ([n 10])
  (define e (expt 10 n))
  (define r (+ (* e (random e)) (random e)))
  (printf "~s: ~a\n" r (integer->english r)))


constant @I = <zero one    two    three    four     five    six     seven     eight    nine
               ten  eleven twelve thirteen fourteen fifteen sixteen seventeen eighteen nineteen>;
constant @X = <0    X      twenty thirty   forty    fifty   sixty   seventy   eighty   ninety>;
constant @C = @I X~ ' hundred';
constant @M = (<0 thousand>,
    ((<m b tr quadr quint sext sept oct non>,
    (map { ('', <un duo tre quattuor quin sex septen octo novem>).flat X~ $_ },
    <dec vigint trigint quadragint quinquagint sexagint septuagint octogint nonagint>),
    'cent').flat X~ 'illion')).flat;

sub int-name ($num) {
    if $num.substr(0,1) eq '-' { return "negative {int-name($num.substr(1))}" }
    if $num eq '0' { return @I[0] }
    my $m = 0;
    return join ', ', reverse gather for $num.flip.comb(/\d ** 1..3/) {
        my ($i,$x,$c) = .comb».Int;
        if $i or $x or $c {
            take join ' ', gather {
                if $c { take @C[$c] }
                if $x and $x == 1 { take @I[$i+10] }
                else {
                    if $x { take @X[$x] }
                    if $i { take @I[$i] }
                }
                take @M[$m] // die "WOW! ZILLIONS!\n" if $m;
            }
        }
        $m++;
    }
}

while '' ne (my $n = prompt("Number: ")) {
    say int-name($n);
}


OneList=["zero",    "one",     "two",       "three",    "four",
              "five",    "six",     "seven",     "eight",    "nine",
              "ten",     "eleven",  "twelve",    "thirteen", "fourteen",
              "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"]
tenList=["" , "" , "twenty",  "thirty", "fourty",
            "fifty", "sixty", "seventy", "eighty", "ninety"]

millionStr="Million"
thousandStr="Thousand"
hundredStr="Hundred"
andStr="And"
pointStr=" Point "

while true
	see "enter number to convert:"
	give theNumber

	pointSplited=splitString(theNumber,".")
	fraction=0

	useFr=false
	if len(pointSplited) >=1 theNumber=pointSplited[1] ok
	if len(pointSplited) >=2 useFr=true fraction=pointSplited[2] ok
	pointSplited=null

	see getName(number(theNumber))
	if useFr=true see pointStr + getName(number(fraction)) ok
	see nl
end

func getName num
rtn=null
if num=0
    rtn += OneList[floor(num+1)]
	return rtn
ok
if num<0
	return "minus " + getName(fabs(num))
ok
if num>= 1000000
	rtn += getName(num / 1000000) +" "+ millionStr
	num%=1000000
ok
if num>=1000
	if len(rtn)>0 rtn += ", " ok

	rtn += getName(num / 1000)+ " " + thousandStr
	num%=1000
ok

if num >=100
if len(rtn)>0 rtn += ", " ok
	rtn += OneList[floor((num / 100)+1)] + " " + hundredStr
	num%=100
ok

if num=0
	return rtn +
ok
if len(rtn)>0 rtn += " " + andStr + " " ok
if(num>=20)

	rtn += tenList[floor((num / 10)+1)]
	num%=10
ok
if num=0
	return rtn
ok
if len(rtn)>0 rtn +=  " " ok
rtn += OneList[num+1]
return rtn

func splitString str,chr
	for i in str if strcmp(i,chr)=0 i=nl ok next
	return str2list(str)


SMALL = %w(zero one two three four five six seven eight nine ten
           eleven twelve thirteen fourteen fifteen sixteen seventeen
           eighteen nineteen)

TENS = %w(wrong wrong twenty thirty forty fifty sixty seventy
          eighty ninety)

BIG = [nil, "thousand"] +
      %w( m b tr quadr quint sext sept oct non dec).map{ |p| "#{p}illion" }

def wordify number
  case
  when number < 0
    "negative #{wordify -number}"

  when number < 20
    SMALL[number]

  when number < 100
    div, mod = number.divmod(10)
    TENS[div] + (mod==0 ? "" : "-#{wordify mod}")

  when number < 1000
    div, mod = number.divmod(100)
    "#{SMALL[div]} hundred" + (mod==0 ? "" : " and #{wordify mod}")

  else
    # separate into 3-digit chunks
    chunks = []
    div = number
    while div != 0
      div, mod = div.divmod(1000)
      chunks << mod                 # will store smallest to largest
    end

    raise ArgumentError, "Integer value too large." if chunks.size > BIG.size

    chunks.map{ |c| wordify c }.
           zip(BIG).    # zip pairs up corresponding elements from the two arrays
           find_all { |c| c[0] != 'zero' }.
           map{ |c| c.join ' '}.    # join ["forty", "thousand"]
           reverse.
           join(', ').              # join chunks
           strip
  end
end

data = [-1123, 0, 1, 20, 123, 200, 220, 1245, 2000, 2200, 2220, 467889,
        23_000_467, 23_234_467, 2_235_654_234, 12_123_234_543_543_456,
        987_654_321_098_765_432_109_876_543_210_987_654,
        123890812938219038290489327894327894723897432]

data.each do |n|
  print "#{n}: "
  begin
    puts "'#{wordify n}'"
  rescue => e
    puts "Error: #{e}"
  end
end


use std::io::{self, Write, stdout};

const SMALL: &[&str] = &[
    "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten",
    "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen",
    "nineteen",
];

const TENS: &[&str] = &[
    "PANIC", "PANIC", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety",
];

const MAGNITUDE: &[&str] = &[
    "PANIC", "thousand", "million", "billion", "trillion", "quadrillion", "quintillion",
];

fn wordify<W: Write>(w: &mut W, mut number: i64) -> Result<(), io::Error> {
    if number == 0 {
        return write!(w, "zero");
    }
    if number < 0 {
        write!(w, "negative ")?;
        number = -number;
    }
    while number != 0 {
        if number < 20 {
            write!(w, "{}", SMALL[number as usize])?;
            break;
        } else if number < 100 {
            write!(w, "{}", TENS[number as usize / 10])?;
            number %= 10;
            if number != 0 {
                write!(w, "-")?;
            }
        } else if number < 1_000 {
            write!(w, "{} hundred", SMALL[number as usize / 100])?;
            number %= 100;
            if number != 0 {
                write!(w, " and ")?;
            }
        } else {
            let mut top = number;
            let mut magnitude = 0i64;
            let mut magnitude_pow = 1i64;
            while top >= 1_000 {
                top /= 1_000;
                magnitude += 1;
                magnitude_pow *= 1_000;
            }
            wordify(w, top)?;
            number %= magnitude_pow;
            if number == 0 {
                write!(w, " {}", MAGNITUDE[magnitude as usize])?;
            } else if number > 100 {
                write!(w, " {}, ", MAGNITUDE[magnitude as usize])?;
            } else {
                write!(w, " {} and ", MAGNITUDE[magnitude as usize])?;
            }
        }
    }
    Ok(())
}

fn main() {
    let stdout = stdout();
    let mut stdout = stdout.lock();
    for &n in &[12, 1048576, 9_000_000_000_000_000_000, -2, 0, 5_000_000_000_000_000_001, -555_555_555_555] {
        wordify(&mut stdout, n).unwrap();
        write!(&mut stdout, "\n").unwrap();
    }
}


import scala.annotation.tailrec
import scala.collection.parallel.ParSeq

/** Spells an English numeral longhand. The numbers are expressed using words.
 *
 *  The implementation goes up to 1069-1 and also supports negative and zero inputs.
 *
 *  @example longhand( 1234 )  // results in: "one thousand two hundred thirty-four".
 */
trait LongHand {
  /** Spells a number longhand
   *
   *  Done by recursively process the triplets of decimal numbers.
   *  @param numeral		the numeric value to be converted
   *  @param showAnd		flag the output extra and in output, default off
   *  @param zeroString		the word for 0, default to "zero"
   *  @param showHyphen		hyphenate all compound numbers e.g. twenty-four, default is on
   *  @return				the numeric value expressed in words
   */
  def longhand(numeral: BigInt,
               showAnd: Boolean = false,
               zeroString: String = "zero",
               showHyphen: Boolean = true): String = {

    val condAndString = if (showAnd) "and " else ""
    val condHyphenString = if (showHyphen) "-" else " "

    // 234 Becomes "two hundred [and] thirty-four"
    def composeScale(nnn: String, isLSDgroup: Boolean, strE3: String): String = {
      nnn match { // Rare exceptions confirms the rule
        case "000" => ""
        case "100" => onesAndTeens(1) + hundredString + strE3 // Solves the faulty hundred AND thousand problem
        case _ => {
          val eval = (nnn.par.map(_.toString.toInt).reverse zip ParSeq('units, 'tens, 'hundreds)).reverse

          eval.map {
            case (d, 'units) if eval.seq.contains(1, 'tens) => onesAndTeens(d + 10)
            case (d, 'units) if (isLSDgroup && nnn == "0") => zeroString
            case (d, 'units) => onesAndTeens(d)
            case (d, 'hundreds) if d > 0 => onesAndTeens(d) + hundredString + condAndString
            case (d, 'tens) if d > 1 && eval.seq.contains(0, 'units) => tens(d)
            case (d, 'tens) if d > 1 => tens(d) + condHyphenString //'
            case _ => ""
          }.mkString + strE3
        }
      }
    } // def composeScale(…

    def compose(n: BigInt): String = {
      // "1234" becomes List((1,"thousand"), (234, ""))
      val decGroups = n.toString.reverse.grouped(3).map(_.reverse).toSeq.par // Group into powers of thousands
      if (decGroups.size <= shortScale.size) // Detect overflow
      { // Send per group section to composeScale
        @tailrec
        def iter(elems: Seq[(String, String)], acc: String): String = {
          elems match {
            case (group, powers) :: tail => {
              iter(tail, acc + composeScale(group, tail == Nil, powers))
            }
            case _ => acc
          }
        } // Group of decimals are accompanied with the short scale name.
        iter(decGroups.zip(shortScale).reverse.toList, "").mkString.trim
      } else "###.overflow.###"
    } // def compose(…

    // Here starts def longhand(…
    if (numeral < 0) "minus " + compose(-numeral) else compose(numeral)
  } // End def longhand(…

  private val onesAndTeens = {
    def dozen = "one two three four five six seven eight nine ten eleven twelve".split(' ').map(_ + " ").par
    def teens = "thir four fif six seven eigh nine".split(' ').map(_ + "teen ").par
    ParSeq("") ++ dozen ++ teens
  }

  private val tens = ParSeq("", "") ++
    ("twen thir for fif six seven eigh nine".split(' ')).map(_ + "ty")
  private final val hundredString = "hundred "
  private val shortScale = {
    def p1 = "m b tr quadr quint sext sept oct non dec".split(' ').map(_ + "illion ").par
    def p2 = "un duo tre quattuor quin sex septen octo novem ".split(' ').map(_ + "decillion ").par
    def p3 = "vigint cent".split(' ').map(_ + "illion ").par
    ParSeq("", "thousand ") ++ p1 ++ p2 ++ p3
  }
} // trait LongHand

object SpellNumber extends LongHand with App {
  // Main entry A little test...
  { // Anonymous ordered list as test set
    def testVal1 = BigInt("1" * 69)
    def testVal9 = BigInt(10).pow(69) - 1

    @tailrec // Series generator of 9, 98, 987, 9876 …
    def inner(counter: Int, elem: BigInt, testList: ParSeq[BigInt]): ParSeq[BigInt] = {
      if (counter < 20)
        inner(counter + 1, elem * 10 + (9 - (counter % 10)), testList ++ ParSeq(elem))
      else testList.par
    }
    inner(0, 0L, // Test values
      ParSeq(-Long.MaxValue, -1000000000, 12, 13, 19, 20, 21, 112, 1001, 1012, 1013,
        Long.MaxValue - 1, Long.MaxValue - 13, testVal1, testVal9)) ++
      (for (z <- 0 to 69) yield BigInt(10).pow(z)) // powers of ten

  }.seq.sorted.foreach(num => println(f"$num%+,80d -> ${longhand(numeral = num, showAnd = true)}"))
} // object SpellNumber @ line 110


$ include "seed7_05.s7i";
  include "stdio.s7i";
  include "wrinum.s7i";

const proc: main is func
  local
    var integer: number is 0;
  begin
    for number range 1 to 999999 do
      writeln(str(ENGLISH, number));
    end for;
  end func;


set numbers to [0,1,7,22,186,pi,-48.6,-3451,925734, 12570902378]

repeat with each number in numbers
	put number into output
	put numberWords of number into character 15 of output
	put output
end repeat


import <Utilities/Math.sl>;
import <Utilities/Sequence.sl>;
import <Utilities/Conversion.sl>;
import <Utilities/String.sl>;

main(argv(2)) := delimit(numberToEnglish(stringToInt(argv)), '\n');

ones := ["one", "two", "three", "four", "five", "six", "seven", "eight", "nine"];
teens := ["eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"];
tens := ["ten", "twenty", "thrity", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"];

magnitudes := ["", "thousand", "million", "billion", "trillion"];

numberToEnglish(num(0)) :=
    let
        triplets[i] :=
                (num / integerPower(1000, i - 1)) mod 1000
                foreach i within 1 ... ceiling(log(1000, num + 1));

        englishtTriplets[j] := numberToEnglishHelper(triplets[j]);

        partials[j] :=
                englishtTriplets[j] ++ magnitudes[j] ++ ", " when size(englishtTriplets[j]) > 0
                foreach j within reverse(1 ... size(triplets));
    in
            "zero" when num = 0
        else
            "negative " ++ numberToEnglish(-num) when num < 0
        else
            trim(allButLast(trim(join(partials))));

numberToEnglishHelper(num(0)) :=
    let
        onesPlace := num mod 10;
        tensPlace := (num mod 100) / 10;
        hundredsPlace :=  (num mod 1000) / 100;

        onesWord :=     "ten " when tensPlace = 1 and onesPlace = 0
                    else
                        "" when onesPlace = 0
                    else
                        teens[onesPlace] ++ " " when tensPlace = 1
                    else
                        ones[onesPlace] ++ " ";

        tensWord :=    "" when tensPlace = 0 or tensPlace = 1
                    else
                        tens[tensPlace] ++ " " when onesPlace = 0
                    else
                        tens[tensPlace] ++ "-";

        hundredsWord :=     "" when hundredsPlace = 0
                         else
                             ones[hundredsPlace] ++ " hundred ";

        andWord := "" when hundredsPlace = 0 or (tensPlace = 0 and onesPlace = 0) else "and ";

    in
        hundredsWord ++ andWord ++ tensWord ++ onesWord;


#!/usr/local/bin/shale

maths library

0 ones:: dup var "zero" =
1 ones:: dup var "one" =
2 ones:: dup var "two" =
3 ones:: dup var "three" =
4 ones:: dup var "four" =
5 ones:: dup var "five" =
6 ones:: dup var "six" =
7 ones:: dup var "seven" =
8 ones:: dup var "eight" =
9 ones:: dup var "nine" =
10 teens:: dup var "ten" =
11 teens:: dup var "eleven" =
12 teens:: dup var "twelve" =
13 teens:: dup var "thirteen" =
14 teens:: dup var "fourteen" =
15 teens:: dup var "fifteen" =
16 teens:: dup var "sixteen" =
17 teens:: dup var "seventeen" =
18 teens:: dup var "eighteen" =
19 teens:: dup var "nineteen" =
2 tens:: dup var "twenty" =
3 tens:: dup var "thirty" =
4 tens:: dup var "forty" =
5 tens:: dup var "fifty" =
6 tens:: dup var "sixty" =
7 tens:: dup var "seventy" =
8 tens:: dup var "eighty" =
9 tens:: dup var "ninety" =

say dup var {
  commaFlag dup var swap =
  andFlag dup var swap =
  n dup var swap =
  h dup var n 100 / =
  t dup var n 100 % =
  o dup var n 10 % =

  h 0 > {
    commaFlag { "," print commaFlag false = } ifthen
    h.value ones:: " %s hundred" printf
  } ifthen

  h 0 > t 0 > and t 0 > andFlag and or { " and" print commaFlag false = } ifthen

  t 9 > {
    t 19 > {
      commaFlag { "," print commaFlag false = } ifthen
      t 10 / tens:: " %s" printf
      o 0 > { o.value ones:: "-%s" printf } ifthen
    } {
      t 9 > { commaFlag { "," print } ifthen t.value teens:: " %s" printf } ifthen
    } if
  } {
    o 0 > { commaFlag { "," print } ifthen o.value ones:: " %s" printf } ifthen
  } if
} =

speak dup var {
  n dup var swap =
  m dup var n 1000000 / =
  t dup var n 1000 /  1000 % =
  h dup var n 1000 % =

  n "%10d ->" printf
  m 0 > { m.value false false say() " million" print } ifthen
  t 0 > { t.value false m 0 > say() " thousand" print } ifthen
  h 0 > m 0 == t 0 == and or { h.value m 0 > t 0 > or dup say() } ifthen
  "" println
} =

"Stock numbers" println
1 speak()
10 speak()
100 speak()
1000 speak()
1001 speak()
100001000 speak()
100001001 speak()
123456789 speak()
987654321 speak()
100200300 speak()
10020030 speak()

"" println
"Randomly generated numbers" println
i var
i 0 =
{ i 10 < } {
  random maths::() 1000000000 % speak()   // Cap it to less than 1 billion.
  i++
} while


var l = frequire('Lingua::EN::Numbers');
say l.num2en(123456789);


SELECT val, to_char(to_date(val,'j'),'jsp') name
FROM
(
SELECT
round( dbms_random.VALUE(1, 5373484)) val
FROM dual
CONNECT BY level <= 5
);

SELECT to_char(to_date(5373485,'j'),'jsp') FROM dual;


extension Int {
  private static let bigNames = [
    1_000: "thousand",
    1_000_000: "million",
    1_000_000_000: "billion",
    1_000_000_000_000: "trillion",
    1_000_000_000_000_000: "quadrillion",
    1_000_000_000_000_000_000: "quintillion"
  ]

  private static let names = [
    1: "one",
    2: "two",
    3: "three",
    4: "four",
    5: "five",
    6: "six",
    7: "seven",
    8: "eight",
    9: "nine",
    10: "ten",
    11: "eleven",
    12: "twelve",
    13: "thirteen",
    14: "fourteen",
    15: "fifteen",
    16: "sixteen",
    17: "seventeen",
    18: "eighteen",
    19: "nineteen",
    20: "twenty",
    30: "thirty",
    40: "forty",
    50: "fifty",
    60: "sixty",
    70: "seventy",
    80: "eighty",
    90: "ninety"
  ]

  public var numberName: String {
    guard self != 0 else {
      return "zero"
    }

    let neg = self < 0
    let maxNeg = self == Int.min
    var nn: Int

    if maxNeg {
      nn = -(self + 1)
    } else if neg {
      nn = -self
    } else {
      nn = self
    }

    var digits3 = [Int](repeating: 0, count: 7)

    for i in 0..<7 {
      digits3[i] = (nn % 1000)
      nn /= 1000
    }

    func threeDigitsToText(n: Int) -> String {
      guard n != 0 else {
        return ""
      }

      var ret = ""

      let hundreds = n / 100
      let remainder = n % 100

      if hundreds > 0 {
        ret += "\(Int.names[hundreds]!) hundred"

        if remainder > 0 {
          ret += " "
        }
      }

      if remainder > 0 {
        let tens = remainder / 10
        let units = remainder % 10

        if tens > 1 {
          ret += Int.names[tens * 10]!

          if units > 0 {
            ret += "-\(Int.names[units]!)"
          }
        } else {
          ret += Int.names[remainder]!
        }
      }

      return ret
    }

    let strings = (0..<7).map({ threeDigitsToText(n: digits3[$0]) })
    var name = strings[0]
    var big = 1000

    for i in 1...6 {
      if digits3[i] > 0 {
        var name2 = "\(strings[i]) \(Int.bigNames[big]!)"

        if name.count > 0 {
          name2 += ", "
        }

        name = name2 + name
      }

      big &*= 1000
    }

    if maxNeg {
      name = String(name.dropLast(5) + "eight")
    }

    return neg ? "minus \(name)" : name
  }
}

let nums = [
  0, 1, 7, 10, 18, 22, 67, 99, 100, 105, 999, -1056, 1000005000,
  2074000000, 1234000000745003, Int.min
]

for number in nums {
  print("\(number) => \(number.numberName)")
}


proc int2words {n} {
    if { ! [regexp -- {^(-?\d+)$} $n -> n]} {
        error "not a decimal integer"
    }
    if {$n == 0} {
        return zero
    }
    if {$n < 0} {
        return "negative [int2words [expr {abs($n)}]]"
    }
    if {[string length $n] > 36} {
        error "value too large to represent"
    }

    set groups [get_groups $n]
    set l [llength $groups]
    foreach group $groups {
        incr l -1
        # ensure any group with a leading zero is not treated as octal
        set val [scan $group %d]
        if {$val > 0} {
            lappend result [group2words $val $l]
        }
    }
    return [join $result ", "]
}

set small {"" one two three four five six seven eight nine ten eleven twelve
           thirteen fourteen fifteen sixteen seventeen eighteen nineteen}
set tens {"" "" twenty thirty forty fifty sixty seventy eighty ninety}
set powers {"" thousand}
foreach p {m b tr quadr quint sext sept oct non dec} {lappend powers ${p}illion}

proc group2words {n level} {
    global small tens powers
    if {$n < 20} {
        lappend result [lindex $small $n]
    } elseif {$n < 100} {
        lassign [divmod $n 10] a b
        set result [lindex $tens $a]
        if {$b > 0} {
            append result - [lindex $small $b]
        }
    } else {
        lassign [divmod $n 100] a b
        lappend result [lindex $small $a] hundred
        if {$b > 0} {
            lappend result and [group2words $b 0]
        }
    }
    return [join [concat $result [lindex $powers $level]]]
}

proc divmod {n d} {
    return [list [expr {$n / $d}] [expr {$n % $d}]]
}

proc get_groups {num} {
    # from http://wiki.tcl.tk/5000
    while {[regsub {^([-+]?\d+)(\d\d\d)} $num {\1 \2} num]} {}
    return [split $num]
}

foreach test {
        0 -0 5 -5 10 25 99 100 101 999 1000 1008 1010 54321 1234567890
        0x7F
        123456789012345678901234567890123456
        1234567890123456789012345678901234567
} {
    catch {int2words $test} result
    puts "$test -> $result"
}


Public twenties As Variant
Public decades As Variant
Public orders As Variant

Private Sub init()
    twenties = [{"zero","one","two","three","four","five","six","seven","eight","nine","ten", "eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen"}]
    decades = [{"twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety"}]
    orders = [{1E15,"quadrillion"; 1E12,"trillion"; 1E9,"billion"; 1E6,"million"; 1E3,"thousand"}]
End Sub

Private Function Twenty(N As Variant)
    Twenty = twenties(N Mod 20 + 1)
End Function

Private Function Decade(N As Variant)
    Decade = decades(N Mod 10 - 1)
End Function

Private Function Hundred(N As Variant)
    If N < 20 Then
        Hundred = Twenty(N)
        Exit Function
    Else
        If N Mod 10 = 0 Then
            Hundred = Decade((N \ 10) Mod 10)
            Exit Function
        End If
    End If
    Hundred = Decade(N \ 10) & "-" & Twenty(N Mod 10)
End Function

Private Function Thousand(N As Variant, withand As String)
    If N < 100 Then
        Thousand = withand & Hundred(N)
        Exit Function
    Else
        If N Mod 100 = 0 Then
            Thousand = withand & Twenty(WorksheetFunction.Floor_Precise(N / 100)) & " hundred"
            Exit Function
        End If
    End If
    Thousand = Twenty(N \ 100) & " hundred and " & Hundred(N Mod 100)
End Function

Private Function Triplet(N As Variant)
    Dim Order, High As Variant, Low As Variant
    Dim Name As String, res As String
    For i = 1 To UBound(orders)
        Order = orders(i, 1)
        Name = orders(i, 2)
        High = WorksheetFunction.Floor_Precise(N / Order)
        Low = N - High * Order 'N Mod Order
        If High <> 0 Then
            res = res & Thousand(High, "") & " " & Name
        End If
        N = Low
        If Low = 0 Then Exit For
        If Len(res) And High <> 0 Then
            res = res & ", "
        End If
    Next i
    If N <> 0 Or res = "" Then
        res = res & Thousand(WorksheetFunction.Floor_Precise(N), IIf(res = "", "", "and "))
        N = N - Int(N)
        If N > 0.000001 Then
            res = res & " point"
            For i = 1 To 10
                n_ = WorksheetFunction.Floor_Precise(N * 10.0000001)
                res = res & " " & twenties(n_ + 1)
                N = N * 10 - n_
                If Abs(N) < 0.000001 Then Exit For
            Next i
        End If
    End If
    Triplet = res
End Function

Private Function spell(N As Variant)
    Dim res As String
    If N < 0 Then
        res = "minus "
        N = -N
    End If
    res = res & Triplet(N)
    spell = res
End Function

Private Function smartp(N As Variant)
    Dim res As String
    If N = WorksheetFunction.Floor_Precise(N) Then
        smartp = CStr(N)
        Exit Function
    End If
    res = CStr(N)
    If InStr(1, res, ".") Then
        res = Left(res, InStr(1, res, "."))
    End If
    smartp = res
End Function

Sub Main()
    Dim si As Variant
    init
    Samples1 = [{99, 300, 310, 417, 1501, 12609, 200000000000100, 999999999999999, -123456787654321,102003000400005,1020030004,102003,102,1,0,-1,-99, -1501,1234,12.34}]
    Samples2 = [{10000001.2,1E-3,-2.7182818, 201021002001,-20102100200,2010210020,-201021002,20102100,-2010210, 201021,-20102,2010,-201,20,-2}]
    For i = 1 To UBound(Samples1)
        si = Samples1(i)
        Debug.Print Format(smartp(si), "@@@@@@@@@@@@@@@@"); " "; spell(si)
    Next i
    For i = 1 To UBound(Samples2)
        si = Samples2(i)
        Debug.Print Format(smartp(si), "@@@@@@@@@@@@@@@@"); " "; spell(si)
    Next i
End Sub