--#SET TERMINATOR @

SET SERVEROUTPUT ON @

CREATE OR REPLACE FUNCTION LUHN_TEST (
  IN NUMBER VARCHAR(24)
 ) RETURNS SMALLINT
 --) RETURNS BOOLEAN
 BEGIN
  DECLARE TYPE CARD_NUMBER AS VARCHAR(1) ARRAY [24];
  DECLARE LENGTH SMALLINT;
  DECLARE REVERSE CARD_NUMBER;
  DECLARE I SMALLINT;
  DECLARE POS SMALLINT;
  DECLARE S1 SMALLINT;
  DECLARE S2 SMALLINT;
  DECLARE TEMP SMALLINT;
  DECLARE RET SMALLINT;
  --DECLARE RET BOOLEAN;
  DECLARE INVALID_CHAR CONDITION FOR SQLSTATE 'LUHN1';

  -- Reverse the order of the digits in the number.
  SET LENGTH = LENGTH(NUMBER);
  SET I = 1;
  WHILE (I <= LENGTH) DO
   SET POS = LENGTH - I + 1;
   SET REVERSE[POS] = SUBSTR(NUMBER, I, 1);
   IF (ASCII(REVERSE[POS]) < 48 OR 57 < ASCII(REVERSE[POS])) THEN
    SIGNAL INVALID_CHAR SET MESSAGE_TEXT = 'Invalid character, not a digit';
   END IF;
   SET I = I + 1;
  END WHILE;

  -- Take the first, third, ... and every other odd digit in the reversed digits and sum them to form the partial sum s1
  SET S1 = 0;
  SET I = 1;
  WHILE (I <= LENGTH) DO
   IF (MOD(I, 2) = 1) THEN
    SET S1 = S1 + REVERSE[I];
   END IF;
   -- CALL DBMS_OUTPUT.PUT_LINE('I ' || I || ', S1 ' || S1 || ', val ' || REVERSE[I]);
   SET I = I + 1;
  END WHILE;

  -- Taking the second, fourth ... and every other even digit in the reversed digits:
  SET S2 = 0;
  SET TEMP = 0;
  SET I = 1;
  WHILE (I <= LENGTH) DO
   IF (MOD(I, 2) = 0) THEN
    -- Multiply each digit by two and sum the digits if the answer is greater than nine to form partial sums for the even digits
    SET TEMP = REVERSE[I] * 2;
    IF (TEMP > 9) THEN
     SET TEMP = (TEMP / 10) + (MOD(TEMP, 10));
    END IF;
    -- Sum the partial sums of the even digits to form s2
    SET S2 = S2 + TEMP;
   END IF;
   -- CALL DBMS_OUTPUT.PUT_LINE('I ' || I || ', S2 ' || S2 || ', TEMP ' || TEMP || ' val ' || REVERSE[I]);
   SET I = I + 1;
  END WHILE;

  -- If s1 + s2 ends in zero then the original number is in the form of a valid credit card number as verified by the Luhn test.
  SET RET = 1;
  --SET RET = FALSE;
  SET TEMP = S1 + S2;
  IF (MOD(TEMP, 10) = 0) THEN
   SET RET = 0;
   --SET RET = TRUE;
   CALL DBMS_OUTPUT.PUT_LINE('It is a valid number ' || S1 || '+' || S2 || '=' || TEMP);
  ELSE
   CALL DBMS_OUTPUT.PUT_LINE('It is NOT a valid number ' || S1 || '+' || S2 || '=' || TEMP);
  END IF;
  RETURN RET;
 END
@


local
  fun revDigits 0 = []
    | revDigits n = (n mod 10) :: revDigits (n div 10)

  fun digitSum n = if n > 9 then digitSum (n div 10 + n mod 10)
                            else n

  fun luhn_sum []  = 0
    | luhn_sum [d] = d
    | luhn_sum (d::d'::ds) = d + digitSum (2*d') + luhn_sum ds
in
  fun luhn_test n = luhn_sum (revDigits n) mod 10 = 0

  val res = map luhn_test [49927398716, 49927398717, 1234567812345678, 1234567812345670];
end;

(*
[opening file "luhn.sml"]
> val luhn_test = fn : int -> bool
  val res = [true, false, false, true] : bool list
[closing file "luhn.sml"]
*)


func luhn(_ number: String) -> Bool {
    return number.reversed().enumerated().map({
        let digit = Int(String($0.element))!
        let even = $0.offset % 2 == 0
        return even ? digit : digit == 9 ? 9 : digit * 2 % 9
    }).reduce(0, +) % 10 == 0
}

luhn("49927398716") // true
luhn("49927398717") // false


package require Tcl 8.5
proc luhn digitString {
    if {[regexp {[^0-9]} $digitString]} {error "not a number"}
    set sum 0
    set flip 1
    foreach ch [lreverse [split $digitString {}]] {
	incr sum [lindex {
	    {0 1 2 3 4 5 6 7 8 9}
	    {0 2 4 6 8 1 3 5 7 9}
	} [expr {[incr flip] & 1}] $ch]
    }
    return [expr {($sum % 10) == 0}]
}


variable number {
  type = "string"
}

locals {
  digits = reverse(split("", var.number))
  count = length(local.digits)
  odds = [for i in range(local.count): local.digits[i] if i%2==0]
  evens = [for i in range(local.count): local.digits[i] if i%2==1]
  s1 = length(flatten([for d in local.odds: range(d)]))
  doubles = [for d in local.evens: d * 2]
  partials = [for d in local.doubles: d < 10 ? d : floor(d/10)+d%10]
  s2 = length(flatten([for p in local.partials: range(p)]))
  check = (local.s1 + local.s2) % 10
}

output "valid" {
  value = local.check == 0
}


PROGRAM:LUHN
:Disp "ENTER NUMBER"
:Input Str1
:0→S
:0→E
:For(I,length(Str1),1,-1)
  :inString("0123456789",sub(Str1,I,1))–1→X
  :If X<0
    :Goto BA
  :If E≠0
  :Then
    :2X→X
    :If X>9
      :X–9→X
  :End
  :X+S→S
  :not(E)→E
:End
:If fPart(S/10)=0
:Then
  :Disp "GOOD CARD"
:Else
  :Lbl BA
  :Disp "BAD CARD"
:End


CREATE FUNCTION dbo._CreditCardNumCheck( @strCCNum VarChar(40) )
RETURNS VarChar(7)
AS
BEGIN
	DECLARE @string			VarChar(40) = REVERSE(@strCCNum); -- usage: set once, never changed
	DECLARE @strS2Values		VarChar(10) = '0246813579';  -- constant: maps digits to their S2 summed values
	DECLARE @table			TABLE (ID INT, Value INT, S_Value INT); -- ID=digit position. S_Value is used for SUM().
	DECLARE @p			INT = 0; -- loop counter: position in string
	-- Convert the reversed string's digits into rows in a table variable, S_Values to be updated afterwards
	WHILE @p < LEN(@string)
		BEGIN
			SET @p = @p+1;
			INSERT INTO @table (ID,Value,S_Value) VALUES (@p, CONVERT(INT,SUBSTRING(@string,@p,1)), 0);
		END
	-- Update S_Value column : the digit's value to be summed (for even-positioned digits this is mapped via @strS2Values)
	UPDATE @table SET S_Value = CASE WHEN ID % 2 = 1 THEN Value ELSE CONVERT(INT,SUBSTRING(@strS2Values,Value+1,1)) END
	-- If the SUM of S_Values ends in 0 (modulo 10 = 0) then the CC Number is valid
	RETURN CASE WHEN (SELECT SUM(S_Value) FROM @table) % 10 = 0 THEN 'Valid' ELSE 'Invalid' END
END


$$ MODE TUSCRIPT
MODE DATA
$$ SET cardnumbers=*
49927398716
49927398717
1234567812345678
1234567812345670
$$ MODE TUSCRIPT
-> collecting information for output-format
SET length=MAX_LENGTH(cardnumbers)
SET adjust=length+2

LOOP c=cardnumbers
-> ">/" = any digit
SET cstring=STRINGS (c,":>/:")
SET creverse=REVERSE (cstring)
SET s1=evenx2=esum=s2=""
 LOOP n,oe=creverse
  SET modrest=MOD(n,2)
  IF (modrest==0) THEN
   SET even=oe*2
    IF (even>9) THEN
     SET estring=STRINGS (even,":>/:")
     SET esum=SUM (estring)
     SET s2=APPEND (s2,esum)
    ELSE
     SET s2=APPEND (s2,even)
    ENDIF
  ELSE
   SET s1=APPEND(s1,oe)
  ENDIF
 ENDLOOP
SET s1=SUM(s1),s2=SUM(s2)
SET checksum=s1+s2
SET c=CENTER(c,-adjust)
IF (checksum.ew."0") THEN
 PRINT c,"true"
ELSE
 PRINT c,"false"
ENDIF
ENDLOOP


@(do (defun luhn (num)
       (for ((i 1) (sum 0))
            ((not (zerop num)) (zerop (mod sum 10)))
            ((inc i) (set num (trunc num 10)))
          (let ((dig (mod num 10)))
            (if (oddp i)
              (inc sum dig)
              (let ((dig2 (* 2 dig)))
                (inc sum (+ (trunc dig2 10) (mod dig2 10)))))))))
@(collect :vars nil)
@{ccnumber /[0-9]+/}
@(output)
@ccnumber -> @(if (luhn (int-str ccnumber 10)) "good" "bad")
@(end)
@(end)


#import std
#import nat

luhn = %nP; %np*hxiNCNCS; not remainder\10+ //sum:[email protected] ~&iK27K28TK25 iota10


Option Explicit

Sub Main()
  Debug.Print "Number 49927398716 is "; Luhn("49927398716")
  Debug.Print "Number 49927398717 is "; Luhn("49927398717")
  Debug.Print "Number 1234567812345678 is "; Luhn("1234567812345678")
  Debug.Print "Number 1234567812345670 is "; Luhn("1234567812345670")
End Sub
Private Function Luhn(Nb As String) As String
Dim t$, i&, Summ&, s&
    t = StrReverse(Nb)
    For i = 1 To Len(t) Step 2
        Summ = Summ + CInt(Mid(t, i, 1))
    Next i
    For i = 2 To Len(t) Step 2
        s = 2 * (CInt(Mid(t, i, 1)))
        If s >= 10 Then
            Summ = Summ - 9
        End If
        Summ = Summ + s
    Next i
    If Summ Mod 10 = 0 Then
        Luhn = "valid"
    Else
        Luhn = "invalid"
    End If
End Function


Function Luhn_Test(cc)
	cc = RevString(cc)
	s1 = 0
	s2 = 0
	For i = 1 To Len(cc)
		If i Mod 2 > 0 Then
			s1 = s1 + CInt(Mid(cc,i,1))
		Else
			tmp = CInt(Mid(cc,i,1))*2
			If  tmp < 10 Then
				s2 = s2 + tmp
			Else
				s2 = s2 + CInt(Right(CStr(tmp),1)) + 1
			End If
		End If
	Next
	If Right(CStr(s1 + s2),1) = "0" Then
		Luhn_Test = "Valid"
	Else
		Luhn_Test = "Invalid"
	End If
End Function

Function RevString(s)
	For i = Len(s) To 1 Step -1
		RevString = RevString & Mid(s,i,1)
	Next
End Function

WScript.Echo "49927398716 is " & Luhn_Test("49927398716")
WScript.Echo "49927398717 is " & Luhn_Test("49927398717")
WScript.Echo "1234567812345678 is " & Luhn_Test("1234567812345678")
WScript.Echo "1234567812345670 is " & Luhn_Test("1234567812345670")


Public Function LuhnCheckPassed(ByVal dgts As String) As Boolean
Dim i As Long, s As Long, s1 As Long
  dgts = VBA.StrReverse(dgts)
    For i = 1 To Len(dgts) Step 2
        s = s + CInt(Mid$(dgts, i, 1))
    Next i
    For i = 2 To Len(dgts) Step 2
        s1 = 2 * (CInt(Mid$(dgts, i, 1)))
        If s1 >= 10 Then
            s = s - 9
        End If
        s = s + s1
    Next i
  LuhnCheckPassed = Not CBool(s Mod 10)
End Function


    Imports System.Linq
    Function ValidLuhn(value As String)
        Return value.Select(Function(c, i) (AscW(c) - 48) << ((value.Length - i - 1) And 1)).Sum(Function(n) If(n > 9, n - 9, n)) Mod 10 = 0
    End Function
    Sub Main()
        Console.WriteLine(ValidLuhn("49927398716"))
        Console.WriteLine(ValidLuhn("49927398717"))
        Console.WriteLine(ValidLuhn("1234567812345678"))
        Console.WriteLine(ValidLuhn("1234567812345670"))
    End Sub


import "/fmt" for Fmt
import "/trait" for Stepped

var luhn = Fn.new { |s|
    // reverse digits
    s = s[-1..0]
    // sum the odd digits
    var s1 = Stepped.new(s, 2).reduce(0) { |sum, d| sum + d.bytes[0] - 48 }
    // sum two times the even digits
    var s2 = Stepped.new(s[1..-1], 2).reduce(0) { |sum, d|
        var d2 = (d.bytes[0] - 48) * 2
        return sum  + ((d2 > 9) ?  d2%10 + 1 : d2)
    }
    // check if s1 + s2 ends in zero
    return (s1 + s2)%10 == 0
}

var tests = [ "49927398716", "49927398717", "1234567812345678", "1234567812345670"]
for (test in tests) {
    var ans = (luhn.call(test)) ? "pass" : "fail"
    System.print("%(Fmt.s(-16, test)) -> %(ans)")
}


Public Function Modulus10(digits As String) as String
  //
  // Confirm the digits are really, well, digits
  //

  dim validator as new RegEx
  validator.SearchPattern = "\A\d+\z"
  if validator.Search( digits ) is nil then
    //
    // Raise an exception or something
    //
  end if

  static doublingTable() as string = array( "0", "2", "4", "6", "8", "1", "3", "5", "7", "9" )

  dim digitArr() as string = digits.Split( "" )
  for i as integer = digitArr.Ubound downto 0 step 2
    digitArr( i ) = doublingTable( digitArr( i ).Val )
  next

  dim sum as integer
  for each digit as string in digitArr
    sum = sum + digit.Val
  next

  dim check as integer = ( sum * 9 ) mod 10
  return str( check )
End Function

