class FizzBuzz(schema=Hash(<3 Fizz 5 Buzz>...)) {
    method filter(this) {
        var fb = ''
        schema.sort_by {|k,_| k.to_i }.each { |pair|
            fb += (pair[0].to_i `divides` this ? pair[1] : '')
        }
        fb.len > 0 ? fb : this
    }
}

func GeneralFizzBuzz(upto, schema) {
    var ping = FizzBuzz()
    if (nil != schema) {
        ping.schema = schema.to_hash
    }
    (1..upto).map {|i| ping.filter(i) }
}

GeneralFizzBuzz(20, <3 Fizz 5 Buzz 7 Baxx>).each { .say }


import Foundation

print("Input max number: ", terminator: "")

guard let maxN = Int(readLine() ?? "0"), maxN > 0 else {
  fatalError("Please input a number greater than 0")
}

func getFactor() -> (Int, String) {
  print("Enter a factor and phrase: ", terminator: "")

  guard let factor1Input = readLine() else {
    fatalError("Please enter a factor")
  }

  let sep1 = factor1Input.components(separatedBy: " ")
  let phrase = sep1.dropFirst().joined(separator: " ")

  guard let factor = Int(sep1[0]), factor != 0, !phrase.isEmpty else {
    fatalError("Please enter a factor and phrase")
  }

  return (factor, phrase)
}

let (factor1, phrase1) = getFactor()
let (factor2, phrase2) = getFactor()
let (factor3, phrase3) = getFactor()

for i in 1...maxN {
  let factors = [
    (i.isMultiple(of: factor1), phrase1),
    (i.isMultiple(of: factor2), phrase2),
    (i.isMultiple(of: factor3), phrase3)
  ].filter({ $0.0 }).map({ $0.1 }).joined()

  print("\(factors.isEmpty ? String(i) : factors)")
}


def input: {N: 110"1", words: [ { mod: 3"1", word: 'Fizz' }, { mod: 5"1", word: 'Buzz'}, {mod:7"1", word: 'Baxx'}]};

templates sayWords
  def i: $;
  templates maybeSay
    def word: $.word;
    $i mod $.mod -> \(<=0"1"> $word !\) !
  end maybeSay
  $input.words... -> maybeSay !
end sayWords

[ 1"1"..$input.N -> '$->sayWords;' ] -> \[i](<=''> $i ! <> $ !\) -> '$;
' -> !OUT::write


to swap :s1 :s2
  localmake "t thing :s1
  make :s1 thing :s2
  make :s2 :t
end

make "a 4
make "b "dog
swap "a "b        ; pass the names of the variables to swap
show list :a :b  ; [dog 4]


:- object(paws).

    :- public(swap/4).
    swap(First, Second, Second, First).

:- end_object.


HAI 1.3

I HAS A foo ITZ "kittehz"
I HAS A bar ITZ 42

foo, foo R bar, bar R IT

VISIBLE foo BTW, 42
VISIBLE bar BTW, kittehz

KTHXBYE


x, y = y, x                -- swap the values inside x and y
t[1], t[2] = t[2], t[1]    -- swap the first and second values inside table t


proc fizzbuzz {n args} {
    if {$args eq ""} {
        set args {{3 Fizz} {5 Buzz}}
    }
    while {[incr i] <= $n} {
        set out ""
        foreach rule $args {
            lassign $rule m echo
            if {$i % $m == 0} {append out $echo}
        }
        if {$out eq ""} {set out $i}
        puts $out
    }
}
fizzbuzz 20 {3 Fizz} {5 Buzz} {7 Baxx}


#
# general fizzbuzz
#
decl int<> factors
decl string<> words
decl int max

# get the max number
out ">" console
set max (in int console)

# get the factors
decl string input
set input " "
while (not (= input ""))
        out ">" console
        set input (in string console)
        if (not (= input ""))
                append (int (split input " ")<0>) factors
                append (split input " ")<1> words
        end if
end while

# output all the numbers
decl int i
for (set i 1) (< i (+ max 1)) (inc i)
        decl boolean foundfactor
        set foundfactor false
        for (decl int j) (< j (size factors)) (inc j)
                if (= (mod i factors<j>) 0)
                        set foundfactor true
                        out words<j> console
                end if
        end for
        set j 0

        if (not foundfactor)
                out i console
        end if
        out endl console
end for


Option Explicit

Private Type Choice
    Number As Integer
    Name As String
End Type

Private MaxNumber As Integer

Sub Main()
Dim U(1 To 3) As Choice, i As Integer, j As Integer, t$

    MaxNumber = Application.InputBox("Enter the max number : ", "Integer please", Type:=1)
    For i = 1 To 3
        U(i) = UserChoice
    Next
    For i = 1 To MaxNumber
        t = vbNullString
        For j = 1 To 3
            If i Mod U(j).Number = 0 Then t = t & U(j).Name
        Next
        Debug.Print IIf(t = vbNullString, i, t)
    Next i
End Sub

Private Function UserChoice() As Choice
Dim ok As Boolean

    Do While Not ok
        UserChoice.Number = Application.InputBox("Enter the factors to be calculated : ", "Integer please", Type:=1)
        UserChoice.Name = InputBox("Enter the corresponding word : ")
        If StrPtr(UserChoice.Name) <> 0 And UserChoice.Number < MaxNumber Then ok = True
    Loop
End Function


'The Function
Function FizzBuzz(range, mapping)
    data = Array()

    'Parse the mapping and put to "data" array
    temp = Split(mapping, ",")
    ReDim data(UBound(temp),1)
    For i = 0 To UBound(temp)
        map = Split(temp(i), " ")
        data(i, 0) = map(0)
        data(i, 1) = map(1)
    Next

    'Do the loop
    For i = 1 to range
        noMatch = True
        For j = 0 to UBound(data, 1)
            If (i Mod data(j, 0)) = 0 Then
                WScript.StdOut.Write data(j, 1)
                noMatch = False
            End If
        Next
        If noMatch Then WScript.StdOut.Write i
        WScript.StdOut.Write vbCrLf
    Next
End Function

'The Main Thing
WScript.StdOut.Write "Range? "
x = WScript.StdIn.ReadLine
WScript.StdOut.Write "Mapping? "
y = WScript.StdIn.ReadLine
WScript.StdOut.WriteLine ""
FizzBuzz x, y


\\ pgramming again Swap (for local use)
Module Swap (&a, &b) {
      \\ this call internal command - by default is by reference without using character &
      Swap a, b
}
X=20
Y=100
Swap &x, &y
Print X, Y, Type$(X)="Double",Type$(Y)="Double"
A$="A$"
B$="B$"
Swap &A$, &B$
Print A$="B$", B$="A$"


swap[a_, b_] := {a, b} = {b, a}
SetAttributes[swap, HoldAll]


Imports System.Globalization

Module Program
    Sub Main()
        Console.Write("Max: ")
        Dim max = Integer.Parse(Console.ReadLine(), CultureInfo.InvariantCulture)

        Dim factors As New SortedDictionary(Of Integer, String)

        Const NUM_FACTORS = 3
        For i = 1 To NUM_FACTORS
            Console.Write("Factor {0}: ", i)
            Dim input = Console.ReadLine().Split()
            factors.Add(Integer.Parse(input(0), CultureInfo.InvariantCulture), input(1))
        Next

        For i = 1 To max
            Dim anyMatches = False
            For Each factor In factors
                If i Mod factor.Key = 0 Then
                    Console.Write(factor.Value)
                    anyMatches = True
                End If
            Next
            If Not anyMatches Then Console.Write(i)
            Console.WriteLine()
        Next
    End Sub
End Module


import os

fn main() {
    max := os.input('Max: ').int()
    f1 := os.input('Starting factor (#) and word: ').fields()
    f2 := os.input('Next factor (#) and word: ').fields()
    f3 := os.input('Next factor (#) and word: ').fields()

    //using the provided data
    words := {
        f1[0].int(): f1[1],
        f2[0].int(): f2[1],
        f3[0].int(): f3[1],
    }
    keys := words.keys()
    mut divisible := false
    for i := 1; i <= max; i++ {
        for n in keys {
            if i % n == 0 {
                print(words[n])
                divisible = true
            }
        }
        if !divisible {
            print(i)
        }
        println('')
        divisible = false
    }
}


import "io" for Stdin, Stdout
import "/sort" for Sort

var n

while (true) {
    System.write("Maximum number : ")
    Stdout.flush()
    n = Num.fromString(Stdin.readLine())
    if (!n || !n.isInteger || n < 3) {
        System.print("Must be an integer > 2, try again.")
    } else {
        break
    }
}

var factors = []
var words = {}
for (i in 0..2) {
    while (true) {
        System.write("Factor %(i+1) : ")
        Stdout.flush()
        var factor = Num.fromString(Stdin.readLine())
        if (!factor || !factor.isInteger || factor < 2 || factors.contains(factor)) {
            System.print("Must be an unused integer > 1, try again.")
        } else {
            factors.add(factor)
            var outer = false
            while (true) {
                System.write("  Word %(i+1) : ")
                Stdout.flush()
                var word = Stdin.readLine()
                if (word.count == 0) {
                    System.print("Must have at least one character, try again.")
                } else {
                    words[factor] = word
                    outer = true
                    break
                }
            }
            if (outer) break
        }
    }
}

Sort.insertion(factors)
System.print()
for (i in 1..n) {
    var s = ""
    for (j in 0..2) {
        var factor = factors[j]
        if (i % factor == 0) s = s + words[factor]
    }
    if (s == "") s = i.toString
    System.print(s)
}


a: 10$
b: foo$

/* A simple way to swap values */
[a, b]: [b, a]$

a; /* foo */
b; /* 10 */