Public Function ValidateMod10(digits As String) as Boolean
  dim checkDigit as string = digits.Right( 1 )
  digits = digits.Left( digits.Len - 1 )

  return Modulus10( digits ) = checkDigit
End Function


string 0;               \use zero-terminated strings

func    Valid(Str);     \Return 'true' if digits in Str pass Luhn test
char    Str;
int     Len, Sum, I, Dig;
[Len:= 0;               \find length of Str
while Str(Len) do Len:= Len+1;
Sum:= 0;                \sum even and odd digits
for I:= 0 to Len-1 do   \(no need to reverse)
        [if (I xor Len) and 1 then
                Sum:= Sum + Str(I) - ^0
        else    [Dig:= Str(I) - ^0;
                Dig:= Dig*2;
                Sum:= Sum + Dig/10 + rem(0);
                ];
        ];
return rem(Sum/10) = 0;
];

int     Luhn, N;
[Luhn:= ["49927398716",
         "49927398717",
         "1234567812345678",
         "1234567812345670"];
for N:= 0 to 4-1 do
        [Text(0, Luhn(N));
         Text(0, if Valid(Luhn(N))
                then " is valid"
                else " is not valid");
        CrLf(0);
        ];
]


fcn luhnTest(n){
   0 == (n.split().reverse().reduce(fcn(s,n,clk){
      s + if(clk.next()) n else 2*n%10 + n/5 },0,Walker.cycle(1,0)) %10)
}


V n = 1024
L n > 0
   print(n)
   n I/= 2


*        While                     27/06/2016
WHILELOO CSECT                     program's control section
         USING WHILELOO,12         set base register
         LR    12,15               load base register
         LA    6,1024              v=1024
LOOP     LTR   6,6                 while v>0
         BNP   ENDLOOP             .
         CVD   6,PACKED              convert v to packed decimal
         OI    PACKED+7,X'0F'        prepare unpack
         UNPK  WTOTXT,PACKED         packed decimal to zoned printable
         WTO   MF=(E,WTOMSG)         display v
         SRA   6,1                   v=v/2   by right shift
         B     LOOP                end while
ENDLOOP  BR    14                  return to caller
PACKED   DS    PL8                 packed decimal
WTOMSG   DS    0F                  full word alignment for wto
WTOLEN   DC    AL2(8),H'0'         length of wto buffer (4+1)
WTOTXT   DC    CL4' '              wto text
         END   WHILELOO


LoopsWhile:	PHA			;push accumulator onto stack

		LDA #$00		;the 6502 is an 8-bit processor
		STA Ilow		;and so 1024 ($0400) must be stored in two memory locations
		LDA #$04
		STA Ihigh
WhileLoop:	LDA Ilow
		BNE NotZero
		LDA Ihigh
		BEQ EndLoop
NotZero:	JSR PrintI		;routine not implemented
		LSR Ihigh		;shift right
		ROR Ilow		;rotate right
		JMP WhileLoop

EndLoop:	PLA			;restore accumulator from stack
		RTS			;return from subroutine


main:
MOVE.W #1024,D0

WhileLoop:
jsr PrintHexWord
LSR.W #1,D0
BNE WhileLoop


/* ARM assembly AARCH64 Raspberry PI 3B */
/*  program loopwhile64.s   */

/*******************************************/
/* Constantes file                         */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
/*********************************/
/* Initialized data              */
/*********************************/
.data
szMessResult:      .asciz "@"            // message result
szCarriageReturn:  .asciz "\n"
/*********************************/
/* UnInitialized data            */
/*********************************/
.bss
sZoneConv:           .skip 24
/*********************************/
/*  code section                 */
/*********************************/
.text
.global main
main:                                    // entry of program
    mov x20,#1024                        // loop counter
1:                                       // begin loop
    mov x0,x20
    ldr x1,qAdrsZoneConv                 // display value
    bl conversion10                      // decimal conversion
    ldr x0,qAdrszMessResult
    ldr x1,qAdrsZoneConv
    bl strInsertAtCharInc                // insert result at @ character
    bl affichageMess                     // display message
    ldr x0,qAdrszCarriageReturn
    bl affichageMess                     // display return line
    lsr x20,x20,1                        // division by 2
    cmp x20,0                            // end ?
    bgt 1b                               // no ->begin loop one

100:                                     // standard end of the program
    mov x0,0                             // return code
    mov x8,EXIT                          // request to exit program
    svc 0                                // perform the system call

qAdrsZoneConv:            .quad sZoneConv
qAdrszMessResult:         .quad szMessResult
qAdrszCarriageReturn:     .quad szCarriageReturn

/********************************************************/
/*        File Include fonctions                        */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"


PROC Main()
  CARD i=[1024]

  WHILE i>0
  DO
    PrintCE(i)
    i=i/2
  OD
RETURN


var i:int = 1024;
while (i > 0) {
    trace(i);
    i /= 2;
}


declare
   I : Integer := 1024;
begin
   while I > 0 loop
      Put_Line(Integer'Image(I));
      I := I / 2;
   end loop;
end;


scope
    local i := 1024;
    while i > 0 do
        print( i );
        i := i \ 2
    od
epocs


integer i;

i = 1024;
while (i) {
    o_plan(i, "\n");
    i /= 2;
}


begin
	comment Loops/While - algol60 - 21/10/2014;
	integer i;
	for i:=1024,i div 2 while i>0 do outinteger(1,i)
end


INT i := 1024;
WHILE i > 0 DO
   print(i);
   i := i OVER 2
OD


begin
    integer i;
    i := 1024;
    while i > 0 do
    begin
        write( i );
        i := i div 2
    end
end.


begin
    integer i;
    i := 1024;
    while i > 0 do begin
        write( i );
        i := i / 2;
    end;
end


// print 1024 512 etc
def i := 1024;
while: { i > 0 } do: {
  system.print(" "+i);
  i := i/2;
}


PROC main()
  DEF i = 1024
  WHILE i > 0
    WriteF('\d\n', i)
    i := i / 2
  ENDWHILE
ENDPROC


set i to 1024
repeat while i > 0
	log i
	set i to i / 2
end repeat


/* ARM assembly Raspberry PI  */
/*  program loopwhile.s   */

/* Constantes    */
.equ STDOUT, 1     @ Linux output console
.equ EXIT,   1     @ Linux syscall
.equ WRITE,  4     @ Linux syscall

/*********************************/
/* Initialized data              */
/*********************************/
.data
szMessResult:      .ascii ""                    @ message result
sMessValeur:       .fill 11, 1, ' '
szCarriageReturn:  .asciz "\n"
/*********************************/
/* UnInitialized data            */
/*********************************/
.bss
/*********************************/
/*  code section                 */
/*********************************/
.text
.global main
main:                                       @ entry of program
    mov r4,#1024                            @ loop counter
1:                                          @ begin loop
    mov r0,r4
    ldr r1,iAdrsMessValeur                  @ display value
    bl conversion10                         @ decimal conversion
    ldr r0,iAdrszMessResult
    bl affichageMess                        @ display message
    ldr r0,iAdrszCarriageReturn
    bl affichageMess                        @ display return line
    lsr r4,#1                               @ division by 2
    cmp r4,#0                               @ end ?
    bgt 1b                                  @ no ->begin loop one

100:                                        @ standard end of the program
    mov r0, #0                              @ return code
    mov r7, #EXIT                           @ request to exit program
    svc #0                                  @ perform the system call

iAdrsMessValeur:          .int sMessValeur
iAdrszMessResult:         .int szMessResult
iAdrszCarriageReturn:     .int szCarriageReturn
/******************************************************************/
/*     display text with size calculation                         */
/******************************************************************/
/* r0 contains the address of the message */
affichageMess:
    push {r0,r1,r2,r7,lr}                   @ save  registres
    mov r2,#0                               @ counter length
1:                                          @ loop length calculation
    ldrb r1,[r0,r2]                         @ read octet start position + index
    cmp r1,#0                               @ if 0 its over
    addne r2,r2,#1                          @ else add 1 in the length
    bne 1b                                  @ and loop
                                            @ so here r2 contains the length of the message
    mov r1,r0                               @ address message in r1
    mov r0,#STDOUT                          @ code to write to the standard output Linux
    mov r7, #WRITE                          @ code call system "write"
    svc #0                                  @ call systeme
    pop {r0,r1,r2,r7,lr}                    @ restaur registers */
    bx lr                                   @ return
/******************************************************************/
/*     Converting a register to a decimal                                 */
/******************************************************************/
/* r0 contains value and r1 address area   */
.equ LGZONECAL,   10
conversion10:
    push {r1-r4,lr}                         @ save registers
    mov r3,r1
    mov r2,#LGZONECAL
1:                                          @ start loop
    bl divisionpar10                        @ r0 <- dividende. quotient ->r0 reste -> r1
    add r1,#48                              @ digit
    strb r1,[r3,r2]                         @ store digit on area
    cmp r0,#0                               @ stop if quotient = 0
    subne r2,#1                               @ previous position
    bne 1b                                  @ else loop
                                            @ end replaces digit in front of area
    mov r4,#0
2:
    ldrb r1,[r3,r2]
    strb r1,[r3,r4]                         @ store in area begin
    add r4,#1
    add r2,#1                               @ previous position
    cmp r2,#LGZONECAL                       @ end
    ble 2b                                  @ loop
    mov r1,#0                               @ final zero
    strb r1,[r3,r4]
100:
    pop {r1-r4,lr}                          @ restaur registres
    bx lr                                   @return
/***************************************************/
/*   division par 10   signé                       */
/* Thanks to http://thinkingeek.com/arm-assembler-raspberry-pi/*
/* and   http://www.hackersdelight.org/            */
/***************************************************/
/* r0 dividende   */
/* r0 quotient */
/* r1 remainder  */
divisionpar10:
  /* r0 contains the argument to be divided by 10 */
    push {r2-r4}                           @ save registers  */
    mov r4,r0
    mov r3,#0x6667                         @ r3 <- magic_number  lower
    movt r3,#0x6666                        @ r3 <- magic_number  upper
    smull r1, r2, r3, r0                   @ r1 <- Lower32Bits(r1*r0). r2 <- Upper32Bits(r1*r0)
    mov r2, r2, ASR #2                     @ r2 <- r2 >> 2
    mov r1, r0, LSR #31                    @ r1 <- r0 >> 31
    add r0, r2, r1                         @ r0 <- r2 + r1
    add r2,r0,r0, lsl #2                   @ r2 <- r0 * 5
    sub r1,r4,r2, lsl #1                   @ r1 <- r4 - (r2 * 2)  = r4 - (r0 * 10)
    pop {r2-r4}
    bx lr                                  @ return


IT'S SHOWTIME
HEY CHRISTMAS TREE n
YOU SET US UP 1024
STICK AROUND n
TALK TO THE HAND n
GET TO THE CHOPPER n
HERE IS MY INVITATION n
HE HAD TO SPLIT 2
ENOUGH TALK
CHILL
YOU HAVE BEEN TERMINATED


i: 1024

while [i>0] [
	print i
	i: i/2
]


int i = 1024;

while(i > 0) {
  write(i);
  i = i # 2;       //or also i = quotient(i, 2);
}

//# Integer division; equivalent to quotient(x,y).
//Noting that the Python3 community adopted the comment symbol (//) for integer division, the
//Asymptote community decided to reciprocate and use their comment symbol for integer division!


#include "share/atspre_staload.hats"

fn
loop_while () : void =
  let
    fun
    loop {n : int | 0 <= n} .<n>.
         (n : uint n) : void =
      if n <> 0U then
        begin
          println! (n);
          loop (n / 2U)
        end
  in
    loop 1024U
  end

implement
main0 () =
  loop_while ()


i = 1024
While (i > 0)
{
  output = %output%`n%i%
  i := Floor(i / 2)
}
MsgBox % output


BEGIN {
  v = 1024
  while(v > 0) {
    print v
    v = int(v/2)
  }
}


1024→A
While A>0
 Disp A▶Dec,i
 A/2→A
End


i = 1024
WHILE i > 0
   PRINT i
   i = i / 2
WEND


num = 1024
while num > 1 # blz will automatically cast num to a fraction when dividing 1/2, so this is necessary to stop an infinite loop
    print(num)
    num = num / 2
end


_while_ ← {𝔽⍟𝔾∘𝔽_𝕣_𝔾∘𝔽⍟𝔾𝕩}

(⌊∘÷⟜2 •Show) _while_ (>⟜0) 1024


int i = 1024;
while(i > 0){
   System.Console.WriteLine(i);
   i /= 2;
}


int i = 1024;
while(i > 0){
  std::cout << i << std::endl;
  i /= 2;
}


WHILELOOP
    set x = 1024
    while (x > 0) {
        write x,!
        set x = (x \ 2)    ; using non-integer division will never get to 0
    }

    quit


var val = 1024;
while val > 0 {
        writeln(val);
        val /= 2;
}


1024 => int value;

while(value > 0)
{
    <<<value>>>;
    value / 2 => value;
}


(def i (ref 1024))

(while (> @i 0)
  (println @i)
  (dosync (ref-set i (quot @i 2))))


start_up = proc ()
    po: stream := stream$primary_output()
    n: int := 1024
    while n>0 do
        stream$putl(po, int$unparse(n))
        n := n/2
    end
end start_up


       IDENTIFICATION DIVISION.
       PROGRAM-ID. Loop-While.

       DATA DIVISION.
       WORKING-STORAGE SECTION.
       01  I PIC 9999 VALUE 1024.

       PROCEDURE DIVISION.
           PERFORM UNTIL NOT 0 < I
               DISPLAY I
               DIVIDE 2 INTO I
           END-PERFORM

           GOBACK
           .


<cfset i = 1024 /><cfloop condition="i GT 0">  #i#< br />
  <cfset i /= 2 />
</cfloop>


(let ((i 1024))
  (loop while (plusp i) do
        (print i)
        (setf i (floor i 2))))

(loop with i = 1024
      while (plusp i) do
      (print i)
      (setf i (floor i 2)))

(defparameter *i* 1024)
(loop while (plusp *i*) do
      (print *i*)
      (setf *i* (floor *i* 2)))


include "cowgol.coh";

var n: uint16 := 1024;
while n > 0 loop
    print_i16(n);
    print_nl();
    n := n/2;
end loop;


i = 1024
while i > 0
    puts i
    i //= 2
end


import std.stdio;

void main() {
    int i = 1024;

    while (i > 0) {
        writeln(i);
        i >>= 1;
    }
}


[ q ] sQ [ d 0!<Q p 2 / lW x ] sW 1024 lW x


$ i = 1024
$Loop:
$ IF ( i .LE. 0 ) THEN GOTO LoopEnd
$ WRITE sys$output F$FAO( "  i = !4UL", i )  ! formatted ASCII output, fixed-width field
$ ! Output alternatives:
$ !   WRITE sys$output F$STRING( i )         ! explicit integer-to-string conversion
$ !   WRITE sys$output i                     ! implicit conversion to string/output
$ i = i / 2
$ GOTO Loop
$LoopEnd:


var
  i : Integer;
begin
  i := 1024;

  while i > 0 do
  begin
    Writeln(i);
    i := i div 2;
  end;
end;


proc nonrec main() void:
    word i;
    i := 1024;
    while i > 0 do
        writeln(i);
        i := i >> 1
    od
corp


i = 1024
while(i > 0){
   showln i
   i >>= 1 //also acceptable: i /= 2
}


var i := 1024;

while i > 0 do begin
   PrintLn(i);
   i := i div 2;
end;


var i = 1024
while i > 0 {
  print(i)
  i /= 2
}


var i := 1024
while (i > 0) {
    println(i)
    i //= 2
}


i = 1024
while i > 0
  print i
  i = i div 2
.


x int = 1024;
while ( x > 0 )
   SysLib.writeStdout( x );
   x = MathLib.floor( x / 2 );
end


public program()
{
    int i := 1024;
    while (i > 0)
    {
        console.writeLine:i;

        i /= 2
    }
}


defmodule Loops do
  def while(0), do: :ok
  def while(n) do
    IO.puts n
    while( div(n,2) )
  end
end

Loops.while(1024)


-module(while).
-export([loop/0]).

loop() ->
	loop(1024).

loop(N) when N div 2 =:= 0 ->
	io:format("~w~n", [N]);

loop(N) when N >0 ->
	io:format("~w~n", [N]),
	loop(N div 2).


   I%=1024
   WHILE I%>0 DO  ! you can leave out >0
     PRINT(I%)
     I%=I% DIV 2  ! I%=INT(I%/2) for C-64 version
   END WHILE


integer i
i = 1024

while i > 0 do
    printf(1, "%g\n", {i})
    i = floor(i/2) --Euphoria does NOT use integer division.  1/2 = 0.5
end while


let rec loop n = if n > 0 then printf "%d " n; loop (n / 2)
loop 1024


1024 [ dup 0 > ] [ dup . 2 /i ] while drop


F pprint(m)
   L(row) m
      print(row)

F matrix_mul(a, b)
   V result = [[0.0] * a.len] * a.len
   L(j) 0 .< a.len
      L(i) 0 .< a.len
         V r = 0.0
         L(k) 0 .< a.len
            r += a[i][k] * b[k][j]
         result[i][j] = r
   R result

F pivotize(m)
   ‘Creates the pivoting matrix for m.’
   V n = m.len
   V ID = (0 .< n).map(j -> (0 .< @n).map(i -> Float(i == @j)))
   L(j) 0 .< n
      V row = max(j .< n, key' i -> abs(@m[i][@j]))
      I j != row
         swap(&ID[j], &ID[row])
   R ID

F lu(A)
   ‘Decomposes a nxn matrix A by PA=lU and returns l, U and P.’
   V n = A.len
   V l = [[0.0] * n] * n
   V U = [[0.0] * n] * n
   V P = pivotize(A)
   V A2 = matrix_mul(P, A)
   L(j) 0 .< n
      l[j][j] = 1.0
      L(i) 0 .. j
         V s1 = sum((0 .< i).map(k -> @U[k][@j] * @l[@i][k]))
         U[i][j] = A2[i][j] - s1
      L(i) j .< n
         V s2 = sum((0 .< j).map(k -> @U[k][@j] * @l[@i][k]))
         l[i][j] = (A2[i][j] - s2) / U[j][j]
   R (l, U, P)

V a = [[1, 3, 5], [2, 4, 7], [1, 1, 0]]
L(part) lu(a)
   pprint(part)
   print()
print()
V b = [[11, 9, 24, 2], [1, 5, 2, 6], [3, 17, 18, 1], [2, 5, 7, 1]]
L(part) lu(b)
   pprint(part)
   print()


class Main
{
  public static Void main ()
  {
    Int i := 1024
    while (i > 0)
    {
      echo (i)
      i /= 2
    }
  }
}


(var n 1024)
(while (> i 0)
  (print i)
  (set i (// n 2)))


with Ada.Numerics.Generic_Real_Arrays;
generic
   with package Matrix is new Ada.Numerics.Generic_Real_Arrays (<>);
package Decomposition is

   -- decompose a square matrix A by PA = LU
   procedure Decompose (A : Matrix.Real_Matrix; P, L, U : out Matrix.Real_Matrix);

end Decomposition;


;--------------------------
LU_decomposition(A){
    P := Pivot(A)
    A_ := Multiply_Matrix(P, A)

    U := [], L := [], n := A_.Count()
    loop % n {
        i := A_Index
        loop % n {
            j := A_Index

            Sigma := 0, k := 1
            while (k <= i-1)
                Sigma += (U[k, j] * L[i, k]), k++
            U[i, j] := A_[i, j] - Sigma

            Sigma := 0, k := 1
            while (k <= j-1)
                Sigma += (U[k, j] * L[i, k]), k++
            L[i, j] := (A_[i, j] - Sigma) / U[j, j]
        }
    }
    return [L, U, P]
}
;--------------------------
Pivot(M){
    n := M.Count(), P := [], i := 0
    while (i++ < n){
        P.push([])
        j := 0
        while (j++ < n)
            P[i].push(i=j ? 1 : 0)
    }
    i := 0
    while (i++ < n){
        maxm := M[i, i], row := i, j := i
        while (j++ < n)
            if (M[j, i] > maxm)
                maxm := M[j, i], row := j
        if (i != row)
            tmp := P[i], P[i] := P[row], P[row] := tmp
    }
    return P
}
;--------------------------
Multiply_Matrix(A,B){
    if (A[1].Count() <> B.Count())
        return
    RCols := A[1].Count()>B[1].Count()?A[1].Count():B[1].Count()
    RRows := A.Count()>B.Count()?A.Count():B.Count(),     R := []
    Loop, % RRows {
        RRow:=A_Index
        loop, % RCols {
            RCol:=A_Index,            v := 0
            loop % A[1].Count()
                col := A_Index,        v += A[RRow, col] * B[col,RCol]
            R[RRow,RCol] := v
        }
    }
    return R
}
;--------------------------
ShowMatrix(L, f:=3){
    for r, obj in L{
        row := ""
        for c, v in obj
            row .= Format("{:." f "f}", v) ", "
        output .= "[" trim(row, ", ") "]`n,"
    }
    return "[" Trim(output, "`n,") "]"
}
;--------------------------


: halving ( n -- )
  begin  dup 0 >
  while  cr dup .  2/
  repeat drop ;
1024 halving


INTEGER :: i = 1024
DO WHILE (i > 0)
  WRITE(*,*) i
  i = i / 2
END DO


      DIM A1(2,2)
      A1() = 1, 3, 5, 2, 4, 7, 1, 1, 0
      PROCLUdecomposition(A1(), L1(), U1(), P1())
      PRINT "L1:" ' FNshowmatrix(L1())
      PRINT "U1:" ' FNshowmatrix(U1())
      PRINT "P1:" ' FNshowmatrix(P1())

      DIM A2(3,3)
      A2() = 11, 9, 24, 2, 1, 5, 2, 6, 3, 17, 18, 1, 2, 5, 7, 1
      PROCLUdecomposition(A2(), L2(), U2(), P2())
      PRINT "L2:" ' FNshowmatrix(L2())
      PRINT "U2:" ' FNshowmatrix(U2())
      PRINT "P2:" ' FNshowmatrix(P2())
      END

      DEF PROCLUdecomposition(a(), RETURN l(), RETURN u(), RETURN p())
      LOCAL i%, j%, k%, n%, s, b() : n% = DIM(a(),2)
      DIM l(n%,n%), u(n%,n%), b(n%,n%)
      PROCpivot(a(), p())
      b() = p() . a()
      FOR j% = 0 TO n%
        l(j%,j%) = 1
        FOR i% = 0 TO j%
          s = 0
          FOR k% = 0 TO i% : s += u(k%,j%) * l(i%,k%) : NEXT
          u(i%,j%) = b(i%,j%) - s
        NEXT
        FOR i% = j% TO n%
          s = 0
          FOR k% = 0 TO j% : s += u(k%,j%) * l(i%,k%) : NEXT
          IF i%<>j% l(i%,j%) = (b(i%,j%) - s) / u(j%,j%)
        NEXT
      NEXT j%
      ENDPROC

      DEF PROCpivot(a(), RETURN p())
      LOCAL i%, j%, m%, n%, r% : n% = DIM(a(),2)
      DIM p(n%,n%) : FOR i% = 0 TO n% : p(i%,i%) = 1 : NEXT
      FOR i% = 0 TO n%
        m% = a(i%,i%)
        r% = i%
        FOR j% = i% TO n%
          IF a(j%,i%) > m% m% = a(j%,i%) : r% = j%
        NEXT
        IF i%<>r% THEN
          FOR j% = 0 TO n% : SWAP p(i%,j%),p(r%,j%) : NEXT
        ENDIF
      NEXT i%
      ENDPROC

      DEF FNshowmatrix(a())
      LOCAL @%, i%, j%, a$
      @% = &102050A
      FOR i% = 0 TO DIM(a(),1)
        FOR j% = 0 TO DIM(a(),2)
          a$ += STR$(a(i%,j%)) + ", "
        NEXT
        a$ = LEFT$(LEFT$(a$)) + CHR$(13) + CHR$(10)
      NEXT i%
      = a$


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

#define foreach(a, b, c) for (int a = b; a < c; a++)
#define for_i foreach(i, 0, n)
#define for_j foreach(j, 0, n)
#define for_k foreach(k, 0, n)
#define for_ij for_i for_j
#define for_ijk for_ij for_k
#define _dim int n
#define _swap(x, y) { typeof(x) tmp = x; x = y; y = tmp; }
#define _sum_k(a, b, c, s) { s = 0; foreach(k, a, b) s+= c; }

typedef double **mat;

#define _zero(a) mat_zero(a, n)
void mat_zero(mat x, int n) { for_ij x[i][j] = 0; }

#define _new(a) a = mat_new(n)
mat mat_new(_dim)
{
	mat x = malloc(sizeof(double*) * n);
	x[0]  = malloc(sizeof(double) * n * n);

	for_i x[i] = x[0] + n * i;
	_zero(x);

	return x;
}

#define _copy(a) mat_copy(a, n)
mat mat_copy(void *s, _dim)
{
	mat x = mat_new(n);
	for_ij x[i][j] = ((double (*)[n])s)[i][j];
	return x;
}

#define _del(x) mat_del(x)
void mat_del(mat x) { free(x[0]); free(x); }

#define _QUOT(x) #x
#define QUOTE(x) _QUOT(x)
#define _show(a) printf(QUOTE(a)" =");mat_show(a, 0, n)
void mat_show(mat x, char *fmt, _dim)
{
	if (!fmt) fmt = "%8.4g";
	for_i {
		printf(i ? "      " : " [ ");
		for_j {
			printf(fmt, x[i][j]);
			printf(j < n - 1 ? "  " : i == n - 1 ? " ]\n" : "\n");
		}
	}
}

#define _mul(a, b) mat_mul(a, b, n)
mat mat_mul(mat a, mat b, _dim)
{
	mat c = _new(c);
	for_ijk c[i][j] += a[i][k] * b[k][j];
	return c;
}

#define _pivot(a, b) mat_pivot(a, b, n)
void mat_pivot(mat a, mat p, _dim)
{
	for_ij { p[i][j] = (i == j); }
	for_i  {
		int max_j = i;
		foreach(j, i, n)
			if (fabs(a[j][i]) > fabs(a[max_j][i])) max_j = j;

		if (max_j != i)
			for_k { _swap(p[i][k], p[max_j][k]); }
	}
}

#define _LU(a, l, u, p) mat_LU(a, l, u, p, n)
void mat_LU(mat A, mat L, mat U, mat P, _dim)
{
	_zero(L); _zero(U);
	_pivot(A, P);

	mat Aprime = _mul(P, A);

	for_i  { L[i][i] = 1; }
	for_ij {
		double s;
		if (j <= i) {
			_sum_k(0, j, L[j][k] * U[k][i], s)
			U[j][i] = Aprime[j][i] - s;
		}
		if (j >= i) {
			_sum_k(0, i, L[j][k] * U[k][i], s);
			L[j][i] = (Aprime[j][i] - s) / U[i][i];
		}
	}

	_del(Aprime);
}

double A3[][3] = {{ 1, 3, 5 }, { 2, 4, 7 }, { 1, 1, 0 }};
double A4[][4] = {{11, 9, 24, 2}, {1, 5, 2, 6}, {3, 17, 18, 1}, {2, 5, 7, 1}};

int main()
{
	int n = 3;
	mat A, L, P, U;

	_new(L); _new(P); _new(U);
	A = _copy(A3);
	_LU(A, L, U, P);
	_show(A); _show(L); _show(U); _show(P);
	_del(A);  _del(L);  _del(U);  _del(P);

	printf("\n");

	n = 4;

	_new(L); _new(P); _new(U);
	A = _copy(A4);
	_LU(A, L, U, P);
	_show(A); _show(L); _show(U); _show(P);
	_del(A);  _del(L);  _del(U);  _del(P);

	return 0;
}


component loops_while
  export Executable

  var i:ZZ32 = 1024
  run() = while i > 0 do
    println(i)
    i := i DIV 2
  end
end


' FB 1.05.0 Win64

Dim i As Integer = 1024

While i > 0
  Print i
  i Shr= 1
Wend

Sleep