/* A macro to hide this */
swap(x, y) ::= buildq([x, y], ([x, y]: [y, x], 'done))$

swap(a, b)$

a; /* 10 */
b; /* foo */


stop:=ask("Count: ").toInt();
fizzBuzzers:=List();
do(3){ n,txt:=ask(">").split(); fizzBuzzers.append(T(n.toInt(),txt)) }
foreach n in ([1..stop]){
   s:=fizzBuzzers.filter('wrap([(fb,txt)]){ n%fb==0 }).apply("get",1).concat();
   println(s or n);
}


10 INPUT "Maximum number: ";max
20 INPUT "Number of factors: ";n
30 DIM f(n): DIM w$(n,4)
40 FOR i=1 TO n
50 INPUT "Input value-ENTER-word: ";f(i);w$(i)
60 NEXT i
70 FOR i=1 TO max
80 LET matched=0
90 FOR j=1 TO n
100 IF FN m(i,f(j))=0 THEN LET matched=1: PRINT w$(j);
110 NEXT j
120 IF NOT matched THEN PRINT ;i: GO TO 140
130 PRINT
140 NEXT i
150 DEF FN m(a,b)=a-INT (a/b)*b


vardef swap(suffix a, b) =
  save ?; string s_;
  if boolean a: boolean ?
    elseif numeric a: numeric ? % this one could be omitted
    elseif pair a: pair ?
    elseif path a: path ?
    elseif pen a: pen ?
    elseif picture a: picture ?
    elseif string a: string ?
    elseif transform a: transform ? fi;
  ? := a; a := b; b := ?
enddef;


swap = function(map, a, b)
    temp = map[a]
    map[a] = map[b]
    map[b] = temp
end function

x = 1
y = 2
print "BEFORE: x=" + x + ", y=" + y
swap(locals, "x", "y")
print "AFTER:  x=" + x + ", y=" + y


GENERIC INTERFACE GenericSwap(Elem);

PROCEDURE Swap(VAR left: Elem.T; VAR right: Elem.T);

END GenericSwap.


def coords    = (1, -1);
def invcoords = Swap(coords);


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

  -- Simple values with no spaces can be swapped without the use of a parse template
  lval = 27
  rval = 5
  say 'Before - <lval>'lval'</lval> <rval>'rval'</rval>'
  parse (lval rval) rval lval
  say 'After  - <lval>'lval'</lval> <rval>'rval'</rval>'
  say

  -- More complex data needs to use some form of parsing template
  lval = 'This value started on the left'
  rval = 'This value started on the right'
  dlm  = 12x80facebead01 -- some delimiting value that is unlikely to occur in the LVAL to be swapped
  say 'Before - <lval>'lval'</lval> <rval>'rval'</rval>'
  parse (lval || dlm || rval) rval (dlm) lval
  say 'After  - <lval>'lval'</lval> <rval>'rval'</rval>'
  say

  return


  macro Swap(a,b,    c)
    typeof(a) c
    c=a
    a=b
    b=c
  end macro

  'demo with compound types:
  '=========================
  type point { float x,y}
  point p={1,2}
  point q={3,4}
  swap p,q
  print "p: "  p.x "," p.y    'p: 3,4
  print "q: "  q.x "," q.y    'q: 1,2


  proc {SwapCells A B}
     Tmp = @A
  in
     A := @B
     B := Tmp
  end


program generictest;

{$mode objfpc}

type
  generic TSwap<T> = procedure (var a, b: T);

procedure Proc1(var a, b: integer);
  var
    temp: integer;
  begin
    temp := a;
    a := b;
    b := temp;
  end;

var
  S, T: integer;
  SwapInt: specialize TSwap<integer>;

begin
  S := 4;
  T := 3;
  SwapInt := @Proc1;
  writeln(S, T:2);
  SwapInt(S, T);
  writeln(S, T:2);
end.


function swap(&$a, &$b) {
    list($a, $b) = array($b, $a);
}


(let (A 1  B 2)
   (xchg 'A 'B)
   (println A B) )

(let (Lst1 '(a b c)  Lst2 '(d e f))
   (xchg (cdr Lst1) (cdr Lst2))
   (println Lst1 Lst2) )


%swap: procedure (a, b);
   declare (a, b) character;
   return ( 't=' || a || ';' || a || '=' || b || ';' || b '=t;' );
%end swap;
%activate swap;


SUB nswap (a, b)
    temp = a: a = b: b = temp
END SUB

a = 1
b = 2

PRINT a, b
CALL nswap(a, b)
PRINT a, b


[ over take over take
  2swap dip put put ] is exchange ( s s --> )


swap <- function(name1, name2, envir = parent.env(environment()))
{
    temp <- get(name1, pos = envir)
    assign(name1, get(name2, pos = envir), pos = envir)
    assign(name2, temp, pos = envir)
}


#lang racket/load

(module swap racket
  (provide swap)

  ;; a simple macro to swap two variables
  (define-syntax-rule (swap a b)
    (let ([tmp a])
      (set! a b)
      (set! b tmp))))

;; works fine in a statically typed setting
(module typed typed/racket
  (require 'swap)

  (: x Integer)
  (define x 3)

  (: y Integer)
  (define y 4)

  (swap x y)
  (printf "x is ~a~n" x)
  (printf "y is ~a~n" y))


rebol [
	Title: "Generic Swap"
	URL: http://rosettacode.org/wiki/Generic_swap
	Reference: [http://reboltutorial.com/blog/rebol-words/]
]

swap: func [
	"Swap contents of variables."
	a [word!] b [word!] /local x
][
	x: get a
	set a get b
	set b x
]

answer: 42  ship: "Heart of Gold"
swap 'answer 'ship ; Note quoted variables.
print rejoin ["The answer is " answer ", the ship is " ship "."]


a = 'I see you.'
b = -6

_temp_ = a                           /*swap ···     */
     a = b                           /*     A ···   */
     b = _temp_                      /*  and  B     */


a = 1
b = 2
temp = a
a = b
b = temp
see "a = " + a + nl
see "b = " + b + nl


a = 1
b = 2
'----- swap ----
tmp = a
a   = b
b  = tmp
end


fn generic_swap<'a, T>(var1: &'a mut T, var2: &'a mut T) {
    std::mem::swap(var1, var2)
}


class SWAP{T} is
  swap(inout a, inout b:T) is
    t ::= a;
    a := b;
    b := t;
  end;
end;


def swap[A,B](a: A, b: B): (B, A) = (b, a)


; swap elements of a vector
; vector-swap! is not part of r5rs, so we define it
(define (vector-swap! v i j)
(let ((a (vector-ref v i)) (b (vector-ref v j)))
(vector-set! v i b)
(vector-set! v j a)))

(let ((vec (vector 1 2 3 4 5)))
  (vector-swap! vec 0 4)
  vec)
; #(5 2 3 4 1)

; we can swap also in lists
(define (list-swap! v i j)
(let* ((x (list-tail v i))
       (y (list-tail v j))
       (a (car x))
       (b (car y)))
(set-car! x b)
(set-car! y a)))

(let ((lis (list 1 2 3 4 5)))
   (list-swap! lis 0 4)
   lis)
; (5 2 3 4 1)

; using macros (will work on variables, not on vectors or lists)
(define-syntax swap!
(syntax-rules ()
((_ a b)
   (let ((tmp a))
   (set! a b)
   (set! b tmp)))))

; try it
(let ((a 1) (b 2)) (swap! a b) (list a b))
; (2 1)


const proc: generate_swap (in type: aType) is func
  begin

    const proc: swap (inout aType: left, inout aType: right) is func
      local
        var aType: temp is aType.value;
      begin
        temp := left;
        left := right;
        right := temp;
      end func;

  end func;


set [x,y] to [13,"Hello"] -- assign values to two variables
put x,y
put
set [x,y] to [y,x] -- swap the variable values
put x,y


func swap(Ref a, Ref b) {
    var tmp = *a;
    *a = *b;
    *b = tmp;
}


[email protected](Syntax LoadVariable traits) swapWith: [email protected](Syntax LoadVariable traits) &environment: env
"A macro that expands into simple code swapping the values of two variables
in the current scope."
[
  env ifNil: [error: 'Cannot swap variables outside of a method'].
  tmpVar ::= env addVariable.
  {tmpVar store: x variable load.
   x variable store: y variable load.
   y variable store: tmpVar load} parenthesize
].


OrderedCollection extend [
    swap: a and: b [
	|t|
	t := self at: a.
	self at: a put: (self at: b).
	self at: b put: t
    ]
]


* SWAP(.V1, .V2) - Exchange the contents of two variables.
*  The variables must be prefixed with the name operator
*  when the function is called.

        DEFINE('SWAP(X,Y)TEMP')              :(SWAP_END)
SWAP    TEMP = $X
        $X = $Y
        $Y = TEMP                            :(RETURN)
SWAP_END


mata
a=1,2,3
b="ars longa vita brevis"
swap(a, b)
end


func swap<T>(inout a: T, inout b: T) {
  (a, b) = (b, a)
}


proc swap {aName bName} {
    upvar 1 $aName a $bName b
    lassign [list $a $b] b a
}


Define swap(swapvar1, swapvar2) = Prgm
  Local swaptmp
  #swapvar1 → swaptmp
  #swapvar2 → #swapvar1
  swaptmp → #swapvar2
EndPrgm

1 → x
2 → y
swap("x", "y")
x
    2
y
    1


    LET a = 11
    LET b = 22
    PRINT a, "  ", b
    GOSUB 100
    PRINT a, "  ", b
    END

100 REM swap(a, b)
    LET t = a
    LET a = b
    LET b = t
    RETURN


SUB SWAP(a, b)
    LET temp = a
    LET a = b
    LET b = temp
END SUB

LET a = 1
LET b = 2

PRINT a, b
CALL SWAP(a, b)
PRINT a, b
END


(defmacro swp (left right)
  (with-gensyms (tmp)
    ^(let ((,tmp ,left))
       (set ,left ,right
            ,right ,tmp))))


a = 5 : b = 7
Print a,b
Push a,b : a = Pop() : b = Pop()
Print a,b


$ swap() { typeset -n var1=$1 var2=$2; set -- "$var1" "$var2"; var1=$2; var2=$1; }
$ a=1 b=2
$ echo $a $b
1 2
$ swap a b
$ echo $a $b
2 1
$ swap a b
$ echo $a $b
1 2


pmgs("x","y") = ("y","x")    # the pattern matching way

ugs = ~&rlX                  # the idiosyncratic Ursala way

#cast %sWL

test = <pmgs ('a','b'),ugs ('x','y')>


[swap [a b : b a] view].

1 2 swap
= 2 1
'hello' 'hi' swap


sub swap( byref x, byref y )
	dim temp
	temp = x
	x = y
	y = temp
end sub


// user-defined swap verb -- parms are passed by alias, not value, so they can be updated:

'<==> [_a] @FN [_b] { _a _b = _b _a } by_alias: ;

// test out swap verb

@VAR a = 12345;
@VAR b = "*****";

@SAY "a=" a "   b=" b;

\b <==> \a;                    // "\" verb prevents evaluation of a and b here,
                               // so they can be passed by alias to <==>
@SAY "a=" a "   b=" b;

a b = b a;                     // swap them back, just using the usual  =  verb

@SAY "a=" a "   b=" b;


Sub Swap(Of T)(ByRef a As T, ByRef b As T)
    Dim temp = a
    a = b
    b = temp
End Sub


Since Visual FoxPro is not strongly typed, this will work with any data types.


var swap = Fn.new { |l|
    var t = l[0]
    l[0] = l[1]
    l[1] = t
}

var a = 6
var b = 3
var c = [a, b]
swap.call(c) // pass a list instead of individual variables
a = c[0] // unpack
b = c[1] // ditto
System.print("a is now %(a)")
System.print("b is now %(b)")
System.print()

// all user defined classes are reference types
class Box {
    construct new(v) { _v = v }
    v { _v }
    v=(value) { _v = value }
}

// by passing boxed arguments we can mutate them
var boxSwap = Fn.new { |a, b|
    var t = a.v
    a.v = b.v
    b.v = t
}

var d = Box.new(4)
var e = Box.new(8)
boxSwap.call(d, e)
d = d.v // unbox
e = e.v // ditto
System.print("d is now %(d)")
System.print("e is now %(e)")


set x=1;
set y=2;
log("Before Swap");
log(x);
log(y);
swap x y;
log("After Swap");
log(x);
log(y);


include c:\cxpl\codes;

proc Exch(A, B, S);
char A, B, S;
int  I, T;
for I:= 0 to S-1 do
        [T:= A(I);  A(I):= B(I);  B(I):= T];

real X, Y;
[X:= 3.0;  Y:= 4.0;
Exch(addr X, addr Y, 8);
RlOut(0, X);  RlOut(0, Y);  CrLf(0);
]


a = 1
b = 2

print a, b
//----- swap ----
temp = a : a = b : b = temp
print a, b


> a = 1
> b = "foo"
> swap, a, b
> a
"foo"
> b
1


push ix
push iy
pop ix   ;the value that was once in IY is now in IX
pop iy   ;the value that was once in IX is now in IY


class C{var v; fcn init(n){v=n}}
var c1=C(1), c2=C(2);
println(c1.v," : ",c2.v);
fcn swap(ca,cb,name){
   tmp:=ca.resove(name);
   ca.setVar(name,cb.resolve(name)); cb.setVar(name,tmp)
}
swap(c1,c2,"v");
println(c1.v," : ",c2.v);


L(start, n) [(100, 30), (1'000'000, 15), (1'000'000'000, 10)]
   print("\nFirst "n‘ gapful numbers from ’start)
   [Int] l
   L(x) start..
      I x % (Int(String(x)[0]) * 10 + (x % 10)) == 0
         l.append(x)
         I l.len == n
            L.break
   print(l)


with Ada.Text_IO;  use Ada.Text_IO;

procedure Gapful_Numbers is

   function Divisor (N : in Positive) return Positive is
      NN : Positive := N;
   begin
      while NN >= 10 loop
         NN := NN / 10;
      end loop;
      return 10 * NN + (N mod 10);
   end Divisor;

   function Is_Gapful (N : in Positive) return Boolean is
   begin
      return N mod Divisor (N) = 0;
   end Is_Gapful;

   procedure Find_Gapful (Count : in Positive; From : in Positive) is
      Found : Natural := 0;
   begin
      for Candidate in From .. Positive'Last loop
         if Is_Gapful (Candidate) then
            Put (Candidate'Image);
            Found := Found + 1;
            exit when Found = Count;
         end if;
      end loop;
      New_Line;
   end Find_Gapful;

begin
   Put_Line ("First 30 gapful numbers over 100:");
   Find_Gapful (From => 100, Count => 30);
   New_Line;

   Put_Line ("First 15 gapful numbers over 1_000_000:");
   Find_Gapful (From => 1_000_000, Count => 15);
   New_Line;

   Put_Line ("First 10 gapful numbers over 1_000_000_000:");
   Find_Gapful (From => 1_000_000_000, Count => 10);
   New_Line;
end Gapful_Numbers;


BEGIN # find some gapful numbers - numbers divisible by f*10 + b #
      # where f is the first digit and b is the final digit      #
    # unary GAPFUL operator - returns TRUE  if n is gapful       #
    #                                 FALSE otherwise            #
    OP   GAPFUL = ( INT n )BOOL:
         BEGIN
            INT abs n  = ABS n;
            INT back   = abs n MOD 10; # final digit             #
            INT front := abs n OVER 10;
            WHILE front > 9 DO front OVERAB 10 OD;
            abs n MOD ( ( front * 10 ) + back ) = 0
         END; # GAPFUL #
    # dyadic GAPFUL operator - returns an array of n gapful      #
    # numbers starting from first                                #
    PRIO GAPFUL = 9;
    OP   GAPFUL = ( INT n, INT first )[]INT:
         BEGIN
            [ 1 : n ]INT result;
            INT g pos := 0;
            FOR i FROM first WHILE g pos < n DO
                IF GAPFUL i THEN result[ g pos +:= 1 ] := i FI
            OD;
            result
         END; # GAPFUL #
    # prints a sequence of gapful numbers                        #
    PROC print gapful = ( []INT seq, INT start )VOID:
         BEGIN
            print( ( "First ", whole( ( UPB seq + 1 ) - LWB seq, 0 )
                   , " gapful numbers starting from ", whole( start, 0 )
                   , ":", newline
                   )
                 );
            FOR i FROM LWB seq TO UPB seq DO print( ( " ", whole( seq[ i ], 0 ) ) ) OD;
            print( ( newline ) )
         END; # print gapful #
    print gapful( 30 GAPFUL            100,           100 );
    print gapful( 15 GAPFUL      1 000 000,     1 000 000 );
    print gapful( 10 GAPFUL  1 000 000 000, 1 000 000 000 )
END


V Eps = 1e-10

F transformToRref(&mat)
   V lead = 0

   L(r) 0 .< mat.len
      I lead >= mat[0].len
         R

      V i = r
      L mat[i][lead] == 0
         i++
         I i == mat.len
            i = r
            lead++
            I lead == mat[0].len
               R
      swap(&mat[i], &mat[r])

      V d = mat[r][lead]
      I abs(d) > Eps
         L(&item) mat[r]
            item /= d

      L(i) 0 .< mat.len
         I i != r
            V m = mat[i][lead]
            L(c) 0 .< mat[0].len
               mat[i][c] -= mat[r][c] * m

      lead++

F inverse(mat)
   V augmat = [[0.0] * (2 * mat.len)] * mat.len
   L(i) 0 .< mat.len
      L(j) 0 .< mat.len
         augmat[i][j] = mat[i][j]
      augmat[i][mat.len + i] = 1

   transformToRref(&augmat)

   V result = [[0.0] * mat.len] * mat.len
   L(i) 0 .< mat.len
      L(j) 0 .< mat.len
         I augmat[i][j] != Float(i == j)
            X ValueError(‘matrix is singular’)
         result[i][j] = augmat[i][mat.len + j]
   R result

F print_mat(mat)
   L(row) mat
      V line = ‘’
      L(val) row
         I !line.empty
            line ‘’= ‘ ’
         line ‘’= ‘#3.5’.format(val)
      print(line)

F runTest(mat)
   print(‘Matrix:’)
   print_mat(mat)
   print()
   print(‘Inverse:’)
   print_mat(inverse(mat))
   print()
   print()

V m1 = [[Float(1), 2, 3],
        [Float(4), 1, 6],
        [Float(7), 8, 9]]

V m2 = [[Float( 2), -1,  0],
        [Float(-1),  2, -1],
        [Float( 0), -1,  2]]

V m3 = [[Float(-1), -2,  3,  2],
        [Float(-4), -1,  6,  2],
        [Float( 7), -8,  9,  1],
        [Float( 1), -2,  1,  3]]

runTest(m1)
runTest(m2)
runTest(m3)


on isGapful(n)
    set units to n mod 10
    set temp to n div 10
    repeat until (temp < 10)
        set temp to temp div 10
    end repeat

    return (n mod (temp * 10 + units) = 0)
end isGapful

-- Task code:
on getGapfuls(n, q)
    set collector to {}
    repeat until ((count collector) = q)
        if (isGapful(n)) then set end of collector to n
        set n to n + 1
    end repeat
    return collector
end getGapfuls

local output, astid
set output to {}
set astid to AppleScript's text item delimiters
set AppleScript's text item delimiters to "  "
set end of output to "First 30 gapful numbers ≥ 100:" & linefeed & getGapfuls(100, 30)
set end of output to "First 15 gapful numbers ≥ 1,000,000:" & linefeed & getGapfuls(1000000, 15)
set end of output to "First 10 gapful numbers ≥ 100,000,000:" & linefeed & getGapfuls(1.0E+9, 10)
set AppleScript's text item delimiters to linefeed & linefeed
set output to output as text
set AppleScript's text item delimiters to astid
return output


*        Gauss-Jordan matrix inversion 17/01/2021
GAUSSJOR CSECT
         USING  GAUSSJOR,R13       base register
         B      72(R15)            skip savearea
         DC     17F'0'             savearea
         SAVE   (14,12)            save previous context
         ST     R13,4(R15)         link backward
         ST     R15,8(R13)         link forward
         LR     R13,R15            set addressability
         LA     R6,1               i=1
       DO  WHILE=(C,R6,LE,N)       do i=1 to n
         LA     R7,1                 j=1
       DO  WHILE=(C,R7,LE,N)         do j=1 to n
         LR     R1,R6                  i
         BCTR   R1,0                   -1
         MH     R1,HN                  *n
         LR     R0,R7                   j
         BCTR   R0,0                   -1
         AR     R1,R0                  (i-1)*n+j-1
         SLA    R1,2                   *4
         LE     F0,AA(R1)              aa(i,j)
         LR     R1,R6                  i
         BCTR   R1,0                   -1
         MH     R1,HN2                 *n*2
         LR     R0,R7                  j
         BCTR   R0,0                   -1
         AR     R1,R0                  (i-1)*n*2+j-1
         SLA    R1,2                   *4
         STE    F0,TMP(R1)             tmp(i,j)=aa(i,j)
         LA     R7,1(R7)               j++
       ENDDO    ,                    enddo j
         LA     R7,1                 j=1
         A      R7,N                 j=n+1
       DO  WHILE=(C,R7,LE,N2)        do j=n+1 to 2*n
         LR     R1,R6                  i
         BCTR   R1,0                   -1
         MH     R1,HN2                 *n*2
         LR     R0,R7                  j
         BCTR   R0,0                   -1
         AR     R1,R0                  (i-1)*n*2+j-1
         SLA    R1,2                   *4
         LE     F0,=E'0'               0
         STE    F0,TMP(R1)             tmp(i,j)=0
         LA     R7,1(R7)               j++
       ENDDO    ,                    enddo j
         LR     R2,R6                i
         A      R2,N                 i+n
         LR     R1,R6                i
         BCTR   R1,0                 -1
         MH     R1,HN2               *n*2
         BCTR   R2,0                 -1
         AR     R1,R2                (i+n-1)*n*2+i-1
         SLA    R1,2                 *4
         LE     F0,=E'1'             1
         STE    F0,TMP(R1)           tmp(i,i+n)=1
         LA     R6,1(R6)             i++
       ENDDO    ,                  enddo i
         LA     R6,1               i=1
       DO  WHILE=(C,R6,LE,N)       do r=1 to n
         LR     R1,R6                r
         BCTR   R1,0                 -1
         MH     R1,HN2               *n*2
         LR     R0,R6                r
         BCTR   R0,0                 -1
         AR     R1,R0                (r-1)*n*2+r-1
         SLA    R1,2                 *4
         LE     F0,TMP(R1)           tmp(r,r)
         STE    F0,T                 t=tmp(r,r)
         LA     R7,1                 c=1
       DO WHILE=(C,R7,LE,N2)         do c=1 to n*2
         LR     R1,R6                  r
         BCTR   R1,0
         MH     R1,HN2
         LR     R0,R7                  c
         BCTR   R0,0
         AR     R1,R0
         SLA    R1,2
         LE     F0,TMP(R1)
         LTER   F0,F0
         BZ     *+8
         DE     F0,T                   tmp(r,c)/t
         LR     R1,R6                  r
         BCTR   R1,0
         MH     R1,HN2
         LR     R0,R7                  c
         BCTR   R0,0
         AR     R1,R0
         SLA    R1,2
         STE    F0,TMP(R1)             tmp(r,c)=tmp(r,c)/t
         LA     R7,1(R7)               c++
       ENDDO    ,                    enddo c
         LA     R8,1                   i=1
       DO WHILE=(C,R8,LE,N)            do i=1 to n
       IF    CR,R8,NE,R6 THEN            if i^=r then
         LR     R1,R8                      i
         BCTR   R1,0
         MH     R1,HN2
         LR     R0,R6                      r
         BCTR   R0,0
         AR     R1,R0
         SLA    R1,2
         LE     F0,TMP(R1)                 tmp(i,r)
         STE    F0,T                       t=tmp(i,r)
         LA     R7,1                       c=1
       DO WHILE=(C,R7,LE,N2)               do c=1 to n*2
         LR     R2,R8                        i
         BCTR   R2,0
         MH     R2,HN2
         LR     R0,R7                        c
         BCTR   R0,0
         AR     R2,R0
         SLA    R2,2
         LE     F0,TMP(R2)                   f0=tmp(i,c)
         LR     R1,R6                        r
         BCTR   R1,0
         MH     R1,HN2
         LR     R0,R7                        c
         BCTR   R0,0
         AR     R1,R0
         SLA    R1,2
         LE     F2,TMP(R1)                   f2=tmp(r,c)
         LE     F4,T                         t
         MER    F4,F2                        f4=t*tmp(r,c)
         SER    F0,F4                        f0=tmp(i,c)-t*tmp(r,c)
         STE    F0,TMP(R2)                   tmp(i,c)=f0
         LA     R7,1(R7)                     c++
       ENDDO    ,                          enddo c
       ENDIF    ,                        endif
         LA     R8,1(R8)                 i++
       ENDDO    ,                      enddo i
         LA     R6,1(R6)             r++
       ENDDO    ,                  enddo r
         LA     R6,1               i=1
       DO WHILE=(C,R6,LE,N)        do i=1 to n
         L      R7,N                 n
         LA     R7,1(R7)             j=n+1
       DO WHILE=(C,R7,LE,N2)       do j=n+1 to 2*n
         LR     R2,R7                  j
         S      R2,N                   -n
         LR     R1,R6                  i
         BCTR   R1,0
         MH     R1,HN2                 *2*n
         LR     R0,R7                  j
         BCTR   R0,0
         AR     R1,R0
         SLA    R1,2
         LE     F0,TMP(R1)             tmp(i,j)
         LR     R1,R6                  i
         BCTR   R1,0
         MH     R1,HN                  *n
         BCTR   R2,0
         AR     R1,R2
         SLA    R1,2
         STE    F0,BB(R1)              bb(i,j-n)=tmp(i,j)
         LA     R7,1(R7)               j++
       ENDDO    ,                    enddo j
         LA     R6,1(R6)             i++
       ENDDO    ,                  enddo i
         LA     R6,1               i=1
       DO WHILE=(C,R6,LE,N)        do i=1 to n
         LA     R3,PG                @pg
         LA     R7,1                 j=1
       DO WHILE=(C,R7,LE,N)          do j=1 to n
         LR     R1,R6                  i
         BCTR   R1,0
         MH     R1,HN                  *n
         LR     R0,R7                  j
         BCTR   R0,0
         AR     R1,R0
         SLA    R1,2
         LE     F0,BB(R1)              bb(i,j)
         LA     R0,5                   number of decimals
         BAL    R14,FORMATF            FormatF(bb(i,j))
         MVC    0(13,R3),0(R1)         edit
         LA     R3,13(R3)              @pg+=13
         LA     R7,1(R7)               j++
       ENDDO    ,                    enddo j
         XPRNT  PG,L'PG              print buffer
         LA     R6,1(R6)             i++
       ENDDO    ,                  enddo i
         L      R13,4(0,R13)       restore previous savearea pointer
         RETURN (14,12),RC=0       restore registers from calling save
         COPY   plig\$_FORMATF.MLC format a float
NN       EQU    5
N        DC     A(NN)
N2       DC     A(NN*2)
AA       DC     E'3.0',E'1.0',E'5.0',E'9.0',E'7.0'
         DC     E'8.0',E'2.0',E'8.0',E'0.0',E'1.0'
         DC     E'1.0',E'7.0',E'2.0',E'0.0',E'3.0'
         DC     E'0.0',E'1.0',E'7.0',E'0.0',E'9.0'
         DC     E'3.0',E'5.0',E'6.0',E'1.0',E'1.0'
BB       DS     (NN*NN)E
TMP      DS     (NN*NN*2)E
T        DS     E
HN       DC     AL2(NN)
HN2      DC     AL2(NN*2)
PG       DC     CL80' '            buffer
         REGEQU
         END    GAUSSJOR


begin
    comment Gauss-Jordan matrix inversion - 22/01/2021;
    integer n;
    n:=4;
    begin
        procedure rref(m); real array m;
        begin
            integer r, c, i;
            real d, w;
            for r := 1 step 1 until n do begin
                d := m[r,r];
                if d notequal 0 then
                    for c := 1 step 1 until n*2 do
                        m[r,c] := m[r,c] / d
                else
                    outstring(1,"inversion impossible!\n");
                for i := 1 step 1 until n do
                    if i notequal r then begin
                        w := m[i,r];
                        for c := 1 step 1 until n*2 do
                            m[i,c] := m[i,c] - w * m[r,c]
                    end
            end
        end rref;

        procedure inverse(mat,inv); real array mat, inv;
        begin
            integer i, j;
            real array aug[1:n,1:n*2];
            for i := 1 step 1 until n do begin
                for j := 1 step 1 until n do
                    aug[i,j] := mat[i,j];
                for j := 1+n step 1 until n*2 do
                    aug[i,j] := 0;
                aug[i,i+n] := 1
            end;
            rref(aug);
            for i := 1 step 1 until n do
                for j := n+1 step 1 until 2*n do
                    inv[i,j-n] := aug[i,j]
        end inverse;

        procedure show(c, m); string c; real array m;
        begin
            integer i, j;
            outstring(1,"matrix "); outstring(1,c); outstring(1,"\n");
            for i := 1 step 1 until n do begin
                for j := 1 step 1 until n do
                    outreal(1,m[i,j]);
                outstring(1,"\n")
            end
        end show;

        integer i;
        real array a[1:n,1:n], b[1:n,1:n], c[1:n,1:n];
        i:=1; a[i,1]:= 2; a[i,2]:= 1; a[i,3]:= 1; a[i,4]:= 4;
        i:=2; a[i,1]:= 0; a[i,2]:=-1; a[i,3]:= 0; a[i,4]:=-1;
        i:=3; a[i,1]:= 1; a[i,2]:= 0; a[i,3]:=-2; a[i,4]:= 4;
        i:=4; a[i,1]:= 4; a[i,2]:= 1; a[i,3]:= 2; a[i,4]:= 2;
        show("a",a);
        inverse(a,b);
        show("b",b);
        inverse(b,c);
        show("c",c)
    end
end


BEGIN # Gauss-Jordan matrix inversion #
    PROC rref = ( REF[,]REAL m )VOID:
         BEGIN
            INT n = 1 UPB m;
            FOR r TO n DO
                REAL d = m[ r, r ];
                IF d /= 0 THEN
                    FOR c TO  n * 2 DO m[ r, c ] := m[ r, c ] / d OD
                ELSE
                    print( ( "inversion impossible!", newline ) )
                FI;
                FOR i TO n DO
                    IF i /= r THEN
                        REAL w = m[ i, r ];
                        FOR c TO n * 2 DO m[ i, c ] := m[ i, c ] - w * m[ r, c ] OD
                    FI
                OD
            OD
         END # rref # ;
    PROC inverse = ( REF[,]REAL mat )[,]REAL:
         BEGIN
            INT n = 1 UPB mat;
            [ 1 : n, 1 : n     ]REAL inv;
            [ 1 : n, 1 : n * 2 ]REAL aug;
            FOR i TO n DO
                FOR j            TO n     DO aug[ i, j ] := mat[ i, j ] OD;
                FOR j FROM 1 + n TO n * 2 DO aug[ i, j ] := 0           OD;
                aug[ i, i + n ] := 1
            OD;
            rref( aug );
            FOR i TO n DO
                FOR j FROM n + 1 TO 2 * n DO inv[ i, j - n ] := aug[ i, j ] OD
            OD;
            inv
         END # inverse # ;
    PROC show = ( STRING c, [,]REAL m )VOID:
         BEGIN
            INT n = 1 UPB m;
            print( ( "matrix ", c, newline ) );
            FOR i TO n DO
                FOR j TO n DO print( ( " ", fixed( m[ i, j ], -8, 3 ) ) ) OD;
                print( ( newline ) )
            OD
         END # show #;

    INT n = 4;
    [ 1 : n, 1 : n ]REAL a, b, c;
    a := [,]REAL( (  2,  1,  1,  4 )
                , (  0, -1,  0, -1 )
                , (  1,  0, -2,  4 )
                , (  4,  1,  2,  2 )
                );
    show( "a", a );
    b := inverse( a );
    show( "b", b );
    c := inverse( b );
    show( "c", c )
END


Gapful_numbers(Min, Qty){
	counter:= 0, output := ""
	while (counter < Qty){
		n := A_Index+Min-1
		d := SubStr(n, 1, 1) * 10 + SubStr(n, 0)
		if (n/d = Floor(n/d))
			output .= ++counter ": " n "`t" n " / " d " = " Format("{:d}", n/d) "`n"
	}
	return output
}


# syntax: GAWK -f GAPFUL_NUMBERS.AWK
# converted from C++
BEGIN {
    show_gapful(100,30)
    show_gapful(1000000,15)
    show_gapful(1000000000,10)
    show_gapful(7123,25)
    exit(0)
}
function is_gapful(n,  m) {
    m = n
    while (m >= 10) {
      m = int(m / 10)
    }
    return(n % ((n % 10) + 10 * (m % 10)) == 0)
}
function show_gapful(n,  count,i) {
    printf("first %d gapful numbers >= %d:",count,n)
    for (i=0; i<count; n++) {
      if (is_gapful(n)) {
        printf(" %d",n)
        i++
      }
    }
    printf("\n")
}


/*----------------------------------------------------------------------
gjinv - Invert a matrix, Gauss-Jordan algorithm
A is destroyed.  Returns 1 for a singular matrix.

___Name_____Type______In/Out____Description_____________________________
   a[n*n]   double*   In        An N by N matrix
   n        int       In        Order of matrix
   b[n*n]   double*   Out       Inverse of A
----------------------------------------------------------------------*/
#include <math.h>
int gjinv (double *a, int n, double *b)
{
	int i, j, k, p;
	double f, g, tol;
	if (n < 1) return -1;  /* Function Body */
	f = 0.;  /* Frobenius norm of a */
	for (i = 0; i < n; ++i) {
		for (j = 0; j < n; ++j) {
			g = a[j+i*n];
			f += g * g;
		}
	}
	f = sqrt(f);
	tol = f * 2.2204460492503131e-016;
	for (i = 0; i < n; ++i) {  /* Set b to identity matrix. */
		for (j = 0; j < n; ++j) {
			b[j+i*n] = (i == j) ? 1. : 0.;
		}
	}
	for (k = 0; k < n; ++k) {  /* Main loop */
		f = fabs(a[k+k*n]);  /* Find pivot. */
		p = k;
		for (i = k+1; i < n; ++i) {
			g = fabs(a[k+i*n]);
			if (g > f) {
				f = g;
				p = i;
			}
		}
		if (f < tol) return 1;  /* Matrix is singular. */
		if (p != k) {  /* Swap rows. */
			for (j = k; j < n; ++j) {
				f = a[j+k*n];
				a[j+k*n] = a[j+p*n];
				a[j+p*n] = f;
			}
			for (j = 0; j < n; ++j) {
				f = b[j+k*n];
				b[j+k*n] = b[j+p*n];
				b[j+p*n] = f;
			}
		}
		f = 1. / a[k+k*n];  /* Scale row so pivot is 1. */
		for (j = k; j < n; ++j) a[j+k*n] *= f;
		for (j = 0; j < n; ++j) b[j+k*n] *= f;
		for (i = 0; i < n; ++i) {  /* Subtract to get zeros. */
			if (i == k) continue;
			f = a[k+i*n];
			for (j = k; j < n; ++j) a[j+i*n] -= a[j+k*n] * f;
			for (j = 0; j < n; ++j) b[j+i*n] -= b[j+k*n] * f;
		}
	}
	return 0;
} /* end of gjinv */


function is_gapful(n)
	m = n
	l = n mod 10
	while (m >= 10)
		m = int(m / 10)
	end while
	return (m * 10) + l
end function

subroutine muestra_gapful(n, gaps)
	inc = 0
	print "Primeros "; gaps; " números gapful >= "; n
	while inc < gaps
		if n mod is_gapful(n) = 0 then
			print " " ; n ;
			inc = inc + 1
		end if
		n = n + 1
	end while
	print chr(10)
end subroutine

call muestra_gapful(100, 30)
call muestra_gapful(1000000, 15)
call muestra_gapful(1000000000, 10)
call muestra_gapful(7123,25)
end


#include<stdio.h>

void generateGaps(unsigned long long int start,int count){

    int counter = 0;
    unsigned long long int i = start;
    char str[100];

    printf("\nFirst %d Gapful numbers >= %llu :\n",count,start);

    while(counter<count){
        sprintf(str,"%llu",i);
        if((i%(10*(str[0]-'0') + i%10))==0L){
            printf("\n%3d : %llu",counter+1,i);
            counter++;
        }
        i++;
    }
}

int main()
{
    unsigned long long int i = 100;
    int count = 0;
    char str[21];

    generateGaps(100,30);
    printf("\n");
    generateGaps(1000000,15);
    printf("\n");
    generateGaps(1000000000,15);
    printf("\n");

    return 0;
}


using System;

namespace Rosetta
{
    internal class Vector
    {
        private double[] b;
        internal readonly int rows;

        internal Vector(int rows)
        {
            this.rows = rows;
            b = new double[rows];
        }

        internal Vector(double[] initArray)
        {
            b = (double[])initArray.Clone();
            rows = b.Length;
        }

        internal Vector Clone()
        {
            Vector v = new Vector(b);
            return v;
        }

        internal double this[int row]
        {
            get { return b[row]; }
            set { b[row] = value; }
        }

        internal void SwapRows(int r1, int r2)
        {
            if (r1 == r2) return;
            double tmp = b[r1];
            b[r1] = b[r2];
            b[r2] = tmp;
        }

        internal double norm(double[] weights)
        {
            double sum = 0;
            for (int i = 0; i < rows; i++)
            {
                double d = b[i] * weights[i];
                sum +=  d*d;
            }
            return Math.Sqrt(sum);
        }

        internal void print()
        {
            for (int i = 0; i < rows; i++)
                Console.WriteLine(b[i]);
            Console.WriteLine();
        }

        public static Vector operator-(Vector lhs, Vector rhs)
        {
            Vector v = new Vector(lhs.rows);
            for (int i = 0; i < lhs.rows; i++)
                v[i] = lhs[i] - rhs[i];
            return v;
        }
    }

    class Matrix
    {
        private double[] b;
        internal readonly int rows, cols;

        internal Matrix(int rows, int cols)
        {
            this.rows = rows;
            this.cols = cols;
            b = new double[rows * cols];
        }

        internal Matrix(int size)
        {
            this.rows = size;
            this.cols = size;
            b = new double[rows * cols];
            for (int i = 0; i < size; i++)
                this[i, i] = 1;
        }

        internal Matrix(int rows, int cols, double[] initArray)
        {
            this.rows = rows;
            this.cols = cols;
            b = (double[])initArray.Clone();
            if (b.Length != rows * cols) throw new Exception("bad init array");
        }

        internal double this[int row, int col]
        {
            get { return b[row * cols + col]; }
            set { b[row * cols + col] = value; }
        }

        public static Vector operator*(Matrix lhs, Vector rhs)
        {
            if (lhs.cols != rhs.rows) throw new Exception("I can't multiply matrix by vector");
            Vector v = new Vector(lhs.rows);
            for (int i = 0; i < lhs.rows; i++)
            {
                double sum = 0;
                for (int j = 0; j < rhs.rows; j++)
                    sum += lhs[i,j]*rhs[j];
                v[i] = sum;
            }
            return v;
        }

        internal void SwapRows(int r1, int r2)
        {
            if (r1 == r2) return;
            int firstR1 = r1 * cols;
            int firstR2 = r2 * cols;
            for (int i = 0; i < cols; i++)
            {
                double tmp = b[firstR1 + i];
                b[firstR1 + i] = b[firstR2 + i];
                b[firstR2 + i] = tmp;
            }
        }

        //with partial pivot
        internal bool InvPartial()
        {
            const double Eps = 1e-12;
            if (rows != cols) throw new Exception("rows != cols for Inv");
            Matrix M = new Matrix(rows); //unitary
            for (int diag = 0; diag < rows; diag++)
            {
                int max_row = diag;
                double max_val = Math.Abs(this[diag, diag]);
                double d;
                for (int row = diag + 1; row < rows; row++)
                    if ((d = Math.Abs(this[row, diag])) > max_val)
                    {
                        max_row = row;
                        max_val = d;
                    }
                if (max_val <= Eps) return false;
                SwapRows(diag, max_row);
                M.SwapRows(diag, max_row);
                double invd = 1 / this[diag, diag];
                for (int col = diag; col < cols; col++)
                {
                    this[diag, col] *= invd;
                }
                for (int col = 0; col < cols; col++)
                {
                    M[diag, col] *= invd;
                }
                for (int row = 0; row < rows; row++)
                {
                    d = this[row, diag];
                    if (row != diag)
                    {
                        for (int col = diag; col < this.cols; col++)
                        {
                            this[row, col] -= d * this[diag, col];
                        }
                        for (int col = 0; col < this.cols; col++)
                        {
                            M[row, col] -= d * M[diag, col];
                        }
                    }
                }
            }
            b = M.b;
            return true;
        }

        internal void print()
        {
            for (int i = 0; i < rows; i++)
            {
                for (int j = 0; j < cols; j++)
                    Console.Write(this[i,j].ToString()+"  ");
                Console.WriteLine();
            }
        }
    }
}


#include <iostream>

bool gapful(int n) {
    int m = n;
    while (m >= 10)
        m /= 10;
    return n % ((n % 10) + 10 * (m % 10)) == 0;
}

void show_gapful_numbers(int n, int count) {
    std::cout << "First " << count << " gapful numbers >= " << n << ":\n";
    for (int i = 0; i < count; ++n) {
        if (gapful(n)) {
            if (i != 0)
                std::cout << ", ";
            std::cout << n;
            ++i;
        }
    }
    std::cout << '\n';
}

int main() {
    show_gapful_numbers(100, 30);
    show_gapful_numbers(1000000, 15);
    show_gapful_numbers(1000000000, 10);
    return 0;
}


using System;

namespace GapfulNumbers
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("The first 30 gapful numbers are: ");
            /* Starting at 100, find 30 gapful numbers */
            FindGap(100, 30);

            Console.WriteLine("The first 15 gapful numbers > 1,000,000 are: ");
            FindGap(1000000, 15);

            Console.WriteLine("The first 10 gapful numbers > 1,000,000,000 are: ");
            FindGap(1000000000, 10);

            Console.Read();
        }

        public static int firstNum(int n)
        {
            /*Divide by ten until the leading digit remains.*/
            while (n >= 10)
            {
                n /= 10;
            }
            return (n);
        }

        public static int lastNum(int n)
        {
            /*Modulo gives you the last digit. */
            return (n % 10);
        }

        static void FindGap(int n, int gaps)
        {
            int count = 0;
            while (count < gaps)
            {

                /* We have to convert our first and last digits to strings to concatenate.*/
                string concat = firstNum(n).ToString() + lastNum(n).ToString();
                /* And then convert our concatenated string back to an integer. */
                int i = Convert.ToInt32(concat);

                /* Modulo with our new integer and output the result. */
                if (n % i == 0)
                {
                    Console.Write(n + " ");
                    count++;
                    n++;
                }
                else
                {
                    n++;
                    continue;
                }
            }
        }
    }
}


#include <algorithm>
#include <cassert>
#include <iomanip>
#include <iostream>
#include <vector>

template <typename scalar_type> class matrix {
public:
    matrix(size_t rows, size_t columns)
        : rows_(rows), columns_(columns), elements_(rows * columns) {}

    matrix(size_t rows, size_t columns, scalar_type value)
        : rows_(rows), columns_(columns), elements_(rows * columns, value) {}

    matrix(size_t rows, size_t columns, std::initializer_list<scalar_type> values)
        : rows_(rows), columns_(columns), elements_(rows * columns) {
        assert(values.size() <= rows_ * columns_);
        std::copy(values.begin(), values.end(), elements_.begin());
    }

    size_t rows() const { return rows_; }
    size_t columns() const { return columns_; }

    scalar_type& operator()(size_t row, size_t column) {
        assert(row < rows_);
        assert(column < columns_);
        return elements_[row * columns_ + column];
    }
    const scalar_type& operator()(size_t row, size_t column) const {
        assert(row < rows_);
        assert(column < columns_);
        return elements_[row * columns_ + column];
    }
private:
    size_t rows_;
    size_t columns_;
    std::vector<scalar_type> elements_;
};

template <typename scalar_type>
matrix<scalar_type> product(const matrix<scalar_type>& a,
                            const matrix<scalar_type>& b) {
    assert(a.columns() == b.rows());
    size_t arows = a.rows();
    size_t bcolumns = b.columns();
    size_t n = a.columns();
    matrix<scalar_type> c(arows, bcolumns);
    for (size_t i = 0; i < arows; ++i) {
        for (size_t j = 0; j < n; ++j) {
            for (size_t k = 0; k < bcolumns; ++k)
                c(i, k) += a(i, j) * b(j, k);
        }
    }
    return c;
}

template <typename scalar_type>
void swap_rows(matrix<scalar_type>& m, size_t i, size_t j) {
    size_t columns = m.columns();
    for (size_t column = 0; column < columns; ++column)
        std::swap(m(i, column), m(j, column));
}

// Convert matrix to reduced row echelon form
template <typename scalar_type>
void rref(matrix<scalar_type>& m) {
    size_t rows = m.rows();
    size_t columns = m.columns();
    for (size_t row = 0, lead = 0; row < rows && lead < columns; ++row, ++lead) {
        size_t i = row;
        while (m(i, lead) == 0) {
            if (++i == rows) {
                i = row;
                if (++lead == columns)
                    return;
            }
        }
        swap_rows(m, i, row);
        if (m(row, lead) != 0) {
            scalar_type f = m(row, lead);
            for (size_t column = 0; column < columns; ++column)
                m(row, column) /= f;
        }
        for (size_t j = 0; j < rows; ++j) {
            if (j == row)
                continue;
            scalar_type f = m(j, lead);
            for (size_t column = 0; column < columns; ++column)
                m(j, column) -= f * m(row, column);
        }
    }
}

template <typename scalar_type>
matrix<scalar_type> inverse(const matrix<scalar_type>& m) {
    assert(m.rows() == m.columns());
    size_t rows = m.rows();
    matrix<scalar_type> tmp(rows, 2 * rows, 0);
    for (size_t row = 0; row < rows; ++row) {
        for (size_t column = 0; column < rows; ++column)
            tmp(row, column) = m(row, column);
        tmp(row, row + rows) = 1;
    }
    rref(tmp);
    matrix<scalar_type> inv(rows, rows);
    for (size_t row = 0; row < rows; ++row) {
        for (size_t column = 0; column < rows; ++column)
            inv(row, column) = tmp(row, column + rows);
    }
    return inv;
}

template <typename scalar_type>
void print(std::ostream& out, const matrix<scalar_type>& m) {
    size_t rows = m.rows(), columns = m.columns();
    out << std::fixed << std::setprecision(4);
    for (size_t row = 0; row < rows; ++row) {
        for (size_t column = 0; column < columns; ++column) {
            if (column > 0)
                out << ' ';
            out << std::setw(7) << m(row, column);
        }
        out << '\n';
    }
}

int main() {
    matrix<double> m(3, 3, {2, -1, 0, -1, 2, -1, 0, -1, 2});
    std::cout << "Matrix:\n";
    print(std::cout, m);
    auto inv(inverse(m));
    std::cout << "Inverse:\n";
    print(std::cout, inv);
    std::cout << "Product of matrix and inverse:\n";
    print(std::cout, product(m, inv));
    std::cout << "Inverse of inverse:\n";
    print(std::cout, inverse(inv));
    return 0;
}


(defn first-digit [n] (Integer/parseInt (subs (str n) 0 1)))

(defn last-digit [n] (mod n 10))

(defn bookend-number [n] (+ (* 10 (first-digit n)) (last-digit n)))

(defn is-gapful? [n] (and (>= n 100) (zero? (mod n (bookend-number n)))))

(defn gapful-from [n] (filter is-gapful? (iterate inc n)))

(defn gapful [] (gapful-from 1))

(defn gapfuls-in-range [start size] (take size (gapful-from start)))

(defn report-range [[start size]]
  (doall (map println
    [(format "First %d gapful numbers >= %d:" size start)
     (gapfuls-in-range start size)
     ""])))

(doall (map report-range [ [1 30] [1000000 15] [1000000000 10] ]))


        IDENTIFICATION DIVISION.
        PROGRAM-ID. GAPFUL.

        DATA DIVISION.
        WORKING-STORAGE SECTION.
        01 COMPUTATION.
            02 N            PIC 9(10).
            02 N-DIGITS     REDEFINES N.
               03 ND        PIC 9 OCCURS 10 TIMES.
            02 DIV-CHECK    PIC 9(10)V9(2).
            02 DIV-PARTS    REDEFINES DIV-CHECK.
               03 DIV-INT   PIC 9(10).
               03 DIV-FRAC  PIC 9(2).
            02 GAP-AMOUNT   PIC 99.
            02 GAP-DSOR     PIC 99.
            02 FIRST-DIGIT  PIC 99.
        01 OUTPUT-FORMAT.
            02 N-OUT        PIC Z(10).

        PROCEDURE DIVISION.
        BEGIN.
            DISPLAY "First 30 gapful numbers >= 100:".
            MOVE 100 TO N. MOVE 30 TO GAP-AMOUNT.
            PERFORM CHECK-GAPFUL-NUMBER.

            DISPLAY " ".
            DISPLAY "First 15 gapful numbers >= 1000000:".
            MOVE 1000000 TO N. MOVE 15 TO GAP-AMOUNT.
            PERFORM CHECK-GAPFUL-NUMBER.

            DISPLAY " ".
            DISPLAY "First 10 gapful numbers >= 1000000000:".
            MOVE 1000000000 TO N. MOVE 10 TO GAP-AMOUNT.
            PERFORM CHECK-GAPFUL-NUMBER.
            STOP RUN.

        CHECK-GAPFUL-NUMBER.
            SET FIRST-DIGIT TO 1.
            INSPECT N TALLYING FIRST-DIGIT FOR LEADING '0'.
            COMPUTE GAP-DSOR = ND(FIRST-DIGIT) * 10 + ND(10).
            DIVIDE N BY GAP-DSOR GIVING DIV-CHECK.
            IF DIV-FRAC IS EQUAL TO 0
                MOVE N TO N-OUT
                DISPLAY N-OUT
                SUBTRACT 1 FROM GAP-AMOUNT.
            ADD 1 TO N.
            IF GAP-AMOUNT IS GREATER THAN 0
                GO TO CHECK-GAPFUL-NUMBER.


USING: kernel math.matrices math.matrices.elimination
prettyprint sequences ;

! Augment a matrix with its identity. E.g.
!
! 1 2 3                        1 2 3 1 0 0
! 4 5 6  augment-identity  ->  4 5 6 0 1 0
! 7 8 9                        7 8 9 0 0 1

: augment-identity ( matrix -- new-matrix )
    dup first length <identity-matrix>
    [ flip ] [email protected] append flip ;

! Note: the 'solution' word finds the reduced row echelon form
! of a matrix.

: gauss-jordan-invert ( matrix -- inverted )
    dup square-matrix? [ "Matrix must be square." throw ] unless
    augment-identity solution

    ! now remove the vestigial identity portion of the matrix
    flip halves nip flip ;

{
    { -1 -2 3 2 }
    { -4 -1 6 2 }
    {  7 -8 9 1 }
    {  1 -2 1 3 }
} gauss-jordan-invert simple-table.


!-----------------------------------------------------------------------
! gjinv - Invert a matrix, Gauss-Jordan algorithm
! A is destroyed.
!
!___Name_______Type_______________In/Out____Description_________________
!   A(LDA,N)   Real               In        An N by N matrix
!   LDA        Integer            In        Row bound of A
!   N          Integer            In        Order of matrix
!   B(LDB,N)   Real               Out       Inverse of A
!   LDB        Integer            In        Row bound of B
!   IERR       Integer            Out       0 = no errors
!                                           1 = singular matrix
!-----------------------------------------------------------------------
      SUBROUTINE GJINV (A, LDA, N, B, LDB, IERR)
       IMPLICIT NONE
       INTEGER LDA, N, LDB, IERR
       REAL A(LDA,N), B(LDB,N)

       REAL EPS                                  ! machine constant
       PARAMETER (EPS = 1.1920929E-07)
       INTEGER I, J, K, P                        ! local variables
       REAL F, TOL

!-----------------------------------------------------------------------
!             Begin.
!-----------------------------------------------------------------------
       IF (N < 1) THEN            ! Validate.
         IERR = -1
         RETURN
       ELSE IF (N > LDA .OR. N > LDB) THEN
         IERR = -2
         RETURN
       END IF
       IERR = 0

       F = 0.                     ! Frobenius norm of A
       DO J = 1, N
         DO I = 1, N
           F = F + A(I,J)**2
         END DO
       END DO
       F = SQRT(F)
       TOL = F * EPS

       DO J = 1, N                ! Set B to identity matrix.
         DO I = 1, N
           IF (I .EQ. J) THEN
             B(I,J) = 1.
           ELSE
             B(I,J) = 0.
           END IF
         END DO
       END DO

!             Main loop
       DO K = 1, N
         F = ABS(A(K,K))          ! Find pivot.
         P = K
         DO I = K+1, N
           IF (ABS(A(I,K)) > F) THEN
             F = ABS(A(I,K))
             P = I
           END IF
         END DO

         IF (F < TOL) THEN        ! Matrix is singular.
           IERR = 1
           RETURN
         END IF

         IF (P .NE. K) THEN       ! Swap rows.
           DO J = K, N
             F = A(K,J)
             A(K,J) = A(P,J)
             A(P,J) = F
           END DO
           DO J = 1, N
             F = B(K,J)
             B(K,J) = B(P,J)
             B(P,J) = F
           END DO
         END IF

         F = 1. / A(K,K)          ! Scale row so pivot is 1.
         DO J = K, N
           A(K,J) = A(K,J) * F
         END DO
         DO J = 1, N
           B(K,J) = B(K,J) * F
         END DO

         DO 10 I = 1, N           ! Subtract to get zeros.
           IF (I .EQ. K) GO TO 10
           F = A(I,K)
           DO J = K, N
             A(I,J) = A(I,J) - A(K,J) * F
           END DO
           DO J = 1, N
             B(I,J) = B(I,J) - B(K,J) * F
           END DO
  10     CONTINUE
       END DO

       RETURN
      END  ! of gjinv


(defun first-digit (n) (parse-integer (string (char (write-to-string n) 0))))

(defun last-digit (n) (mod n 10))

(defun bookend-number (n) (+ (* 10 (first-digit n)) (last-digit n)))

(defun gapfulp (n) (and (>= n 100) (zerop (mod n (bookend-number n)))))

(defun gapfuls-in-range (start size)
  (loop for n from start
        with include = (gapfulp n)
        counting include into found
        if include collecting n
        until (= found size)))

(defun report-range (range)
  (destructuring-bind (start size) range
    (format t "The first ~a gapful numbers >= ~a:~% ~a~%~%" size start
              (gapfuls-in-range start size))))

(mapcar #'report-range '((1 30) (1000000 15) (1000000000 10)))


struct Int
  def gapful?
    a = self.to_s.chars.map(&.to_i)
    self % (a.first*10 + a.last) == 0
  end
end

specs = {100 => 30, 1_000_000 => 15, 1_000_000_000 => 10, 7123 => 25}

specs.each do |start, count|
  puts "first #{count} gapful numbers >= #{start}:"
  puts (start..).each.select(&.gapful?).first(count).to_a, "\n"
end


#include once "matmult.bas"
#include once "rowech.bas"

function matinv( A as Matrix ) as Matrix
    dim ret as Matrix, working as Matrix
    dim as uinteger i, j
    if not ubound( A.m, 1 ) = ubound( A.m, 2 ) then return ret
    dim as integer n = ubound(A.m, 1)
    redim ret.m( n, n )
    working = Matrix( n+1, 2*(n+1) )
    for i = 0 to n
        for j = 0 to n
            working.m(i, j) = A.m(i, j)
        next j
        working.m(i, i+n+1) = 1
    next i
    working = rowech(working)
    for i = 0 to n
        for j = 0 to n
            ret.m(i, j) = working.m(i, j+n+1)
        next j
    next i
    return ret
end function

dim as integer i, j
dim as Matrix M = Matrix(3,3)
for i = 0 to 2
    for j = 0 to 2
        M.m(i, j) = 1 + i*i + 3*j + (i+j) mod 2   'just some arbitrary values
        print M.m(i, j),
    next j
    print
next i
print
M = matinv(M)
for i = 0 to 2
    for j = 0 to 2
        print M.m(i, j),
    next j
    print
next i


// The Generic Language is a database compiler. This code is compiled into database then executed out of database.

generic coordinaat
{
 ecs;
 uuii;

 coordinaat() { ecs=+a;uuii=+a;}

 coordinaat(ecs_set,uuii_set) { ecs = ecs_set; uuii=uuii_set;}

 operaator<(c)
 {
   iph ecs < c.ecs return troo;
   iph c.ecs < ecs return phals;
   iph uuii < c.uuii return troo;
   return phals;
 }

 operaator==(connpair) // eecuuols and not eecuuols deriiu phronn operaator<
 {
   iph this < connpair return phals;
   iph connpair < this return phals;
   return troo;
 }

 operaator!=(connpair)
 {
   iph this < connpair return troo;
   iph connpair < this return troo;
   return phals;
 }

 too_string()
 {
     return "(" + ecs.too_string() + "," + uuii.too_string() + ")";
 }

 print()
 {
   str = too_string();
   str.print();
 }

 println()
 {
   str = too_string();
   str.println();
 }
}

generic nnaatrics
{
  s;         // this is a set of coordinaat/ualioo pairs.
  iteraator; // this field holds an iteraator phor the nnaatrics.

  nnaatrics()   // no parameters required phor nnaatrics construction.
  {
   s = nioo set();   // create a nioo set of coordinaat/ualioo pairs.
   iteraator = nul; // the iteraator is initially set to nul.
  }

  nnaatrics(copee)   // copee the nnaatrics.
  {
   s = nioo set();   // create a nioo set of coordinaat/ualioo pairs.
   iteraator = nul; // the iteraator is initially set to nul.

   r = copee.rouus;
   c = copee.cols;
   i = 0;
   uuiil i < r
   {
     j = 0;
     uuiil j < c
     {
        this[i,j] = copee[i,j];
       j++;
     }
     i++;
   }
  }

  begin { get { return s.begin; } } // property: used to commence manual iteraashon.

  end { get { return s.end; } } // property: used to dephiin the end itenn of iteraashon

  operaator<(a) // les than operaator is corld bii the avl tree algorithnns
  {             // this operaator innpliis phor instance that you could potenshalee hav sets ou nnaatricss.
    iph cees < a.cees  // connpair the cee sets phurst.
       return troo;
    els iph a.cees < cees
       return phals;
    els                // the cee sets are eecuuol thairphor connpair nnaatrics elennents.
    {
     phurst1 = begin;
     lahst1 = end;
     phurst2 = a.begin;
     lahst2 = a.end;

     uuiil phurst1 != lahst1 && phurst2 != lahst2
     {
       iph phurst1.daata.ualioo < phurst2.daata.ualioo
        return troo;
       els
       {
         iph phurst2.daata.ualioo < phurst1.daata.ualioo
          return phals;
         els
         {
            phurst1 = phurst1.necst;
            phurst2 = phurst2.necst;
         }
       }
     }

     return phals;
    }
  }

    operaator==(connpair) // eecuuols and not eecuuols deriiu phronn operaator<
    {
     iph this < connpair return phals;
     iph connpair < this return phals;
     return troo;
    }

    operaator!=(connpair)
    {
     iph this < connpair return troo;
     iph connpair < this return troo;
     return phals;
    }

   operaator[](cee_a,cee_b) // this is the nnaatrics indexer.
   {
       set
       {
           trii { s >> nioo cee_ualioo(new coordinaat(cee_a,cee_b)); } catch {}
           s << nioo cee_ualioo(new coordinaat(nioo integer(cee_a),nioo integer(cee_b)),ualioo);
       }
       get
       {
          d = s.get(nioo cee_ualioo(new coordinaat(cee_a,cee_b)));
          return d.ualioo;
       }
   }

  operaator>>(coordinaat) // this operaator reennoous an elennent phronn the nnaatrics.
  {
   s >> nioo cee_ualioo(coordinaat);
   return this;
  }

  iteraat() // and this is how to iterate on the nnaatrics.
  {
      iph iteraator.nul()
      {
         iteraator = s.lepht_nnohst;
         iph iteraator == s.heder
             return nioo iteraator(phals,nioo nun());
         els
             return nioo iteraator(troo,iteraator.daata.ualioo);
      }
      els
      {
         iteraator = iteraator.necst;

         iph iteraator == s.heder
         {
             iteraator = nul;
             return nioo iteraator(phals,nioo nun());
         }
         els
             return nioo iteraator(troo,iteraator.daata.ualioo);
      }
   }

   couunt // this property returns a couunt ou elennents in the nnaatrics.
   {
      get
      {
         return s.couunt;
      }
   }

   ennptee // is the nnaatrics ennptee?
   {
       get
       {
           return s.ennptee;
       }
   }

   lahst // returns the ualioo of the lahst elennent in the nnaatrics.
   {
       get
       {
           iph ennptee
                 throuu "ennptee nnaatrics";
           els
               return s.lahst.ualioo;
       }
   }

    too_string() // conuerts the nnaatrics too aa string
    {
       return s.too_string();
    }

    print() // prints the nnaatrics to the consohl.
    {
        out = too_string();
        out.print();
    }

   println() // prints the nnaatrics as a liin too the consohl.
    {
        out = too_string();
        out.println();
    }

   cees // return the set ou cees ou the nnaatrics (a set of coordinaats).
   {
      get
      {
          k = nioo set();
          phor e : s k << e.cee;
          return k;
      }
   }

  operaator+(p)
  {
     ouut = nioo nnaatrics();
     phurst1 = begin;
     lahst1 = end;
     phurst2 = p.begin;
     lahst2 = p.end;
     uuiil phurst1 != lahst1 && phurst2 != lahst2
     {
        ouut[phurst1.daata.cee.ecs,phurst1.daata.cee.uuii] = phurst1.daata.ualioo + phurst2.daata.ualioo;
        phurst1 = phurst1.necst;
        phurst2 = phurst2.necst;
     }
     return ouut;
  }

  operaator-(p)
  {
     ouut = nioo nnaatrics();
     phurst1 = begin;
     lahst1 = end;
     phurst2 = p.begin;
     lahst2 = p.end;
     uuiil phurst1 != lahst1 && phurst2 != lahst2
     {
        ouut[phurst1.daata.cee.ecs,phurst1.daata.cee.uuii] = phurst1.daata.ualioo - phurst2.daata.ualioo;
        phurst1 = phurst1.necst;
        phurst2 = phurst2.necst;
     }
     return ouut;
  }

  rouus
  {
     get
     {
        r = +a;
        phurst1 = begin;
        lahst1 = end;
        uuiil phurst1 != lahst1
        {
            iph r < phurst1.daata.cee.ecs r = phurst1.daata.cee.ecs;
            phurst1 = phurst1.necst;
        }
        return r + +b;
     }
  }

  cols
  {
     get
     {
        c = +a;
        phurst1 = begin;
        lahst1 = end;
        uuiil phurst1 != lahst1
        {
            iph c < phurst1.daata.cee.uuii c = phurst1.daata.cee.uuii;
            phurst1 = phurst1.necst;
        }
        return c + +b;
     }
  }

  operaator*(o)
  {
      iph cols != o.rouus throw "rouus-cols nnisnnatch";
      reesult = nioo nnaatrics();
      rouu_couunt = rouus;
      colunn_couunt = o.cols;
      loop = cols;
      i = +a;
      uuiil i < rouu_couunt
      {
        g = +a;
        uuiil g < colunn_couunt
        {
           sunn = +a.a;
           h = +a;
           uuiil h < loop
           {
             a = this[i, h];

             b = o[h, g];
             nn = a * b;
             sunn = sunn +  nn;
             h++;
           }

            reesult[i, g] = sunn;

            g++;
         }
        i++;
     }
     return reesult;
 }

  suuop_rouus(a, b)
  {
    c = cols;
    i = 0;
    uuiil u < cols
    {
      suuop = this[a, i];
      this[a, i] = this[b, i];
      this[b, i] = suuop;
      i++;
    }
  }

  suuop_colunns(a, b)
  {
    r = rouus;
    i = 0;
    uuiil i < rouus
    {
     suuopp = this[i, a];
     this[i, a] = this[i, b];
     this[i, b] = suuop;
     i++;
    }
  }

  transpohs
  {
     get
     {
         reesult = new nnaatrics();

         r = rouus;
         c = cols;
         i=0;
         uuiil i < r
         {
              g = 0;
              uuiil g < c
              {
                 reesult[g, i] = this[i, g];
                 g++;
              }
             i++;
         }

         return reesult;
      }
   }

   deternninant
   {
        get
        {
            rouu_couunt = rouus;
            colunn_count = cols;

            if rouu_couunt != colunn_count
                throw "not a scuuair nnaatrics";

            if rouu_couunt == 0
               throw "the nnaatrics is ennptee";

            if rouu_couunt == 1
               return this[0, 0];

            if rouu_couunt == 2
                return this[0, 0] * this[1, 1] -
                       this[0, 1] * this[1, 0];

            temp = nioo nnaatrics();

            det = 0.0;
            parity = 1.0;

            j = 0;
            uuiil j < rouu_couunt
            {
                 k = 0;
                 uuiil k < rouu_couunt-1
                 {
                      skip_col = phals;

                      l = 0;
                      uuiil l < rouu_couunt-1
                      {
                           if l == j skip_col = troo;

                           if skip_col
                               n = l + 1;
                           els
                               n = l;

                            temp[k, l] = this[k + 1, n];
                            l++;
                       }
                       k++;
                  }

                  det = det + parity * this[0, j] * temp.deeternninant;

                  parity = 0.0 - parity;
                  j++;
            }

        return det;
      }
  }

   ad_rouu(a, b)
   {
       c = cols;
       i = 0;
       uuiil i < c
       {
         this[a, i] = this[a, i] + this[b, i];
         i++;
        }
   }

   ad_colunn(a, b)
   {
       c = rouus;
       i = 0;
       uuiil i < c
       {
         this[i, a] = this[i, a] + this[i, b];
         i++;
        }
   }

   subtract_rouu(a, b)
   {
       c = cols;
       i = 0;
       uuiil i < c
       {
         this[a, i] = this[a, i] - this[b, i];
         i++;
        }
   }

   subtract_colunn(a, b)
   {
       c = rouus;
       i = 0;
       uuiil i < c
       {
         this[i, a] = this[i, a] - this[i, b];
         i++;
        }
   }

   nnultiplii_rouu(rouu, scalar)
   {
       c = cols;
       i = 0;
       uuiil i < c
       {
          this[rouu, i] = this[rouu, i] * scalar;
           i++;
       }
   }

   nnultiplii_colunn(colunn, scalar)
   {
       r = rouus;
       i = 0;
       uuiil i < r
       {
          this[i, colunn] = this[i, colunn] * scalar;
           i++;
       }
   }

   diuiid_rouu(rouu, scalar)
   {
       c = cols;
       i = 0;
       uuiil i < c
       {
          this[rouu, i] = this[rouu, i] / scalar;
           i++;
       }
   }

   diuiid_colunn(colunn, scalar)
   {
       r = rouus;
       i = 0;
       uuiil i < r
       {
          this[i, colunn] = this[i, colunn] / scalar;
           i++;
       }
   }

   connbiin_rouus_ad(a,b,phactor)
   {
       c = cols;
       i = 0;
       uuiil i < c
       {
          this[a, i] = this[a, i] + phactor * this[b, i];
          i++;
       }
    }

   connbiin_rouus_subtract(a,b,phactor)
   {
       c = cols;
       i = 0;
       uuiil i < c
       {
          this[a, i] = this[a, i] - phactor * this[b, i];
          i++;
       }
    }

   connbiin_colunns_ad(a,b,phactor)
   {
       r = rouus;
       i = 0;
       uuiil i < r
       {
          this[i, a] = this[i, a] + phactor * this[i, b];
          i++;
       }
    }

   connbiin_colunns_subtract(a,b,phactor)
   {
       r = rouus;
       i = 0;
       uuiil i < r
       {
          this[i, a] = this[i, a] - phactor * this[i, b];
          i++;
       }
    }

    inuers
    {
        get
        {
            rouu_couunt = rouus;
            colunn_couunt = cols;

            iph rouu_couunt != colunn_couunt
                throw "nnatrics not scuuair";

            els iph rouu_couunt == 0
                throw "ennptee nnatrics";

            els iph rouu_couunt == 1
            {
                r = nioo nnaatrics();
                r[0, 0] = 1.0 / this[0, 0];
                return r;
            }

            gauss = nioo nnaatrics(this);

            i = 0;
            uuiil i < rouu_couunt
            {
                 j = 0;
                 uuiil j < rouu_couunt
                 {
                       iph i == j

                            gauss[i, j + rouu_couunt] = 1.0;
                        els
                            gauss[i, j + rouu_couunt] = 0.0;
                      j++;
                 }

                 i++;
             }

              j = 0;
              uuiil j < rouu_couunt
              {
                 iph gauss[j, j] == 0.0
                 {
                      k = j + 1;

                      uuiil k < rouu_couunt
                      {
                          if gauss[k, j] != 0.0 {gauss.nnaat.suuop_rouus(j, k); break; }
                           k++;
                       }

                       if k == rouu_couunt throw "nnatrics is singioolar";
                 }

                 phactor = gauss[j, j];
                 iph phactor != 1.0 gauss.diuiid_rouu(j, phactor);

                 i = j+1;
                 uuiil i < rouu_couunt
                 {
                     gauss.connbiin_rouus_subtract(i, j, gauss[i, j]);
                     i++;
                  }

                 j++;
              }

              i = rouu_couunt - 1;
              uuiil i > 0
              {
                  k = i - 1;
                  uuiil k >= 0
                  {
                      gauss.connbiin_rouus_subtract(k, i, gauss[k, i]);
                      k--;
                  }
                  i--;
              }

               reesult = nioo nnaatrics();

                i = 0;
                uuiil i < rouu_couunt
                {
                     j = 0;
                     uuiil  j < rouu_couunt
                     {
                         reesult[i, j] = gauss[i, j + rouu_couunt];
                         j++;
                     }
                    i++;
                }

              return reesult;
            }
        }

}


import std.conv;
import std.stdio;

string commatize(ulong n) {
    auto s = n.to!string;
    auto le = s.length;
    for (int i = le - 3; i >= 1; i -= 3) {
        s = s[0..i]
          ~ ","
          ~ s[i..$];
    }
    return s;
}

void main() {
    ulong[] starts = [cast(ulong)1e2, cast(ulong)1e6, cast(ulong)1e7, cast(ulong)1e9, 7123];
    int[] counts = [30, 15, 15, 10, 25];
    for (int i = 0; i < starts.length; i++) {
        int count = 0;
        auto j = starts[i];
        ulong pow = 100;
        while (true) {
            if (j < pow * 10) {
                break;
            }
            pow *= 10;
        }
        writefln("First %d gapful numbers starting at %s:", counts[i], commatize(starts[i]));
        while (count < counts[i]) {
            auto fl = (j / pow) * 10 + (j % 10);
            if (j % fl == 0) {
                write(j, ' ');
                count++;
            }
            j++;
            if (j >= 10 * pow) {
                pow *= 10;
            }
        }
        writeln("\n");
    }
}


-module(gapful).
-export([first_digit/1, last_digit/1, bookend_number/1, is_gapful/1]).

first_digit(N) ->
  list_to_integer(string:slice(integer_to_list(N),0,1)).

last_digit(N) -> N rem 10.

bookend_number(N) -> 10 * first_digit(N) + last_digit(N).

is_gapful(N) -> (N >= 100) and (0 == N rem bookend_number(N)).


package main

import "fmt"

type vector = []float64
type matrix []vector

func (m matrix) inverse() matrix {
    le := len(m)
    for _, v := range m {
        if len(v) != le {
            panic("Not a square matrix")
        }
    }
    aug := make(matrix, le)
    for i := 0; i < le; i++ {
        aug[i] = make(vector, 2*le)
        copy(aug[i], m[i])
        // augment by identity matrix to right
        aug[i][i+le] = 1
    }
    aug.toReducedRowEchelonForm()
    inv := make(matrix, le)
    // remove identity matrix to left
    for i := 0; i < le; i++ {
        inv[i] = make(vector, le)
        copy(inv[i], aug[i][le:])
    }
    return inv
}

// note: this mutates the matrix in place
func (m matrix) toReducedRowEchelonForm() {
    lead := 0
    rowCount, colCount := len(m), len(m[0])
    for r := 0; r < rowCount; r++ {
        if colCount <= lead {
            return
        }
        i := r

        for m[i][lead] == 0 {
            i++
            if rowCount == i {
                i = r
                lead++
                if colCount == lead {
                    return
                }
            }
        }

        m[i], m[r] = m[r], m[i]
        if div := m[r][lead]; div != 0 {
            for j := 0; j < colCount; j++ {
                m[r][j] /= div
            }
        }

        for k := 0; k < rowCount; k++ {
            if k != r {
                mult := m[k][lead]
                for j := 0; j < colCount; j++ {
                    m[k][j] -= m[r][j] * mult
                }
            }
        }
        lead++
    }
}

func (m matrix) print(title string) {
    fmt.Println(title)
    for _, v := range m {
        fmt.Printf("% f\n", v)
    }
    fmt.Println()
}

func main() {
    a := matrix{{1, 2, 3}, {4, 1, 6}, {7, 8, 9}}
    a.inverse().print("Inverse of A is:\n")

    b := matrix{{2, -1, 0}, {-1, 2, -1}, {0, -1, 2}}
    b.inverse().print("Inverse of B is:\n")
}


USING: formatting kernel lists lists.lazy math math.functions
math.text.utils sequences ;

: gapful? ( n -- ? )
    dup 1 digit-groups [ first ] [ last 10 * + ] bi divisor? ;

30 100 15 1,000,000 10 1,000,000,000 [
    2dup lfrom [ gapful? ] lfilter ltake list>array
    "%d gapful numbers starting at %d:\n%[%d, %]\n\n" printf
] [email protected]


variable                  cnt
: Int>Str                 s>d <# #s #>  ;
: firstDigit              [email protected]  [char] 0 -   ;
: lastDigit               + 1- [email protected] [char] 0 - ;
: cnt++                   cnt dup  @ 1+ dup rot ! ;
: GapfulNumber?           dup dup Int>Str
                          2dup drop firstDigit 10 *
                          -rot lastDigit +
                          /mod drop  0= ;
: main                    0 cnt ! 2dup
                          cr ." First " . ." gapful numbers  >= " .
                          begin  dup cnt @ -
                          while swap GapfulNumber?
                                if dup cr cnt++  . ." : " . then
                                1+ swap
                          repeat 2drop ;

100        30 main cr
1000000    15 main cr
1000000000 10 main cr


function is_gapful( n as uinteger ) as boolean
    if n<100 then return false
    dim as string ns = str(n)
    dim as uinteger gap = 10*val(mid(ns,1,1)) + val(mid(ns,len(ns),1))
    if n mod gap = 0 then return true else return false
end function

dim as ulongint i = 100
dim as ushort c
print "The first thirty gapful numbers:"
while c<30
    if is_gapful(i) then
        c += 1
        print i;" ";
    end if
    i += 1
wend
print : print
i = 1000000 : c = 0
print "The first fifteen gapful numbers above 999,999:"
while c<15
    if is_gapful(i) then
        c += 1
        print i;" ";
    end if
    i += 1
wend
print : print
i = 1000000000 : c = 0
print "The first ten gapful numbers above 999,999,999:"
while c<10
    if is_gapful(i) then
        c += 1
        print i;" ";
    end if
    i += 1
wend
print


isMatrix xs = null xs || all ((== (length.head $ xs)).length) xs

isSquareMatrix xs = null xs || all ((== (length xs)).length) xs

mult:: Num a => [[a]] -> [[a]] -> [[a]]
mult uss vss = map ((\xs -> if null xs then [] else foldl1 (zipWith (+)) xs). zipWith (\vs u -> map (u*) vs) vss) uss

matI::(Num a) => Int -> [[a]]
matI n = [ [fromIntegral.fromEnum $ i == j | j <- [1..n]] | i <- [1..n]]

inversion xs = gauss xs (matI $ length xs)

gauss::[[Double]] -> [[Double]] -> [[Double]]
gauss xs bs = map (map fromRational) $ solveGauss (toR xs) (toR bs)
    where toR = map $ map toRational

solveGauss:: (Fractional a, Ord a) => [[a]] -> [[a]] -> [[a]]
solveGauss xs bs | null xs || null bs || length xs /= length bs || (not $ isSquareMatrix xs) || (not $ isMatrix bs) = []
                 | otherwise = uncurry solveTriangle $ triangle xs bs

solveTriangle::(Fractional a,Eq a) => [[a]] -> [[a]] -> [[a]]
solveTriangle us _ | not.null.dropWhile ((/= 0).head) $ us = []
solveTriangle ([c]:as) (b:bs) = go as bs [map (/c) b]
  where
  val us vs ws = let u = head us in map (/u) $ zipWith (-) vs (head $ mult [tail us] ws)
  go [] _ zs          = zs
  go _ [] zs          = zs
  go (x:xs) (y:ys) zs = go xs ys $ (val x y zs):zs

triangle::(Num a, Ord a) => [[a]] -> [[a]] -> ([[a]],[[a]])
triangle xs bs = triang ([],[]) (xs,bs)
    where
    triang ts (_,[]) = ts
    triang ts ([],_) = ts
    triang (os,ps) zs = triang (us:os,cs:ps).unzip $ [(fun tus vs, fun cs es) | (v:vs,es) <- zip uss css,let fun = zipWith (\x y -> v*x - u*y)]
        where ((us@(u:tus)):uss,cs:css) = bubble zs

bubble::(Num a, Ord a) => ([[a]],[[a]]) -> ([[a]],[[a]])
bubble (xs,bs) = (go xs, go bs)
    where
    idmax = snd.maximum.flip zip [0..].map (abs.head) $ xs
    go ys = let (us,vs) = splitAt idmax ys in vs ++ us

main = do
  let a = [[1, 2, 3], [4, 1, 6], [7, 8, 9]]
  let b = [[2, -1, 0], [-1, 2, -1], [0, -1, 2]]
  putStrLn "inversion a ="
  mapM_ print $ inversion a
  putStrLn "\ninversion b ="
  mapM_ print $ inversion b


// Create function to calculate gapful number
gapful[num,totalCounter] :=
{
   // Display a line explaining the current calculation.
   println["First $totalCounter gapful numbers over $num:"]
   // Start a counter to compare with the total count.
   counter = 0
   while counter < totalCounter
   {
      numStr = toString[num] // Convert the integer to a string
      gapfulNumStr = left[numStr,1] + right[numStr,1] // Concatenate the first and last character of the number to form a two digit number
      gapfulNumInt = parseInt[gapfulNumStr] // Turn the concatenated string back into an integer.
      // If the concatenated two digit integer divides into the current num variable with no remainder, print it to the list and increase our counter
      if num mod gapfulNumInt == 0
      {
         print[numStr + " "]
         counter = counter + 1
      }
      // Increase the current number for the next cycle.
      num = num + 1
   }
   println[] // Linkbreak
}

// Print the first 30 gapful numbers over 100, the top 15 over 1,000,000 and the first 10 over 1,000,000,000.
gapful[100,30]
gapful[1000000,15]
gapful[1000000000,10]


package main

import "fmt"

func commatize(n uint64) string {
    s := fmt.Sprintf("%d", n)
    le := len(s)
    for i := le - 3; i >= 1; i -= 3 {
        s = s[0:i] + "," + s[i:]
    }
    return s
}

func main() {
    starts := []uint64{1e2, 1e6, 1e7, 1e9, 7123}
    counts := []int{30, 15, 15, 10, 25}
    for i := 0; i < len(starts); i++ {
        count := 0
        j := starts[i]
        pow := uint64(100)
        for {
            if j < pow*10 {
                break
            }
            pow *= 10
        }
        fmt.Printf("First %d gapful numbers starting at %s:\n", counts[i], commatize(starts[i]))
        for count < counts[i] {
            fl := (j/pow)*10 + (j % 10)
            if j%fl == 0 {
                fmt.Printf("%d ", j)
                count++
            }
            j++
            if j >= 10*pow {
                pow *= 10
            }
        }
        fmt.Println("\n")
    }
}


require 'math/misc/linear'
augmentR_I1=: ,. [email protected]@#       NB. augment matrix on the right with its Identity matrix
matrix_invGJ=: # }."1 [: [email protected]_I1


// GaussJordan.java

import java.util.Random;

public class GaussJordan {
    public static void main(String[] args) {
        int rows = 5;
        Matrix m = new Matrix(rows, rows);
        Random r = new Random();
        for (int row = 0; row < rows; ++row) {
            for (int column = 0; column < rows; ++column)
                m.set(row, column, r.nextDouble());
        }
        System.out.println("Matrix:");
        m.print();
        System.out.println("Inverse:");
        Matrix inv = m.inverse();
        inv.print();
        System.out.println("Product of matrix and inverse:");
        Matrix.product(m, inv).print();
    }
}


# Create an m x n matrix,
# it being understood that:
# matrix(0; _; _) evaluates to []
def matrix(m; n; init):
  if m == 0 then []
  elif m == 1 then [[range(0;n) | init]]
  elif m > 0 then
    [range(0;n) | init] as $row
    | [range(0;m) | $row ]
  else error("matrix\(m);_;_) invalid")
  end;

def mprint($dec):
   def max(s): reduce s as $x (null; if . == null or $x > . then $x else . end);
   def lpad($len): tostring | ($len - length) as $l | (" " * $l)[:$l] + .;

   pow(10; $dec) as $power
   | def p: (. * $power | round) / $power;
   (max(.[][] | p | tostring | length) + 1) as $w
   | . as $in
   | range(0; length) as $i
   | reduce range(0; .[$i]|length) as $j ("|"; . + ($in[$i][$j]|p|lpad($w)))
   | . + " |" ;

# Swaps two rows of the input matrix using IO==0
def swapRows(rowNum1; rowNum2):
  if (rowNum1 == rowNum2)
  then .
  else .[rowNum1] as $t
  | .[rowNum1] = .[rowNum2]
  | .[rowNum2] = $t
  end;

def toReducedRowEchelonForm:
   . as $in
   | length as $nr
   | (.[0]|length) as $nc
   | {a: $in, lead: 0 }
   | label $out
   | last(foreach range(0; $nr) as $r (.;
        if $nc <= .lead then ., break $out else . end
        | .i = $r
        | until( .a[.i][.lead] != 0;
            .i += 1
            | if $nr == .i
              then .i = $r
              | .lead += 1
              | if ($nc == .lead) then ., break $out else . end
	      else .
	      end
           )
        | swapRows(.i; $r)
        | if .a[$r][.lead] != 0
          then .a[$r][.lead] as $div
          | reduce range(0; $nc) as $j (.; .a[$r][$j] /= $div)
	  else .
	  end
        | reduce range(0; $nr) as $k (.;
            if $k != $r
            then .a[$k][.lead] as $mult
            | reduce range(0; $nc) as $j (.; .a[$k][$j] -= .a[$r][$j] * $mult)
            else .
	    end)
        | .lead += 1
	))
  | .a ;

# Assumption: the input is a square matrix with an inverse
# Uses the Gauss-Jordan method.
def inverse:
  . as $a
  | length as $nr
  | reduce range(0; $nr) as $i (
      matrix($nr; 2 * $nr; 0);
      reduce range( 0; $nr) as $j (.;
         .[$i][$j] = $a[$i][$j]
         | .[$i][$i + $nr] = 1 ))
  | last(toReducedRowEchelonForm)
  | . as $ary
  | reduce range(0; $nr) as $i ( matrix($nr; $nr; 0);
      reduce range($nr; 2 *$nr) as $j (.;
        .[$i][$j - $nr] = $ary[$i][$j] )) ;


class GapfulNumbers {
    private static String commatize(long n) {
        StringBuilder sb = new StringBuilder(Long.toString(n))
        int le = sb.length()
        for (int i = le - 3; i >= 1; i -= 3) {
            sb.insert(i, ',')
        }
        return sb.toString()
    }

    static void main(String[] args) {
        List<Long> starts = [(long) 1e2, (long) 1e6, (long) 1e7, (long) 1e9, (long) 7123]
        List<Integer> counts = [30, 15, 15, 10, 25]
        for (int i = 0; i < starts.size(); ++i) {
            println("First ${counts.get(i)} gapful numbers starting at ${commatize(starts.get(i))}")

            long j = starts.get(i)
            long pow = 100
            while (j >= pow * 10) {
                pow *= 10
            }

            int count = 0
            while (count < counts.get(i)) {
                long fl = ((long) (j / pow)) * 10 + (j % 10)
                if (j % fl == 0) {
                    print("$j ")
                    count++
                }
                if (++j >= 10 * pow) {
                    pow *= 10
                }
            }

            println()
            println()
        }
    }
}


// version 1.2.21

typealias Matrix = Array<DoubleArray>

fun Matrix.inverse(): Matrix {
    val len = this.size
    require(this.all { it.size == len }) { "Not a square matrix" }
    val aug = Array(len) { DoubleArray(2 * len) }
    for (i in 0 until len) {
        for (j in 0 until len) aug[i][j] = this[i][j]
        // augment by identity matrix to right
        aug[i][i + len] = 1.0
    }
    aug.toReducedRowEchelonForm()
    val inv = Array(len) { DoubleArray(len) }
    // remove identity matrix to left
    for (i in 0 until len) {
        for (j in len until 2 * len) inv[i][j - len] = aug[i][j]
    }
    return inv
}

fun Matrix.toReducedRowEchelonForm() {
    var lead = 0
    val rowCount = this.size
    val colCount = this[0].size
    for (r in 0 until rowCount) {
        if (colCount <= lead) return
        var i = r

        while (this[i][lead] == 0.0) {
            i++
            if (rowCount == i) {
                i = r
                lead++
                if (colCount == lead) return
            }
        }

        val temp = this[i]
        this[i] = this[r]
        this[r] = temp

        if (this[r][lead] != 0.0) {
           val div = this[r][lead]
           for (j in 0 until colCount) this[r][j] /= div
        }

        for (k in 0 until rowCount) {
            if (k != r) {
                val mult = this[k][lead]
                for (j in 0 until colCount) this[k][j] -= this[r][j] * mult
            }
        }

        lead++
    }
}

fun Matrix.printf(title: String) {
    println(title)
    val rowCount = this.size
    val colCount = this[0].size

    for (r in 0 until rowCount) {
        for (c in 0 until colCount) {
            if (this[r][c] == -0.0) this[r][c] = 0.0  // get rid of negative zeros
            print("${"% 10.6f".format(this[r][c])}  ")
        }
        println()
    }

    println()
}

fun main(args: Array<String>) {
    val a = arrayOf(
        doubleArrayOf(1.0, 2.0, 3.0),
        doubleArrayOf(4.0, 1.0, 6.0),
        doubleArrayOf(7.0, 8.0, 9.0)
    )
    a.inverse().printf("Inverse of A is :\n")

    val b = arrayOf(
        doubleArrayOf( 2.0, -1.0,  0.0),
        doubleArrayOf(-1.0,  2.0, -1.0),
        doubleArrayOf( 0.0, -1.0,  2.0)
    )
    b.inverse().printf("Inverse of B is :\n")
}


{-# LANGUAGE NumericUnderscores #-}

gapful :: Int -> Bool
gapful n = n `rem` firstLastDigit == 0
 where
  firstLastDigit = read [head asDigits, last asDigits]
  asDigits = show n

main :: IO ()
main = do
  putStrLn $ "\nFirst 30 Gapful numbers >= 100 :\n"  ++ r 30 [100,101..]
  putStrLn $ "\nFirst 15 Gapful numbers >= 1,000,000 :\n" ++ r 15 [1_000_000,1_000_001..]
  putStrLn $ "\nFirst 10 Gapful numbers >= 1,000,000,000 :\n" ++ r 10 [1_000_000_000,1_000_000_001..]
 where r n = show . take n . filter gapful


gapful =: 0 = (|~ ({.,{:)&.(10&#.inv))

task =: 100&$: :(dyad define)  NB. MINIMUM task TALLY
 gn =. y {. (#~ gapful&>) x + i. y * 25
 assert 0 ~: {: gn
 'The first ' , (": y) , ' gapful numbers exceeding ' , (":<:x) , ' are ' , (":gn)
)


import java.util.List;

public class GapfulNumbers {
    private static String commatize(long n) {
        StringBuilder sb = new StringBuilder(Long.toString(n));
        int le = sb.length();
        for (int i = le - 3; i >= 1; i -= 3) {
            sb.insert(i, ',');
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        List<Long> starts = List.of((long) 1e2, (long) 1e6, (long) 1e7, (long) 1e9, (long) 7123);
        List<Integer> counts = List.of(30, 15, 15, 10, 25);
        for (int i = 0; i < starts.size(); ++i) {
            int count = 0;
            Long j = starts.get(i);
            long pow = 100;
            while (j >= pow * 10) {
                pow *= 10;
            }
            System.out.printf("First %d gapful numbers starting at %s:\n", counts.get(i), commatize(starts.get(i)));
            while (count < counts.get(i)) {
                long fl = (j / pow) * 10 + (j % 10);
                if (j % fl == 0) {
                    System.out.printf("%d ", j);
                    count++;
                }
                j++;
                if (j >= 10 * pow) {
                    pow *= 10;
                }
            }
            System.out.println('\n');
        }
    }
}


a = [email protected]{{1, 7, 5, 0}, {5, 8, 6, 9}, {2, 1, 6, 4}, {8, 1, 2, 4}};
elimmat = RowReduce[Join[a, IdentityMatrix[Length[a]], 2]];
inv = elimmat[[All, -Length[a] ;;]]


function GaussInverse(M)
    original = M;
    [n,~] = size(M);
    I = eye(n);
    for j = 1:n
        for i = j:n
            if ~(M(i,j) == 0)
                for k = 1:n
                    q = M(j,k); M(j,k) = M(i,k); M(i,k) = q;
                    q = I(j,k); I(j,k) = I(i,k); I(i,k) = q;
                end
                p = 1/M(j,j);
                for k = 1:n
                    M(j,k) = p*M(j,k);
                    I(j,k) = p*I(j,k);
                end
                for L = 1:n
                    if ~(L == j)
                        p = -M(L,j);
                        for k = 1:n
                            M(L,k) = M(L,k) + p*M(j,k);
                            I(L,k) = I(L,k) + p*I(j,k);
                        end
                    end
                end
            end
        end
        inverted = I;
    end
    fprintf("Matrix:\n")
    disp(original)
    fprintf("Inverted matrix:\n")
    disp(inverted)
    fprintf("Inverted matrix calculated by built-in function:\n")
    disp(inv(original))
    fprintf("Product of matrix and inverse:\n")
    disp(original*inverted)
end

A = [ 2, -1,  0;
    -1,  2, -1;
    0, -1,  2 ];

GaussInverse(A)


// Function to construct a new integer from the first and last digits of another
function gapfulness_divisor (number) {
	var digit_string = number.toString(10)
	var digit_count = digit_string.length
	var first_digit = digit_string.substring(0, 1)
	var last_digit = digit_string.substring(digit_count - 1)
	return parseInt(first_digit.concat(last_digit), 10)
}

// Divisibility test to determine gapfulness
function is_gapful (number) {
	return number % gapfulness_divisor(number) == 0
}

// Function to search for the least gapful number greater than a given integer
function next_gapful (number) {
	do {
		++number
	} while (!is_gapful(number))
	return number
}

// Constructor for a list of gapful numbers starting from given lower bound
function gapful_numbers (start, amount) {
	var list = [], count = 0, number = start
	if (amount > 0 && is_gapful(start)) {
		list.push(start)
	}
	while (list.length < amount) {
		number = next_gapful(number)
		list.push(number)
	}
	return list
}

// Formatter for a comma-separated list of gapful numbers
function single_line_gapfuls (start, amount) {
	var list = gapful_numbers(start, amount)
	return list.join(", ")
}

// Windows console output wrapper
function print(message) {
	WScript.StdOut.WriteLine(message)
}

// Main algorithm

function print_gapfuls_with_header(start, amount) {
	print("First " + start + " gapful numbers starting at " + amount)
	print(single_line_gapfuls(start, amount))
}

print_gapfuls_with_header(100, 30)
print_gapfuls_with_header(1000000, 15)
print_gapfuls_with_header(1000000000, 10)


# emit a stream of gapful numbers greater than or equal to $start,
# which is assumed to be an integer
def gapful($start):
    range($start; infinite)
    | . as $i
    | tostring as $s
    | (($s[:1] + $s[-1:]) | tonumber) as $x
    | select($i % $x == 0);

"First 30 gapful numbersstarting from 100:",
([limit(30;gapful(100))] | join(" ")),
"First 15 gapful numbers starting from 1,000,000:",
([limit(15;gapful(1000000))] | join(" ")),
"First 10 gapful numbers starting from 10^9:",
([limit(10;gapful(pow(10;9)))] | join(" "))


import strformat, strutils

const Eps = 1e-10

type
  Matrix[M, N: static Positive] = array[M, array[N, float]]
  SquareMatrix[N: static Positive] = Matrix[N, N]

func toSquareMatrix[N: static Positive](a: array[N, array[N, int]]): SquareMatrix[N] =
  ## Convert a square matrix of integers to a square matrix of floats.

  for i in 0..<N:
    for j in 0..<N:
      result[i][j] = a[i][j].toFloat

func transformToRref(mat: var Matrix) =
  ## Transform a matrix to reduced row echelon form.

  var lead = 0

  for r in 0..<mat.M:

    if lead >= mat.N: return

    var i = r
    while mat[i][lead] == 0:
      inc i
      if i == mat.M:
        i = r
        inc lead
        if lead == mat.N: return
    swap mat[i], mat[r]

    let d = mat[r][lead]
    if abs(d) > Eps:    # Checking "d != 0" will give wrong results in some cases.
      for item in mat[r].mitems:
        item /= d

    for i in 0..<mat.M:
      if i != r:
        let m = mat[i][lead]
        for c in 0..<mat.N:
          mat[i][c] -= mat[r][c] * m

    inc lead

func inverse(mat: SquareMatrix): SquareMatrix[mat.N] =
  ## Return the inverse of a matrix.

  # Build augmented matrix.
  var augmat: Matrix[mat.N, 2 * mat.N]
  for i in 0..<mat.N:
    augmat[i][0..<mat.N] = mat[i]
    augmat[i][mat.N + i] = 1

  # Transform it to reduced row echelon form.
  augmat.transformToRref()

  # Check if the first half is the identity matrix and extract second half.
  for i in 0..<mat.N:
    for j in 0..<mat.N:
      if augmat[i][j] != float(i == j):
        raise newException(ValueError, "matrix is singular")
      result[i][j] = augmat[i][mat.N + j]

proc `$`(mat: Matrix): string =
  ## Display a matrix (which may be a square matrix).

  for row in mat:
    var line = ""
    for val in row:
      line.addSep(" ", 0)
      line.add &"{val:9.5f}"
    echo line

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

template runTest(mat: SquareMatrix) =
  ## Run a test using square matrix "mat".

  echo "Matrix:"
  echo $mat
  echo "Inverse:"
  echo mat.inverse
  echo ""

let m1 = [[1, 2, 3],
          [4, 1, 6],
          [7, 8, 9]].toSquareMatrix()

let m2 = [[ 2, -1,  0],
          [-1,  2, -1],
          [ 0, -1,  2]].toSquareMatrix()

let m3 = [[ -1, -2,  3,  2],
          [ -4, -1,  6,  2],
          [  7, -8,  9,  1],
          [  1, -2,  1,  3]].toSquareMatrix()

runTest(m1)
runTest(m2)
runTest(m3)