#include <cassert>
#include <cmath>
#include <iomanip>
#include <iostream>
#include <limits>
#include <numeric>
#include <sstream>
#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,
        const std::initializer_list<std::initializer_list<scalar_type>>& values)
        : rows_(rows), columns_(columns), elements_(rows * columns) {
        assert(values.size() <= rows_);
        size_t i = 0;
        for (const auto& row : values) {
            assert(row.size() <= columns_);
            std::copy(begin(row), end(row), &elements_[i]);
            i += columns_;
        }
    }

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

    const scalar_type& operator()(size_t row, size_t column) const {
        assert(row < rows_);
        assert(column < columns_);
        return elements_[row * columns_ + column];
    }
    scalar_type& operator()(size_t row, size_t column) {
        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>
void print(std::wostream& out, const matrix<scalar_type>& a) {
    const wchar_t* box_top_left = L"\x23a1";
    const wchar_t* box_top_right = L"\x23a4";
    const wchar_t* box_left = L"\x23a2";
    const wchar_t* box_right = L"\x23a5";
    const wchar_t* box_bottom_left = L"\x23a3";
    const wchar_t* box_bottom_right = L"\x23a6";

    const int precision = 5;
    size_t rows = a.rows(), columns = a.columns();
    std::vector<size_t> width(columns);
    for (size_t column = 0; column < columns; ++column) {
        size_t max_width = 0;
        for (size_t row = 0; row < rows; ++row) {
            std::ostringstream str;
            str << std::fixed << std::setprecision(precision) << a(row, column);
            max_width = std::max(max_width, str.str().length());
        }
        width[column] = max_width;
    }
    out << std::fixed << std::setprecision(precision);
    for (size_t row = 0; row < rows; ++row) {
        const bool top(row == 0), bottom(row + 1 == rows);
        out << (top ? box_top_left : (bottom ? box_bottom_left : box_left));
        for (size_t column = 0; column < columns; ++column) {
            if (column > 0)
                out << L' ';
            out << std::setw(width[column]) << a(row, column);
        }
        out << (top ? box_top_right : (bottom ? box_bottom_right : box_right));
        out << L'\n';
    }
}

// Return value is a tuple with elements (lower, upper, pivot)
template <typename scalar_type>
auto lu_decompose(const matrix<scalar_type>& input) {
    assert(input.rows() == input.columns());
    size_t n = input.rows();
    std::vector<size_t> perm(n);
    std::iota(perm.begin(), perm.end(), 0);
    matrix<scalar_type> lower(n, n);
    matrix<scalar_type> upper(n, n);
    matrix<scalar_type> input1(input);
    for (size_t j = 0; j < n; ++j) {
        size_t max_index = j;
        scalar_type max_value = 0;
        for (size_t i = j; i < n; ++i) {
            scalar_type value = std::abs(input1(perm[i], j));
            if (value > max_value) {
                max_index = i;
                max_value = value;
            }
        }
        if (max_value <= std::numeric_limits<scalar_type>::epsilon())
            throw std::runtime_error("matrix is singular");
        if (j != max_index)
            std::swap(perm[j], perm[max_index]);
        size_t jj = perm[j];
        for (size_t i = j + 1; i < n; ++i) {
            size_t ii = perm[i];
            input1(ii, j) /= input1(jj, j);
            for (size_t k = j + 1; k < n; ++k)
                input1(ii, k) -= input1(ii, j) * input1(jj, k);
        }
    }

    for (size_t j = 0; j < n; ++j) {
        lower(j, j) = 1;
        for (size_t i = j + 1; i < n; ++i)
            lower(i, j) = input1(perm[i], j);
        for (size_t i = 0; i <= j; ++i)
            upper(i, j) = input1(perm[i], j);
    }

    matrix<scalar_type> pivot(n, n);
    for (size_t i = 0; i < n; ++i)
        pivot(i, perm[i]) = 1;

    return std::make_tuple(lower, upper, pivot);
}

template <typename scalar_type>
void show_lu_decomposition(const matrix<scalar_type>& input) {
    try {
        std::wcout << L"A\n";
        print(std::wcout, input);
        auto result(lu_decompose(input));
        std::wcout << L"\nL\n";
        print(std::wcout, std::get<0>(result));
        std::wcout << L"\nU\n";
        print(std::wcout, std::get<1>(result));
        std::wcout << L"\nP\n";
        print(std::wcout, std::get<2>(result));
    } catch (const std::exception& ex) {
        std::cerr << ex.what() << '\n';
    }
}

int main() {
    std::wcout.imbue(std::locale(""));
    std::wcout << L"Example 1:\n";
    matrix<double> matrix1(3, 3,
       {{1, 3, 5},
        {2, 4, 7},
        {1, 1, 0}});
    show_lu_decomposition(matrix1);
    std::wcout << '\n';

    std::wcout << L"Example 2:\n";
    matrix<double> matrix2(4, 4,
      {{11, 9, 24, 2},
        {1, 5, 2, 6},
        {3, 17, 18, 1},
        {2, 5, 7, 1}});
    show_lu_decomposition(matrix2);
    std::wcout << '\n';

    std::wcout << L"Example 3:\n";
    matrix<double> matrix3(3, 3,
      {{-5, -6, -3},
       {-1,  0, -2},
       {-3, -4, -7}});
    show_lu_decomposition(matrix3);
    std::wcout << '\n';

    std::wcout << L"Example 4:\n";
    matrix<double> matrix4(3, 3,
      {{1, 2, 3},
       {4, 5, 6},
       {7, 8, 9}});
    show_lu_decomposition(matrix4);

    return 0;
}


window 1

long i = 1024

while i > 0
  print i
  i = int( i / 2 )
wend

HandleEvents


Public Sub Main()
Dim siCount As Short = 1024

While siCount > 0
  Print siCount;;
  siCount /= 2
Wend

End


n := 1024;
while n > 0 do
    Print(n, "\n");
    n := QuoInt(n, 2);
od;


;; Creates a nxn identity matrix.
(defun eye (n)
  (let ((I (make-array `(,n ,n) :initial-element 0)))
    (loop for j from 0 to (- n 1) do
          (setf (aref I j j) 1))
    I))

;; Swap two rows l and k of a mxn matrix A, which is a 2D array.
(defun swap-rows (A l k)
  (let* ((n (cadr (array-dimensions A)))
         (row (make-array n :initial-element 0)))
    (loop for j from 0 to (- n 1) do
          (setf (aref row j) (aref A l j))
          (setf (aref A l j) (aref A k j))
          (setf (aref A k j) (aref row j)))))

;; Creates the pivoting matrix for A.
(defun pivotize (A)
  (let* ((n (car (array-dimensions A)))
         (P (eye n)))
    (loop for j from 0 to (- n 1) do
          (let ((max (aref A j j))
                (row j))
            (loop for i from j to (- n 1) do
                  (if (> (aref A i j) max)
                      (setq max (aref A i j)
                            row i)))
            (if (not (= j row))
                (swap-rows P j row))))

  ;; Return P.
  P))

;; Decomposes a square matrix A by PA=LU and returns L, U and P.
(defun lu (A)
  (let* ((n (car (array-dimensions A)))
         (L (make-array `(,n ,n) :initial-element 0))
         (U (make-array `(,n ,n) :initial-element 0))
         (P (pivotize A))
         (A (mmul P A)))

    (loop for j from 0 to (- n 1) do
          (setf (aref L j j) 1)
          (loop for i from 0 to j do
                (setf (aref U i j)
                      (- (aref A i j)
                         (loop for k from 0 to (- i 1)
                               sum (* (aref U k j)
                                      (aref L i k))))))
          (loop for i from j to (- n 1) do
                (setf (aref L i j)
                      (/ (- (aref A i j)
                            (loop for k from 0 to (- j 1)
                                  sum (* (aref U k j)
                                         (aref L i k))))
                         (aref U j j)))))

  ;; Return L, U and P.
  (values L U P)))


i = 1024
while(i > 0)
    {
    show_message(string(i))
    i /= 2
    }


int i = 1024
while (i > 0) {
    println i
    i /= 2
}


import std.stdio, std.algorithm, std.typecons, std.numeric,
       std.array, std.conv, std.string, std.range;

bool isRectangular(T)(in T[][] m) pure nothrow @nogc {
    return m.all!(r => r.length == m[0].length);
}

bool isSquare(T)(in T[][] m) pure nothrow @nogc {
    return m.isRectangular && m[0].length == m.length;
}

T[][] matrixMul(T)(in T[][] A, in T[][] B) pure nothrow
in {
    assert(A.isRectangular && B.isRectangular &&
           !A.empty && !B.empty && A[0].length == B.length);
} body {
    auto result = new T[][](A.length, B[0].length);
    auto aux = new T[B.length];

    foreach (immutable j; 0 .. B[0].length) {
        foreach (immutable k, const row; B)
            aux[k] = row[j];
        foreach (immutable i, const ai; A)
            result[i][j] = dotProduct(ai, aux);
    }

    return result;
}

/// Creates the pivoting matrix for m.
T[][] pivotize(T)(immutable T[][] m) pure nothrow
in {
    assert(m.isSquare);
} body {
    immutable n = m.length;
    auto id = iota(n)
              .map!((in j) => n.iota.map!(i => T(i == j)).array)
              .array;

    foreach (immutable i; 0 .. n) {
        // immutable row = iota(i, n).reduce!(max!(j => m[j][i]));
        T maxm = m[i][i];
        size_t row = i;
        foreach (immutable j; i .. n)
            if (m[j][i] > maxm) {
                maxm = m[j][i];
                row = j;
            }

        if (i != row)
            swap(id[i], id[row]);
    }

    return id;
}

/// Decomposes a square matrix A by PA=LU and returns L, U and P.
Tuple!(T[][],"L", T[][],"U", const T[][],"P")
lu(T)(immutable T[][] A) pure nothrow
in {
    assert(A.isSquare);
} body {
    immutable n = A.length;
    auto L = new T[][](n, n);
    auto U = new T[][](n, n);
    foreach (immutable i; 0 .. n) {
        L[i][i .. $] = 0;
        U[i][0 .. i] = 0;
    }

    immutable P = A.pivotize!T;
    immutable A2 = matrixMul!T(P, A);

    foreach (immutable j; 0 .. n) {
        L[j][j] = 1;
        foreach (immutable i; 0 .. j+1) {
            T s1 = 0;
            foreach (immutable k; 0 .. i)
                s1 += U[k][j] * L[i][k];
            U[i][j] = A2[i][j] - s1;
        }
        foreach (immutable i; j .. n) {
            T s2 = 0;
            foreach (immutable k; 0 .. j)
                s2 += U[k][j] * L[i][k];
            L[i][j] = (A2[i][j] - s2) / U[j][j];
        }
    }

    return typeof(return)(L, U, P);
}

void main() {
    immutable a = [[1.0, 3, 5],
                   [2.0, 4, 7],
                   [1.0, 1, 0]];
    immutable b = [[11.0, 9, 24, 2],
                   [1.0,  5,  2, 6],
                   [3.0, 17, 18, 1],
                   [2.0,  5,  7, 1]];

    auto f = "[%([%(%.1f, %)],\n %)]]\n\n".replicate(3);
    foreach (immutable m; [a, b])
        writefln(f, lu(m).tupleof);
}


import Control.Monad (when)

main = loop 1024
  where loop n = when (n > 0)
                      (do print n
                          loop (n `div` 2))


var i = 1024;

while (i > 0) {
  Sys.println(i);
  i >>= 1;
}


let i 1024
while i > 0
  println i
  let i (i / 2)
endwhile


(lib 'matrix) ;; the matrix library provides LU-decomposition
(decimals 5)

(define A (list->array' (1 3 5 2 4 7 1 1 0 ) 3 3))
(define PLU (matrix-lu-decompose A)) ;; -> list of three matrices, P, Lower, Upper

(array-print (first PLU))
0  1  0
1  0  0
0  0  1
(array-print (second PLU))
1    0   0
0.5  1   0
0.5  -1  1
(array-print (caddr PLU))
2  4  7
0  1  1.5
0  0  -2

(define A (list->array '(11 9 24 2 1 5 2 6 3 17 18 1 2 5 7 1 ) 4 4))
(define PLU (matrix-lu-decompose A)) ;; -> list of three matrices, P, Lower, Upper
(array-print (first PLU))
1  0  0  0
0  0  1  0
0  1  0  0
0  0  0  1

(array-print (second PLU))
1        0        0       0
0.27273  1        0       0
0.09091  0.2875   1       0
0.18182  0.23125  0.0036  1

(array-print (caddr PLU))
11  9         24        2
0   14.54545  11.45455  0.45455
0   0         -3.475    5.6875
0   0         0         0.51079


procedure main()
   local i
   i := 1024
   while write(0 < (i := i / 2))
end


let N be 1024;
while N > 0:
	say "[N][line break]";
	let N be N / 2;


DEF X:INT

X=1024

OPENCONSOLE

WHILE X>0

    PRINT X
    X=X/2

ENDWHILE
'Output starts with 1024 and ends with 1.

'Putting the following in the loop will produce output starting with 512 and ending with 0:
'X=X/2
'PRINT X

'When compiled as a console only program, a press any key to continue message is automatic.
'I presume code is added by the compiler.
CLOSECONSOLE

'Since this is, in fact, an IWBASIC console program, which compiles and runs.
END


[[Int]] mat
L 10
   mat [+]= (1..10).map(x -> random:(1..20))

L(row) mat
   L(el) row
      print(el, end' ‘ ’)
      I el == 20
         L(row).break


program lu1
  implicit none
  call check( reshape([real(8)::1,2,1,3,4,1,5,7,0                  ],[3,3]) )
  call check( reshape([real(8)::11,1,3,2,9,5,17,5,24,2,18,7,2,6,1,1],[4,4]) )

contains

  subroutine check(a)
    real(8), intent(in)   :: a(:,:)
    integer               :: i,j,n
    real(8), allocatable  :: aa(:,:),l(:,:),u(:,:)
    integer, allocatable  :: p(:,:)
    integer, allocatable  :: ipiv(:)
    n = size(a,1)
    allocate(aa(n,n),l(n,n),u(n,n),p(n,n),ipiv(n))
    forall (j=1:n,i=1:n)
      aa(i,j) = a(i,j)
      u (i,j) = 0d0
      p (i,j) = merge(1  ,0  ,i.eq.j)
      l (i,j) = merge(1d0,0d0,i.eq.j)
    end forall
    call lu(aa, ipiv)
    do i = 1,n
       l(i, :i-1) = aa(i, :i-1)
       u(i,i:   ) = aa(i,i:   )
    end do
    p(ipiv,:) = p
    call mat_print('a',a)
    call mat_print('p',p)
    call mat_print('l',l)
    call mat_print('u',u)
    print *, "residual"
    print *, "|| P.A - L.U || =  ", maxval(abs(matmul(p,a)-matmul(l,u)))
  end subroutine

  subroutine lu(a,p)
!   in situ decomposition, corresponds to LAPACK's dgebtrf
    real(8), intent(inout) :: a(:,:)
    integer, intent(out  ) :: p(:)
    integer                :: n, i,j,k,kmax
    n = size(a,1)
    p = [ ( i, i=1,n ) ]
    do k = 1,n-1
        kmax = maxloc(abs(a(p(k:),k)),1) + k-1
        if (kmax /= k ) then
            p([k, kmax]) = p([kmax, k])
            a([k, kmax],:) = a([kmax, k],:)
        end if
        a(k+1:,k) = a(k+1:,k) / a(k,k)
        forall (j=k+1:n) a(k+1:,j) = a(k+1:,j) - a(k,j)*a(k+1:,k)
    end do
  end subroutine

  subroutine mat_print(amsg,a)
    character(*), intent(in) :: amsg
    class    (*), intent(in) :: a(:,:)
    integer                  :: i
    print*,' '
    print*,amsg
    do i=1,size(a,1)
      select type (a)
        type is (real(8)) ; print'(100f8.2)',a(i,:)
        type is (integer) ; print'(100i8  )',a(i,:)
      end select
    end do
    print*,' '
  end subroutine

end program


int i = 1024;
while(i > 0){
   System.out.println(i);
   i >>= 1; //also acceptable: i /= 2;
}


*        Loop nested               12/08/2015
LOOPNEST CSECT
         USING  LOOPNEST,R12
         LR     R12,R15
BEGIN    LA     R6,0               i
         LA     R8,1
         LA     R9,20
LOOPI1   BXH    R6,R8,ELOOPI1      do i=1 to hbound(x,1)
         LA     R7,0               j
         LA     R10,1
         LA     R11,20
LOOPJ1   BXH    R7,R10,ELOOPJ1     do j=1 to hbound(x,2)
         L      R5,RANDSEED        n
         M      R4,=F'397204094'   r4r5=n*const
         D      R4,=X'7FFFFFFF'    r5=r5 div (2^31-1)
         ST     R4,RANDSEED        r4=r5 mod (2^31-1) ; n=r4
         LR     R5,R4              r5=n
         LA     R4,0
         D      R4,=F'20'          r5=n div nn; r4=n mod nn
         LR     R2,R4              r2=randint(nn) [0:nn-1]
         LA     R2,1(R2)           randint(nn)+1
         LR     R1,R6              i
         BCTR   R1,0
         MH     R1,=H'20'
         LR     R5,R7              j
         BCTR   R5,0
         AR     R1,R5
         SLA    R1,2
         ST     R2,X(R1)           x(i,j)=randint(20)+1
         B      LOOPJ1
ELOOPJ1  B      LOOPI1
ELOOPI1  MVC    MVCZ,=CL80' '
         LA     R6,0               i
         LA     R8,1
         LA     R9,20
LOOPI2   BXH    R6,R8,ELOOPI2      do i=1 to hbound(x,1)
         LA     R7,0               j
         LA     R10,1
         LA     R11,20
LOOPJ2   BXH    R7,R10,ELOOPJ2     do j=1 to hbound(x,2)
         LR     R1,R6
         BCTR   R1,0
         MH     R1,=H'20'
         LR     R5,R7
         BCTR   R5,0
         AR     R1,R5
         SLA    R1,2
         L      R5,X(R1)           x(i,j)
         LR     R2,R5
         LA     R3,MVCZ
         AH     R3,MVCI
         XDECO  R2,XDEC
         MVC    0(4,R3),XDEC+8
         LH     R3,MVCI
         LA     R3,4(R3)
         STH    R3,MVCI
         L      R5,X(R1)
         C      R5,=F'20'          if x(i,j)=20
         BE     ELOOPI2            then exit
         B      LOOPJ2
ELOOPJ2  XPRNT  MVCZ,80
         MVC    MVCI,=H'0'
         MVC    MVCZ,=CL80' '
         B      LOOPI2
ELOOPI2  XPRNT  MVCZ,80
RETURN   XR     R15,R15
         BR     R14
X        DS     400F
MVCZ     DS     CL80
MVCI     DC     H'0'
XDEC     DS     CL16
RANDSEED DC     F'16807'           running n
         YREGS
         END    LOOPNEST


PROC Main()
  DEFINE PTR="CARD"
  BYTE i,j,found
  PTR ARRAY a(10)
  BYTE ARRAY tmp,
    a0(10),a1(10),a2(10),a3(10),a4(10),
    a5(10),a6(10),a7(10),a8(10),a9(10)

  a(0)=a0 a(1)=a1 a(2)=a2 a(3)=a3 a(4)=a4
  a(5)=a5 a(6)=a6 a(7)=a7 a(8)=a8 a(9)=a9

  FOR j=0 TO 9
  DO
    tmp=a(j)
    FOR i=0 TO 9
    DO
      tmp(i)=Rand(20)+1
    OD
  OD

  found=0
  FOR j=0 TO 9
  DO
    tmp=a(j)
    FOR i=0 TO 9
    DO
      PrintB(tmp(i)) Put(32)
      IF tmp(i)=20 THEN
        found=1 EXIT
      FI
    OD
    IF found THEN
      EXIT
    FI
    PutE()
  OD
RETURN


package main

import "fmt"

type matrix [][]float64

func zero(n int) matrix {
    r := make([][]float64, n)
    a := make([]float64, n*n)
    for i := range r {
        r[i] = a[n*i : n*(i+1)]
    }
    return r
}

func eye(n int) matrix {
    r := zero(n)
    for i := range r {
        r[i][i] = 1
    }
    return r
}

func (m matrix) print(label string) {
    if label > "" {
        fmt.Printf("%s:\n", label)
    }
    for _, r := range m {
        for _, e := range r {
            fmt.Printf(" %9.5f", e)
        }
        fmt.Println()
    }
}

func (a matrix) pivotize() matrix {
    p := eye(len(a))
    for j, r := range a {
        max := r[j]
        row := j
        for i := j; i < len(a); i++ {
            if a[i][j] > max {
                max = a[i][j]
                row = i
            }
        }
        if j != row {
            // swap rows
            p[j], p[row] = p[row], p[j]
        }
    }
    return p
}

func (m1 matrix) mul(m2 matrix) matrix {
    r := zero(len(m1))
    for i, r1 := range m1 {
        for j := range m2 {
            for k := range m1 {
                r[i][j] += r1[k] * m2[k][j]
            }
        }
    }
    return r
}

func (a matrix) lu() (l, u, p matrix) {
    l = zero(len(a))
    u = zero(len(a))
    p = a.pivotize()
    a = p.mul(a)
    for j := range a {
        l[j][j] = 1
        for i := 0; i <= j; i++ {
            sum := 0.
            for k := 0; k < i; k++ {
                sum += u[k][j] * l[i][k]
            }
            u[i][j] = a[i][j] - sum
        }
        for i := j; i < len(a); i++ {
            sum := 0.
            for k := 0; k < j; k++ {
                sum += u[k][j] * l[i][k]
            }
            l[i][j] = (a[i][j] - sum) / u[j][j]
        }
    }
    return
}

func main() {
    showLU(matrix{
        {1, 3, 5},
        {2, 4, 7},
        {1, 1, 0}})
    showLU(matrix{
        {11, 9, 24, 2},
        {1, 5, 2, 6},
        {3, 17, 18, 1},
        {2, 5, 7, 1}})
}

func showLU(a matrix) {
    a.print("\na")
    l, u, p := a.lu()
    l.print("l")
    u.print("u")
    p.print("p")
}


DEFINE putln == put '\n putch.

1024 [] [dup putln 2 /] while.


# To avoid printing 0, test if the input is greater than 1
1024 | recurse( if . > 1 then ./2 | floor else empty end)


#!/usr/bin/env jsish
/* Loops/While in Jsish */
var i = 1024;

while (i > 0) { puts(i); i = i / 2 | 0; }

/*
=!EXPECTSTART!=
1024
512
256
128
64
32
16
8
4
2
1
=!EXPECTEND!=
*/


with Ada.Text_IO;  use Ada.Text_IO;
with Ada.Numerics.Discrete_Random;

procedure Test_Loop_Nested is
   type Value_Type is range 1..20;
   package Random_Values is new Ada.Numerics.Discrete_Random (Value_Type);
   use Random_Values;
   Dice : Generator;
   A : array (1..10, 1..10) of Value_Type :=
          (others => (others => Random (Dice)));
begin

Outer :
   for I in A'Range (1) loop
      for J in A'Range (2) loop
         Put (Value_Type'Image (A (I, J)));
         exit Outer when A (I, J) = 20;
      end loop;
      New_Line;
   end loop Outer;
end Test_Loop_Nested;


'BEGIN' 'COMMENT' Loops/Nested - ALGOL60 - 19/06/2018;
  'INTEGER' SEED;
  'INTEGER' 'PROCEDURE' RANDOM(N);
  'VALUE' N; 'INTEGER' N;
  'BEGIN'
    SEED:=(SEED*19157+12347) '/' 21647;
    RANDOM:=SEED-(SEED '/' N)*N+1
  'END' RANDOM;
  'INTEGER' 'ARRAY' A(/1:10,1:10/);
  'INTEGER' I,J;
  SEED:=31569;
  'FOR' I:=1 'STEP' 1 'UNTIL' 10 'DO'
    'FOR' J:=1 'STEP' 1 'UNTIL' 10 'DO'
      A(/I,J/):=RANDOM(20);
  SYSACT(1,6,120);SYSACT(1,8,60);SYSACT(1,12,1);'COMMENT' open print;
  'FOR' I:=1 'STEP' 1 'UNTIL' 10 'DO'
    'FOR' J:=1 'STEP' 1 'UNTIL' 10 'DO' 'BEGIN'
      OUTINTEGER(1,A(/I,J/));
      'IF' A(/I,J/)=20 'THEN' 'GOTO' LAB;
	'END';
LAB:
'END'


import Data.List
import Data.Maybe
import Text.Printf

-- a matrix is represented as a list of columns
mmult :: Num a => [[a]] -> [[a]] -> [[a]]
mmult a b = [ [ sum $ zipWith (*) ak bj | ak <- (transpose a) ] | bj <- b ]

nth mA i j = (mA !! j) !! i

idMatrixPart n m k = [ [if (i==j) then 1 else 0 | i <- [1..n]] | j <- [k..m]]
idMatrix n = idMatrixPart n n 1

permMatrix n ix1 ix2 =
    [ [ if ((i==ix1 && j==ix2) || (i==ix2 && j==ix1) || (i==j && j /= ix1 && i /= ix2))
        then 1 else 0| i <- [0..n-1]] | j <- [0..n-1]]
permMatrix_inv n ix1 ix2 = permMatrix n ix2 ix1

-- count k from zero
elimColumn :: Int -> [[Rational]] -> Int -> [Rational]
elimMatrix :: Int -> [[Rational]] -> Int -> [[Rational]]
elimMatrix_inv :: Int -> [[Rational]] -> Int -> [[Rational]]

elimColumn n mA k = [(let mAkk = (nth mA k k) in  if (i>k) then (-(nth mA i k)/mAkk)
    else if (i==k) then 1 else 0) | i <- [0..n-1]]
elimMatrix n mA k = (idMatrixPart n k 1) ++ [elimColumn n mA k] ++ (idMatrixPart n n (k+2))
elimMatrix_inv n mA k = (idMatrixPart n k 1) ++ --mA is elimMatrix there
    [let c = (mA!!k) in [if (i==k) then 1 else if (i<k) then 0 else (-(c!!i)) | i <- [0..n-1]]]
     ++ (idMatrixPart n n (k+2))

swapIndx :: [[Rational]] -> Int -> Int
swapIndx mA k = fromMaybe k (findIndex (>0) (drop k (mA!!k)))

-- LUP; lupStep returns [L:U:P]
paStep_recP :: Int -> [[Rational]] -> [[Rational]] -> [[Rational]] -> Int -> [[[Rational]]]
paStep_recM :: Int -> [[Rational]] -> [[Rational]] -> [[Rational]] -> Int -> [[[Rational]]]
lupStep :: Int -> [[Rational]] -> [[[Rational]]]

paStep_recP n mP mA mL cnt =
    let mPt = permMatrix n cnt (swapIndx mA cnt) in
        let mPtInv = permMatrix_inv n cnt (swapIndx mA cnt) in
    if (cnt >= n) then [(mmult mP mL),mA,mP] else
        (paStep_recM n (mmult mPt mP) (mmult mPt mA) (mmult mL mPtInv) cnt)

paStep_recM n mP mA mL cnt =
    let mMt = elimMatrix n mA cnt in
        let mMtInv = elimMatrix_inv n mMt cnt in
    paStep_recP n mP (mmult mMt mA) (mmult mL mMtInv) (cnt + 1)

lupStep n mA = paStep_recP n (idMatrix n) mA (idMatrix n) 0

--IO
matrixFromRationalToString m = concat $ intersperse "\n"
    (map (\x -> unwords $ printf "%8.4f" <$> (x::[Double]))
        (transpose (matrixFromRational m))) where
        matrixFromRational m = map (\x -> map fromRational x) m

solveTask mY = let mLUP = lupStep (length mY) mY in
    putStrLn ("A: \n" ++ matrixFromRationalToString mY) >>
    putStrLn ("L: \n" ++ matrixFromRationalToString (mLUP!!0)) >>
    putStrLn ("U: \n" ++ matrixFromRationalToString (mLUP!!1)) >>
    putStrLn ("P: \n" ++ matrixFromRationalToString (mLUP!!2)) >>
    putStrLn ("Verify: PA\n" ++ matrixFromRationalToString (mmult (mLUP!!2) mY)) >>
    putStrLn ("Verify: LU\n" ++ matrixFromRationalToString (mmult (mLUP!!0) (mLUP!!1)))

mY1 = [[1, 2, 1], [3, 4, 7], [5, 7, 0]] :: [[Rational]]
mY2 = [[11, 1, 3, 2], [9, 5, 17, 5], [24, 2, 18, 7], [2, 6, 1, 1]] :: [[Rational]]
main = putStrLn "Task1: \n" >> solveTask mY1 >>
    putStrLn "Task2: \n" >> solveTask mY2


n = 1024

while n > 0
    println(n)
    n >>= 1
end


// version 1.0.6

fun main(args: Array<String>) {
    var value = 1024
    while (value > 0) {
        println(value)
        value /= 2
    }
}


main: (
    [10][10]INT a; INT i, j;

    FOR i FROM LWB a TO UPB a DO
        FOR j FROM LWB a[i] TO UPB a[i] DO
            a[i][j] := ENTIER (random * 20 + 1)
        OD
    OD ;
    FOR i FROM LWB a TO UPB a DO
        FOR j FROM LWB a[i] TO UPB a[i] DO
            print(whole(a[i][j], -3));
            IF a[i][j] = 20 THEN
                GO TO xkcd com 292 # http://xkcd.com/292/ #
            FI
        OD;
        print(new line)
    OD;
xkcd com 292:
    print(new line)
)


on loopDemo(array, stopVal)
    set out to {}
    repeat with i from 1 to (count array)
        set inRow to item i of array
        set outRow to {}
        repeat with j from 1 to (count inRow)
            set n to item j of inRow
            set end of outRow to n
            if (n = stopVal) then exit repeat # <--
        end repeat
        set end of out to outRow
        if (n = stopVal) then exit repeat # <--
    end repeat

    return out
end loopDemo


module Main

import Data.Vect

Matrix : Nat -> Nat -> Type -> Type
Matrix m n t = Vect m (Vect n t)

-- Creates list from 0 to n (not including n)
upTo : (m : Nat) -> Vect m (Fin m)
upTo Z = []
upTo (S n) = 0 :: (map FS (upTo n))

-- Creates list from 0 to n-1  (not including n-1)
upToM1 : (m : Nat) -> (sz ** Vect sz (Fin m))
upToM1 m = case (upTo m) of
                  (y::ys) => (_ ** init(y::ys))
                  [] => (_ ** [])

-- Creates list from i to n (not including n)
fromUpTo : {n : Nat} -> Fin n -> (sz ** Vect sz (Fin n))
fromUpTo {n} m = filter (>= m) (upTo n)

-- Creates list from i+1 to n (not including n)
fromUpTo1 : {n : Nat} -> Fin n -> (sz ** Vect sz (Fin n))
fromUpTo1 {n} m with (fromUpTo m)
  | (_ ** xs) = case xs of
                  (y::ys) => (_ ** ys)
                  [] => (_ ** [])

-- Create Zero Matrix of size m by n
zeros : (m : Nat) -> (n : Nat) -> Matrix m n Double
zeros m n = replicate m (replicate n 0.0)

replaceAtM : (Fin m, Fin n) -> t -> Matrix m n t -> Matrix m n t
replaceAtM (i, j) e a = replaceAt i (replaceAt j e (index i a)) a

-- Create Identity Matrix of size m by m
eye : (m : Nat) -> Matrix m m Double
eye m = map create1Vec (upTo m)
  where
    set1 : Vect m Double -> Fin m -> Vect m Double
    set1 a n = replaceAt n 1.0 a

    create1Vec : Fin m -> Vect m Double
    create1Vec n = set1 (replicate m 0.0) n

indexM : (Fin m, Fin n) -> Matrix m n t -> t
indexM (i, j) a = index j (index i a)

-- Obtain index for the row containing the
-- largest absolute value for the given column
colAbsMaxIndex : Fin m -> Fin m -> Matrix m m Double -> Fin m
colAbsMaxIndex startRow col a {m} with (fromUpTo startRow)
  | (_ ** xs) =
    snd $ foldl (\(absMax, idx), curIdx =>
          let curAbsVal = abs(indexM (curIdx, col) a) in
            if (curAbsVal > absMax)
              then (curAbsVal, curIdx)
              else (absMax, idx)
        ) (0.0, startRow) xs

-- Swaps two rows in a given matrix
swapRows : Fin m -> Fin m -> Matrix m n t -> Matrix m n t
swapRows r1 r2 a = replaceAt r2 tempRow $ replaceAt r1 (index r2 a) a
  where tempRow = index r1 a

-- Swaps two individual values in a matrix
swapValues : (Fin m, Fin m) -> (Fin m, Fin m) -> Matrix m m Double -> Matrix m m Double
swapValues (i1, j1) (i2, j2) m = replaceAtM (i2, j2) v1 $ replaceAtM (i1, j1) v2 m
  where
      v1 = indexM (i1, j1) m
      v2 = indexM (i2, j2) m

-- Perform row Swap on Lower Triangular Matrix
lSwapRow : Fin m -> Fin m -> Matrix m m Double -> Matrix m m Double
lSwapRow row1 row2 l {m} with (filter (< row1) (upTo m))
  | (_ ** xs) =  foldl (\l',col => swapValues (row1, col) (row2, col) l') l xs

rowSwap : Fin m -> (Matrix m m Double,  Matrix m m Double, Matrix m m Double) ->
                        (Matrix m m Double, Matrix m m Double, Matrix m m Double)
rowSwap col (l,u,p) = (lSwapRow col row l, swapRows col row u, swapRows col row p)
      where row = colAbsMaxIndex col col u

calc : (Fin m) -> (Fin m) -> (Matrix m m Double, Matrix m m Double) ->
                                (Matrix m m Double, Matrix m m Double)
calc i j (l, u) {m} = (l', u')
   where
         l' : Matrix m m Double
         l' = replaceAtM (j, i) ((indexM (j, i) u) / indexM (i, i) u) l

         u'' : (Fin m) -> (Matrix m m Double) -> (Matrix m m Double)
         u'' k u = replaceAtM (j, k) ((indexM (j, k) u) -
                  ((indexM (j, i) l') * (indexM (i, k) u))) u

         u' : (Matrix m m Double)
         u' with (fromUpTo i) | (_ ** xs) = foldl (\curU, idx => u'' idx curU) u xs

-- Perform a single iteration of the algorithm for the given column
iteration : Fin m -> (Matrix m m Double, Matrix m m Double, Matrix m m Double) ->
                        (Matrix m m Double, Matrix m m Double, Matrix m m Double)
iteration i lup {m} = iterate' (rowSwap i lup)

          where
                modify : (Matrix m m Double, Matrix m m Double) ->
                            (Matrix m m Double, Matrix m m Double)
                modify lu with (fromUpTo1 i) | (_ ** xs) =
                                            foldl (\lu',j => calc i j lu') lu xs

                iterate' : (Matrix m m Double, Matrix m m Double, Matrix m m Double) ->
                              (Matrix m m Double, Matrix m m Double, Matrix m m Double)
                iterate' (l, u, p) with (modify (l, u)) | (l', u') = (l', u', p)

-- Generate L, U, P matricies from a given square matrix.
-- Where L * U = A, and P is the permutation matrix
luDecompose : Matrix m m Double -> (Matrix m m Double, Matrix m m Double, Matrix m m Double)
luDecompose a {m} with (upToM1 m)
  | (_ ** xs) = foldl (\lup,idx => iteration idx lup) (eye m,a,eye m) xs

ex1 : (Matrix 3 3 Double, Matrix 3 3 Double, Matrix 3 3 Double)
ex1 = luDecompose [[1, 3, 5], [2, 4, 7], [1, 1, 0]]

ex2 : (Matrix 4 4 Double, Matrix 4 4 Double, Matrix 4 4 Double)
ex2 = luDecompose [[11, 9, 24, 2], [1, 5, 2, 6], [3, 17, 18, 1], [2, 5, 7, 1]]

printEx : (Matrix n n Double, Matrix n n Double, Matrix n n Double) -> IO ()
printEx (l, u, p) = do
  putStr "l:"
  print l
  putStrLn "\n"

  putStr "u:"
  print u
  putStrLn "\n"

  putStr "p:"
  print p
  putStrLn "\n"

main : IO()
main = do
  putStrLn "Solution 1:"
  printEx ex1
  putStrLn "Solution 2:"
  printEx ex2


{def loops_while
 {lambda {:i}
  {if {< :i 1}
   then (end of loop)
   else :i {loops_while {/ :i 2}}}}}
-> loops_while

{loops_while 1024}
-> 1024 512 256 128 64 32 16 8 4 2 1 (end of loop)


/* ARM assembly Raspberry PI  */
/*  program loopnested.s   */

/************************************/
/* Constantes                       */
/************************************/
.equ STDOUT, 1     @ Linux output console
.equ EXIT,   1     @ Linux syscall
.equ WRITE,  4     @ Linux syscall

.equ NBVALUECOL,      10
.equ NBLIGNES,        10
.equ MAXVALUE,        20

/*********************************/
/* Initialized data              */
/*********************************/
.data
sMessResult:        .ascii " "
sMessValeur:        .fill 11, 1, ' '            @ size => 11
szCarriageReturn:   .asciz "\n"

.align 4
iGraine:  .int 314159

/*********************************/
/* UnInitialized data            */
/*********************************/
.bss
tiValues:                .skip  4 * NBVALUECOL * NBLIGNES
/*********************************/
/*  code section                 */
/*********************************/
.text
.global main
main:                                             @ entry of program
    ldr r3,iAdrtiValues
    mov r4,#0                                     @ loop indice
    mov r5,#0
    mov r7,#4 * NBVALUECOL
1:                                                @ begin loop 1
    mov r0,#MAXVALUE + 1
    bl genereraleas                               @ result 0 to MAXVALUE

    mul r6,r5,r7
    add r6,r4,lsl #2
    str r0,[r3,r6]
    add r4,#1
    cmp r4,#NBVALUECOL
    blt 1b
    mov r4,#0
    add r5,#1
    cmp r5,#NBLIGNES
    blt 1b

    mov r4,#0                                     @ loop indice
    mov r5,#0                                     @ total
    ldr r3,iAdrtiValues                           @ table values address
2:
    mul r6,r5,r7
    add r6,r4,lsl #2
    ldr r0,[r3,r6]
    ldr r1,iAdrsMessValeur                        @ display value
    bl conversion10                               @ call conversion decimal
    mov r1,#0
    ldr r0,iAdrsMessResult
    strb r1,[r0,#4]
    ldr r0,iAdrsMessResult
    bl affichageMess                              @ display message
    ldr r0,[r3,r6]
    cmp r0,#MAXVALUE
    beq 3f
    add r4,#1
    cmp r4,#NBVALUECOL
    blt 2b
    ldr r0,iAdrszCarriageReturn
    bl affichageMess                              @ display message
    mov r4,#0
    add r5,#1
    cmp r5,#NBLIGNES
    blt 2b
    b 100f
3:
    ldr r0,iAdrszCarriageReturn
    bl affichageMess                              @ display message

100:                                              @ standard end of the program
    mov r0, #0                                    @ return code
    mov r7, #EXIT                                 @ request to exit program
    svc #0                                        @ perform the system call

iAdrsMessValeur:          .int sMessValeur
iAdrszCarriageReturn:     .int szCarriageReturn
iAdrsMessResult:          .int sMessResult
iAdrtiValues:             .int tiValues

/******************************************************************/
/*     display text with size calculation                         */
/******************************************************************/
/* r0 contains the address of the message */
affichageMess:
    push {r0,r1,r2,r7,lr}                          @ save  registres
    mov r2,#0                                      @ counter length
1:                                                 @ loop length calculation
    ldrb r1,[r0,r2]                                @ read octet start position + index
    cmp r1,#0                                      @ if 0 its over
    addne r2,r2,#1                                 @ else add 1 in the length
    bne 1b                                         @ and loop
                                                   @ so here r2 contains the length of the message
    mov r1,r0                                      @ address message in r1
    mov r0,#STDOUT                                 @ code to write to the standard output Linux
    mov r7, #WRITE                                 @ code call system "write"
    svc #0                                         @ call systeme
    pop {r0,r1,r2,r7,lr}                           @ restaur des  2 registres */
    bx lr                                          @ return
/******************************************************************/
/*     Converting a register to a decimal unsigned                */
/******************************************************************/
/* r0 contains value and r1 address area   */
/* r0 return size of result (no zero final in area) */
/* area size => 11 bytes          */
.equ LGZONECAL,   10
conversion10:
    push {r1-r4,lr}                                 @ save registers
    mov r3,r1
    mov r2,#LGZONECAL

1:                                                  @ start loop
    bl divisionpar10U                               @ unsigned  r0 <- dividende. quotient ->r0 reste -> r1
    add r1,#48                                      @ digit
    strb r1,[r3,r2]                                 @ store digit on area
    cmp r0,#0                                       @ stop if quotient = 0
    subne r2,#1                                     @ else previous position
    bne 1b                                          @ and loop
                                                    @ and move digit from left of area
    mov r4,#0
2:
    ldrb r1,[r3,r2]
    strb r1,[r3,r4]
    add r2,#1
    add r4,#1
    cmp r2,#LGZONECAL
    ble 2b
                                                      @ and move spaces in end on area
    mov r0,r4                                         @ result length
    mov r1,#' '                                       @ space
3:
    strb r1,[r3,r4]                                   @ store space in area
    add r4,#1                                         @ next position
    cmp r4,#LGZONECAL
    ble 3b                                            @ loop if r4 <= area size

100:
    pop {r1-r4,lr}                                    @ restaur registres
    bx lr                                             @return

/***************************************************/
/*   division par 10   unsigned                    */
/***************************************************/
/* r0 dividende   */
/* r0 quotient */
/* r1 remainder  */
divisionpar10U:
    push {r2,r3,r4, lr}
    mov r4,r0                                          @ save value
    //mov r3,#0xCCCD                                   @ r3 <- magic_number lower  raspberry 3
    //movt r3,#0xCCCC                                  @ r3 <- magic_number higter raspberry 3
    ldr r3,iMagicNumber                                @ r3 <- magic_number    raspberry 1 2
    umull r1, r2, r3, r0                               @ r1<- Lower32Bits(r1*r0) r2<- Upper32Bits(r1*r0)
    mov r0, r2, LSR #3                                 @ r2 <- r2 >> shift 3
    add r2,r0,r0, lsl #2                               @ r2 <- r0 * 5
    sub r1,r4,r2, lsl #1                               @ r1 <- r4 - (r2 * 2)  = r4 - (r0 * 10)
    pop {r2,r3,r4,lr}
    bx lr                                              @ leave function
iMagicNumber:  	.int 0xCCCCCCCD
/***************************************************/
/*   Generation random number                  */
/***************************************************/
/* r0 contains limit  */
genereraleas:
    push {r1-r4,lr}                                    @ save registers
    ldr r4,iAdriGraine
    ldr r2,[r4]
    ldr r3,iNbDep1
    mul r2,r3,r2
    ldr r3,iNbDep1
    add r2,r2,r3
    str r2,[r4]                                        @ maj de la graine pour l appel suivant
    cmp r0,#0
    beq 100f
    mov r1,r0                                          @ divisor
    mov r0,r2                                          @ dividende
    bl division
    mov r0,r3                                          @ résult = remainder

100:                                                   @ end function
    pop {r1-r4,lr}                                     @ restaur registers
    bx lr                                              @ return
/*****************************************************/
iAdriGraine: .int iGraine
iNbDep1: .int 0x343FD
iNbDep2: .int 0x269EC3
/***************************************************/
/* integer division unsigned                       */
/***************************************************/
division:
    /* r0 contains dividend */
    /* r1 contains divisor */
    /* r2 returns quotient */
    /* r3 returns remainder */
    push {r4, lr}
    mov r2, #0                                         @ init quotient
    mov r3, #0                                         @ init remainder
    mov r4, #32                                        @ init counter bits
    b 2f
1:                                                     @ loop
    movs r0, r0, LSL #1                                @ r0 <- r0 << 1 updating cpsr (sets C if 31st bit of r0 was 1)
    adc r3, r3, r3                                     @ r3 <- r3 + r3 + C. This is equivalent to r3 ? (r3 << 1) + C
    cmp r3, r1                                         @ compute r3 - r1 and update cpsr
    subhs r3, r3, r1                                   @ if r3 >= r1 (C=1) then r3 <- r3 - r1
    adc r2, r2, r2                                     @ r2 <- r2 + r2 + C. This is equivalent to r2 <- (r2 << 1) + C
2:
    subs r4, r4, #1                                    @ r4 <- r4 - 1
    bpl 1b                                             @ if r4 >= 0 (N=0) then loop
    pop {r4, lr}
    bx lr


import static java.util.Arrays.stream;
import java.util.Locale;
import static java.util.stream.IntStream.range;

public class Test {

    static double dotProduct(double[] a, double[] b) {
        return range(0, a.length).mapToDouble(i -> a[i] * b[i]).sum();
    }

    static double[][] matrixMul(double[][] A, double[][] B) {
        double[][] result = new double[A.length][B[0].length];
        double[] aux = new double[B.length];

        for (int j = 0; j < B[0].length; j++) {

            for (int k = 0; k < B.length; k++)
                aux[k] = B[k][j];

            for (int i = 0; i < A.length; i++)
                result[i][j] = dotProduct(A[i], aux);
        }
        return result;
    }

    static double[][] pivotize(double[][] m) {
        int n = m.length;
        double[][] id = range(0, n).mapToObj(j -> range(0, n)
                .mapToDouble(i -> i == j ? 1 : 0).toArray())
                .toArray(double[][]::new);

        for (int i = 0; i < n; i++) {
            double maxm = m[i][i];
            int row = i;
            for (int j = i; j < n; j++)
                if (m[j][i] > maxm) {
                    maxm = m[j][i];
                    row = j;
                }

            if (i != row) {
                double[] tmp = id[i];
                id[i] = id[row];
                id[row] = tmp;
            }
        }
        return id;
    }

    static double[][][] lu(double[][] A) {
        int n = A.length;
        double[][] L = new double[n][n];
        double[][] U = new double[n][n];
        double[][] P = pivotize(A);
        double[][] A2 = matrixMul(P, A);

        for (int j = 0; j < n; j++) {
            L[j][j] = 1;
            for (int i = 0; i < j + 1; i++) {
                double s1 = 0;
                for (int k = 0; k < i; k++)
                    s1 += U[k][j] * L[i][k];
                U[i][j] = A2[i][j] - s1;
            }
            for (int i = j; i < n; i++) {
                double s2 = 0;
                for (int k = 0; k < j; k++)
                    s2 += U[k][j] * L[i][k];
                L[i][j] = (A2[i][j] - s2) / U[j][j];
            }
        }
        return new double[][][]{L, U, P};
    }

    static void print(double[][] m) {
        stream(m).forEach(a -> {
            stream(a).forEach(n -> System.out.printf(Locale.US, "%5.1f ", n));
            System.out.println();
        });
        System.out.println();
    }

    public static void main(String[] args) {
        double[][] a = {{1.0, 3, 5}, {2.0, 4, 7}, {1.0, 1, 0}};

        double[][] b = {{11.0, 9, 24, 2}, {1.0, 5, 2, 6}, {3.0, 17, 18, 1},
        {2.0, 5, 7, 1}};

        for (double[][] m : lu(a))
            print(m);

        System.out.println();

        for (double[][] m : lu(b))
            print(m);
    }
}


: /i  / int ; : 0=  0 == ;
: dip  swap '_ set execute _ ; : dupd  'dup dip ;
: 2dip  swap '_x set swap '_y set execute _y _x ;
: while
    do  dupd 'execute 2dip
        rot 0= if break else dup 2dip then
    loop ;

1024 "dup 0 >" "dup . 2 /i" while


var .i = 1024
while .i > 0 {
    writeln .i
    .i \= 2
}


Loop, 10
{
  i := A_Index
  Loop, 10
  {
    j := A_Index
    Random, a%i%%j%, 1, 20
  }
}

Loop, 10
{
  i := A_Index
  Loop, 10
  {
    j := A_Index
    If (a%i%%j% == 20)
      Goto finish
  }
}

finish:
  MsgBox % "a[" . i . "][" . j . "]" is 20
Return


BEGIN {
	rows = 5
	columns = 5

	# Fill ary[] with random numbers from 1 to 20.
	for (r = 1; r <= rows; r++) {
		for (c = 1; c <= columns; c++)
			ary[r, c] = int(rand() * 20) + 1
	}

	# Find a 20.
	b = 0
	for (r = 1; r <= rows; r++) {
		for (c = 1; c <= columns; c++) {
			v = ary[r, c]
			printf " %2d", v
			if (v == 20) {
				print
				b = 1
				break
			}
		}
		if (b) break
		print
	}
}


const mult=(a, b)=>{
  let res = new Array(a.length);
  for (let r = 0; r < a.length; ++r) {
    res[r] = new Array(b[0].length);
    for (let c = 0; c < b[0].length; ++c) {
      res[r][c] = 0;
      for (let i = 0; i < a[0].length; ++i)
        res[r][c] += a[r][i] * b[i][c];
    }
  }
  return res;
}

const lu = (mat) => {
    let lower = [],upper = [],n=mat.length;;
    for(let i=0;i<n;i++){
        lower.push([]);
        upper.push([]);
        for(let j=0;j<n;j++){
            lower[i].push(0);
            upper[i].push(0);
        }
    }
    for (let i = 0; i < n; i++) {
        for (let k = i; k < n; k++){
            let sum = 0;
            for (let j = 0; j < i; j++)
                sum += (lower[i][j] * upper[j][k]);
            upper[i][k] = mat[i][k] - sum;
        }
        for (let k = i; k < n; k++) {
            if (i == k)
                lower[i][i] = 1;
            else{
                let sum = 0;
                for (let j = 0; j < i; j++)
                    sum += (lower[k][j] * upper[j][i]);
                lower[k][i] = (mat[k][i] - sum) / upper[i][i];
            }
        }
    }
    return [lower,upper];
}

const pivot = (m) =>{
    let n = m.length;
    let id = [];
    for(let i=0;i<n;i++){
        id.push([]);
        for(let j=0;j<n;j++){
            if(i===j)
                id[i].push(1);
            else
                id[i].push(0);
        }
    }
    for (let i = 0; i < n; i++) {
        let maxm = m[i][i];
        let row = i;
        for (let j = i; j < n; j++)
            if (m[j][i] > maxm) {
                maxm = m[j][i];
                row = j;
            }
        if (i != row) {
            let tmp = id[i];
            id[i] = id[row];
            id[row] = tmp;
        }
    }
    return id;
}

const luDecomposition=(A)=>{
    const P = pivot(A);
    A = mult(P,A);
    return [...lu(A),P];
}


i = 1024
while i > 0
   print i
   i = int( i / 2)
wend
end


set num 1024; while {$num > 0} {print $num; set num [expr $num \ 2]}


DIM a(1 TO 10, 1 TO 10) AS INTEGER
CLS
FOR row = 1 TO 10
        FOR col = 1 TO 10
                a(row, col) = INT(RND * 20) + 1
        NEXT col
NEXT row

FOR row = LBOUND(a, 1) TO UBOUND(a, 1)
        FOR col = LBOUND(a, 2) TO UBOUND(a, 2)
                PRINT a(row, col)
                IF a(row, col) = 20 THEN END
        NEXT col
NEXT row


dim a(20, 20)

for i = 0 to 19
	for j = 0 to 19
		a[i, j] = int(rand * 20) + 1
	next j
next i

for i = 0 to 19
	for j = 0 to 19
		print a[i, j];" ";
		if a[i, j] = 20 then end
	next j
next i

end


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

def I(n): matrix(n;n;0) as $m
  | reduce range(0;n) as $i ($m; . | setpath( [$i,$i]; 1));

def dot_product(a; b):
  reduce range(0;a|length) as $i (0; . + (a[$i] * b[$i]) );

# transpose/0 expects its input to be a rectangular matrix
def transpose:
  if (.[0] | length) == 0 then []
  else [map(.[0])] + (map(.[1:]) | transpose)
  end ;

# A and B should both be numeric matrices, A being m by n, and B being n by p.
def multiply(A; B):
  (B[0]|length) as $p
  | (B|transpose) as $BT
  | reduce range(0; A|length) as $i
       ([];
       reduce range(0; $p) as $j
         (.;
          .[$i][$j] = dot_product( A[$i]; $BT[$j] ) ));

def swap_rows(i;j):
  if i == j then .
  else .[i] as $i | .[i] = .[j] | .[j] = $i
  end ;

# Print a matrix neatly, each cell occupying n spaces, but without truncation
def neatly(n):
  def right: tostring | ( " " * (n-length) + .);
  . as $in
  | length as $length
  | reduce range (0;$length) as $i
      (""; . + reduce range(0;$length) as $j
      (""; "\(.) \($in[$i][$j] | right )" ) + "\n" ) ;


n = 1024
repeat while n>0
  put n
  n = n/2 -- integer division implicitely returns floor: 1/2 -> 0
end repeat


+ i : INTEGER;
i := 1024;
{ i > 0 }.while_do {
  i.println;

  i := i / 2;
};


put 1024 into n
repeat while n > 0
    put n & cr
    divide n by 2
end repeat


      DIM array(10,10)
      FOR row% = 0 TO 10
        FOR col% = 0 TO 10
          array(row%,col%) = RND(20) + 1
        NEXT
      NEXT row%
      FOR row% = 0 TO 10
        FOR col% = 0 TO 10
          PRINT "row "; row%, "col ";col%, "value "; array(row%,col%)
          IF array(row%,col%) = 20 EXIT FOR row%
        NEXT
      NEXT row%


s = 1	/* Seed of the random number generator */

/* Random number from 1 to 20. */
define r() {
	auto r
	while (1) {
		/*
		 * Formula (from POSIX) for random numbers of low
		 * quality, from 0 to 32767.
		 */
		s = (s * 1103515245 + 12345) % 4294967296
		r = (s / 65536) % 32768

		/* Prevent modulo bias. */
		if (r >= 32768 % 20) break
	}
	return ((r % 20) + 1)
}

r = 5	/* Total rows */
c = 5	/* Total columns */

/* Fill array a[] with random numbers from 1 to 20. */
for (i = 0; i < r; i++) {
	for (j = 0; j < c; j++) {
		a[i * c + j] = r()
	}
}

/* Find a 20. */
b = 0
for (i = 0; i < r; i++) {
	for (j = 0; j < c; j++) {
		v = a[i * c + j]
		v	/* Print v and a newline. */
		if (v == 20) {
			b = 1
			break
		}
	}
	if (b) break
	/* Print "==" and a newline. */
	"==
"
}
quit


// version 1.1.4-3

typealias Vector = DoubleArray
typealias Matrix = Array<Vector>

operator fun Matrix.times(other: Matrix): Matrix {
    val rows1 = this.size
    val cols1 = this[0].size
    val rows2 = other.size
    val cols2 = other[0].size
    require(cols1 == rows2)
    val result = Matrix(rows1) { Vector(cols2) }
    for (i in 0 until rows1) {
        for (j in 0 until cols2) {
            for (k in 0 until rows2) {
                result[i][j] += this[i][k] * other[k][j]
            }
        }
    }
    return result
}

fun pivotize(m: Matrix): Matrix {
    val n = m.size
    val im = Array(n) { Vector(n) }
    for (i in 0 until n) im[i][i] = 1.0
    for (i in 0 until n) {
        var max = m[i][i]
        var row = i
        for (j in i until n) {
            if (m[j][i] > max) {
                max = m[j][i]
                row = j
            }
        }
        if (i != row) {
            val t = im[i]
            im[i] = im[row]
            im[row] = t
        }
    }
    return im
}

fun lu(a: Matrix): Array<Matrix> {
    val n = a.size
    val l = Array(n) { Vector(n) }
    val u = Array(n) { Vector(n) }
    val p = pivotize(a)
    val a2 = p * a

    for (j in 0 until n) {
        l[j][j] = 1.0
        for (i in 0 until j + 1) {
            var sum = 0.0
            for (k in 0 until i) sum += u[k][j] * l[i][k]
            u[i][j] = a2[i][j] - sum
        }
        for (i in j until n) {
            var sum2 = 0.0
            for(k in 0 until j) sum2 += u[k][j] * l[i][k]
            l[i][j] = (a2[i][j] - sum2) / u[j][j]
        }
    }
    return arrayOf(l, u, p)
}

fun printMatrix(title: String, m: Matrix, f: String) {
    val n = m.size
    println("\n$title\n")
    for (i in 0 until n) {
        for (j in 0 until n) print("${f.format(m[i][j])}  ")
        println()
    }
}

fun main(args: Array<String>) {
    val a1 = arrayOf(
        doubleArrayOf( 1.0,  3.0,  5.0),
        doubleArrayOf( 2.0,  4.0,  7.0),
        doubleArrayOf( 1.0,  1.0,  0.0)
    )
    val (l1, u1, p1) = lu(a1)
    println("EXAMPLE 1:-")
    printMatrix("A:", a1, "%1.0f")
    printMatrix("L:", l1, "% 7.5f")
    printMatrix("U:", u1, "% 8.5f")
    printMatrix("P:", p1, "%1.0f")

    val a2 = arrayOf(
        doubleArrayOf(11.0,  9.0, 24.0,  2.0),
        doubleArrayOf( 1.0,  5.0,  2.0,  6.0),
        doubleArrayOf( 3.0, 17.0, 18.0,  1.0),
        doubleArrayOf( 2.0,  5.0,  7.0,  1.0)
    )
    val (l2, u2, p2) = lu(a2)
    println("\nEXAMPLE 2:-")
    printMatrix("A:", a2, "%2.0f")
    printMatrix("L:", l2, "%7.5f")
    printMatrix("U:", u2, "%8.5f")
    printMatrix("P:", p2, "%1.0f")
}


make "n 1024
while [:n > 0] [print :n  make "n :n / 2]


HAI 1.3

I HAS A n ITZ 1024

IM IN YR LOOP UPPIN YR nop WILE n
    VISIBLE n
    n R QUOSHUNT OF n AN 2
IM OUTTA YR LOOP

KTHXBYE


n = 1024
while n>0 do
  print(n)
  n = math.floor(n/2)
end


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

int main() {
    int a[10][10], i, j;

    srand(time(NULL));
    for (i = 0; i < 10; i++)
        for (j = 0; j < 10; j++)
            a[i][j] = rand() % 20 + 1;

    for (i = 0; i < 10; i++) {
        for (j = 0; j < 10; j++) {
            printf(" %d", a[i][j]);
            if (a[i][j] == 20)
                goto Done;
        }
        printf("\n");
    }
Done:
    printf("\n");
    return 0;
}


import std

// derived from JAMA v1.03

// rectangular input array A is transformed in place to LU form

def LUDecomposition(LU):
   // Use a "left-looking", dot-product, Crout/Doolittle algorithm.
   let m = LU.length
   let n = LU[0].length
   let piv = map(m): _
   var pivsign = 1
   let LUcolj = map(m): 0.0
   // Outer loop.
   for(n) j:
      // Make a copy of the j-th column to localize references
      for(m) i:
         LUcolj[i] = LU[i][j]
      // Apply previous transformations
      for(m) i:
         let LUrowi = LU[i]
         // Most of the time is spent in the following dot product
         let kmax = min(i,j)
         var s = 0.0
         for(kmax) k:
            s += LUrowi[k] * LUcolj[k]
         s = LUcolj[i] - s
         LUcolj[i] = s
         LUrowi[j] = s
      // Find pivot and exchange if necessary.
      var p = j
      var i = j+1
      while i < m:
         if abs(LUcolj[i]) > abs(LUcolj[p]):
            p = i
         i += 1
      if p != j:
         for(n) k:
            let t = LU[p][k]
            LU[p][k] = LU[j][k]
            LU[j][k] = t
         let k = piv[p]
         piv[p] = piv[j]
         piv[j] = k
         pivsign = -pivsign
      // Compute multipliers.
      if j < m and LU[j][j] != 0.0:
         i = j+1
         while i < m:
            LU[i][j] /= LU[j][j]
            i += 1
   return piv

def print_A(A):
   print "A:"
   for(A) row:
      print row

def print_L(LU):
   print "L:"
   for(LU) lurow, i:
      let row = map(lurow.length): 0.0
      for(lurow) x, j:
         if i > j:
            row[j] = x
         else: if i == j:
            row[j] = 1.0
      print row

def print_U(LU):
   print "U:"
   for(LU) lurow, i:
      let row = map(lurow.length): 0.0
      for(lurow) x, j:
         if i <= j:
            row[j] = x
      print row

def print_P(piv):
   print "P:"
   for(piv) j:
      let row = map(piv.length): 0
      row[j] = 1
      print row

var A = [[1., 3., 5.],
         [2., 4., 7.],
         [1., 1., 0.]]

print_A A
var piv = LUDecomposition(A)
print_L A
print_U A
print_P piv

A = [[11.,  9., 24., 2.],
     [ 1.,  5.,  2., 6.],
     [ 3., 17., 18., 1.],
     [ 2.,  5.,  7., 1.]]

print_A A
piv = LUDecomposition(A)
print_L A
print_U A
print_P piv


Module Checkit {
      Def long A=1024
      While A>0 {
            Print A
            A/=2
      }
}
Checkit


divert(-1)

define(`loop',
  `ifelse(eval(0 < ($1)),1,`$1`
'loop(eval(($1) / 2))')')

divert`'dnl
loop(1024)dnl


NEXT=`expr $* / 2`
MAX=10

all: $(MAX)-n;

0-n:;

%-n: %-echo
       @-make -f while.mk $(NEXT)-n MAX=$(MAX)

%-echo:
       @echo $*


using System;

class Program {
    static void Main(string[] args) {
        int[,] a = new int[10, 10];
        Random r = new Random();

        for (int i = 0; i < 10; i++) {
            for (int j = 0; j < 10; j++) {
                a[i, j] = r.Next(0, 21) + 1;
            }
        }

        for (int i = 0; i < 10; i++) {
            for (int j = 0; j < 10; j++) {
                Console.Write(" {0}", a[i, j]);
                if (a[i, j] == 20) {
                    goto Done;
                }
            }
            Console.WriteLine();
        }
    Done:
        Console.WriteLine();
    }
}


(*Ex1*)a = {{1, 3, 5}, {2, 4, 7}, {1, 1, 0}};
{lu, p, c} = LUDecomposition[a];
l = LowerTriangularize[lu, -1] + IdentityMatrix[Length[p]];
u = UpperTriangularize[lu];
P = Part[IdentityMatrix[Length[p]], p] ;
MatrixForm /@ {P.a , P, l, u, l.u}

(*Ex2*)a = {{11, 9, 24, 2}, {1, 5, 2, 6}, {3, 17, 18, 1}, {2, 5, 7, 1}};
{lu, p, c} = LUDecomposition[a];
l = LowerTriangularize[lu, -1] + IdentityMatrix[Length[p]];
u = UpperTriangularize[lu];
P = Part[IdentityMatrix[Length[p]], p] ;
MatrixForm /@ {P.a , P, l, u, l.u}


i = 1024;
While[i > 0,
 Print[i];
 i = Floor[i/2];
]


i = 1024;
while (i > 0)
    disp(i);
    i = floor(i/2);
end


#include<cstdlib>
#include<ctime>
#include<iostream>

using namespace std;
int main()
{
    int arr[10][10];
    srand(time(NULL));
    for(auto& row: arr)
        for(auto& col: row)
            col = rand() % 20 + 1;

    ([&](){
       for(auto& row : arr)
           for(auto& col: row)
           {
               cout << col << endl;
               if(col == 20)return;
           }
    })();
    return 0;
}


use Random;

var nums:[1..10, 1..10] int;
var rnd = new RandomStream();

[ n in nums ] n = floor(rnd.getNext() * 21):int;
delete rnd;

// this shows a clumsy explicit way of iterating, to actually create nested loops:
label outer for i in nums.domain.dim(1) {
        for j in nums.domain.dim(2) {
                write(" ", nums(i,j));
                if nums(i,j) == 20 then break outer;
        }
        writeln();
}


import macros, strutils
import strfmt

type

  Matrix[M, N: static int] = array[1..M, array[1..N, float]]
  SquareMatrix[N: static int] = Matrix[N, N]

# Templates to allow to use more natural notation for indexing.
template `[]`(m: Matrix; i, j: int): float = m[i][j]
template `[]=`(m: Matrix; i, j: int; val: float) = m[i][j] = val

func `*`[M, N, P: static int](a: Matrix[M, N]; b: Matrix[N, P]): Matrix[M, P] =
  ## Matrix multiplication.
  for i in 1..M:
    for j in 1..P:
      for k in 1..N:
        result[i, j] += a[i, k] * b[k, j]

func pivotize[N: static int](m: SquareMatrix[N]): SquareMatrix[N] =

  for i in 1..N: result[i, i] = 1

  for i in 1..N:
    var max = m[i, i]
    var row = i
    for j in i..N:
      if m[j, i] > max:
        max = m[j, i]
        row = j
    if i != row:
      swap result[i], result[row]

func lu[N: static int](m: SquareMatrix[N]): tuple[l, u, p: SquareMatrix[N]] =

  result.p = m.pivotize()
  let m2 = result.p * m

  for j in 1..N:
    result.l[j, j] = 1
    for i in 1..j:
      var sum = 0.0
      for k in 1..<i: sum += result.u[k, j] * result.l[i, k]
      result.u[i, j] = m2[i, j] - sum
    for i in j..N:
      var sum = 0.0
      for k in 1..<j: sum += result.u[k, j] * result.l[i, k]
      result.l[i, j] = (m2[i, j] - sum) / result.u[j, j]

proc print(m: Matrix; title, f: string) =
  echo '\n', title
  for i in 1..m.N:
    for j in 1..m.N:
      stdout.write m[i, j].format(f), "  "
    stdout.write '\n'

when isMainModule:

  const A1: SquareMatrix[3] = [[1.0, 3.0, 5.0],
                               [2.0, 4.0, 7.0],
                               [1.0, 1.0, 0.0]]

  let (l1, u1, p1) = A1.lu()
  echo "\nExample 2:"
  A1.print("A:", "1.0f")
  l1.print("L:", "8.5f")
  u1.print("U:", "8.5f")
  p1.print("P:", "1.0f")

  const A2: SquareMatrix[4] = [[11.0,  9.0, 24.0,  2.0],
                               [ 1.0,  5.0,  2.0,  6.0],
                               [ 3.0, 17.0, 18.0,  1.0],
                               [ 2.0,  5.0,  7.0,  1.0]]

  let (l2, u2, p2) = A2.lu()
  echo "Example 1:"
  A2.print("A:", "2.0f")
  l2.print("L:", "8.5f")
  u2.print("U:", "8.5f")
  p2.print("P:", "1.0f")


block([n], n: 1024, while n > 0 do (print(n), n: quotient(n, 2)));

/* using a C-like loop: divide control variable by two instead of incrementing it */
for n: 1024 next quotient(n, 2) while n > 0 do print(n);


a = 1024
while a > 0 do
(
    print a
    a /= 2
)


a := 1024;
forever: exitif not (a > 0);
  show a;
  a := a div 2;
endfor


(ns nested)

(defn create-matrix [width height]
  (for [_ (range width)]
    (for [_ (range height)]
      (inc (rand-int 20)))))

(defn print-matrix [matrix]
  (loop [[row & rs] matrix]
    (when (= (loop [[x & xs] row]
               (println x)
               (cond (= x 20) :stop
                     xs (recur xs)
                     :else :continue))
             :continue)
      (when rs (recur rs)))))

(print-matrix (create-matrix 10 10))


       IDENTIFICATION DIVISION.
       PROGRAM-ID. Nested-Loop.

       DATA DIVISION.
       LOCAL-STORAGE SECTION.
       78  Table-Size VALUE 10.
       01  Table-Area.
           03  Table-Row OCCURS Table-Size TIMES
                   INDEXED BY Row-Index.
               05  Table-Element PIC 99 OCCURS Table-Size TIMES
                   INDEXED BY Col-Index.

       01  Current-Time PIC 9(8).
       PROCEDURE DIVISION.
*          *> Seed RANDOM.
           ACCEPT Current-Time FROM TIME
           MOVE FUNCTION RANDOM(Current-Time) TO Current-Time

*          *> Put random numbers in the table.
*          *> The AFTER clause is equivalent to a nested PERFORM VARYING
*          *> statement.
           PERFORM VARYING Row-Index FROM 1 BY 1
                       UNTIL Table-Size < Row-Index
                   AFTER Col-Index FROM 1 BY 1
                       UNTIL Table-Size < Col-Index
               COMPUTE Table-Element (Row-Index, Col-Index) =
                   FUNCTION MOD((FUNCTION RANDOM * 1000), 20) + 1
           END-PERFORM

*          *> Search through table for 20.
*          *> Using proper nested loops.
           PERFORM VARYING Row-Index FROM 1 BY 1
                   UNTIL Table-Size < Row-Index
               PERFORM VARYING Col-Index FROM 1 BY 1
                       UNTIL Table-Size < Col-Index
                   IF Table-Element (Row-Index, Col-Index) = 20
                       EXIT PERFORM
                   ELSE
                       DISPLAY Table-Element (Row-Index, Col-Index)
                   END-IF
               END-PERFORM
           END-PERFORM

           GOBACK
           .


matlup(M) =
{
  my (L = matid(#M), U = M, P = L);

  for (i = 1, #M-1,     \\ pivoting
    p = M[z=i,i];
    for (k = i, #M, if (M[k,i] > p, p = M[z=k,i]));

    if (i != z,         \\ swap rows
      k = U[i,]; U[i,] = U[z,]; U[z,] = k;
      k = P[i,]; P[i,] = P[z,]; P[z,] = k;
    );
  );

  for (i = 1, #M-1,     \\ decompose
    for (k = i+1, #M,
      L[k,i] = U[k,i] / U[i,i];
      for (j = i, #M, U[k,j] -= L[k,i] * U[i,j])
    )
  );

  [L,U,P]       \\ return L,U,P triple matrix
}


i = 1024
While i > 0
  TextWindow.WriteLine(i)
  i = Math.Floor(i / 2)
EndWhile


i = 1024
while i > 0
    print i
    i = floor(i/2)
end while


alias while_loop {
  var %n = 10
  while (%n >= 0) {
    echo -a Countdown: %n
    dec %n
  }
}


<Cfset RandNum = 0>
<Cfloop condition="randNum neq 20">
  <Cfloop from="1" to="5" index="i">
    <Cfset randNum = RandRange(1, 20)>
    <Cfoutput>#randNum# </Cfoutput>
    <Cfif RandNum eq 20><cfbreak></Cfif>
  </Cfloop>
  <br>
</Cfloop>


(let ((a (make-array '(10 10))))
  (dotimes (i 10)
    (dotimes (j 10)
      (setf (aref a i j) (1+ (random 20)))))

  (block outer
    (dotimes (i 10)
      (dotimes (j 10)
        (princ " ")
        (princ (aref a i j))
        (if (= 20 (aref a i j))
            (return-from outer)))
      (terpri))
    (terpri)))


******************************************
* X = M / N WHILE X > 0
* STORE EACH X IN NUMERIC ARRAY
* PRINT ARRAY
*******************************************
M	EQU	1024
N	EQU	2
LPR	EQU	18
BUF0	EQU	100
MSG	EQU	2000
LENGTH	EQU	500
	ORIG	3000
START	IOC	0(LPR)
	ENTX	M
CALC	STX	BUF0,1
	DIV	=N=
	SRAX	5
	INC1	1
	JXP	CALC
	ST1	LENGTH
PRINT	LDA	BUF0,2
	CHAR
	STX	MSG
	OUT	MSG(LPR)
	INC2	1
	CMP2	LENGTH
	JNE	PRINT
	HLT
	END	START