MODULE DivBy2;
  IMPORT InOut;

  VAR
    i: INTEGER;
BEGIN
  i := 1024;
  WHILE i > 0 DO
    InOut.WriteInt(i, 4);
    InOut.WriteLn;
    i := i DIV 2
  END
END DivBy2.


import std.stdio, std.random;

void main() {
    int[10][10] mat;
    foreach (ref row; mat)
        foreach (ref item; row)
            item = uniform(1, 21);

    outer:
    foreach (row; mat)
        foreach (item; row) {
            write(item, ' ');
            if (item == 20)
                break outer;
        }

    writeln();
}


1 ss  [Seed of the random number generator.]sz

[*
 * lrx -- (number)
 * Push a random number from 1 to 20.
 *]sz
[
 [                [If preventing modulo bias:]sz
  sz               [Drop this random number.]sz
  lLx              [Loop.]sz
 ]SI
 [                [Loop:]sz
  [*
   * Formula (from POSIX) for random numbers of low quality.
   * Push a random number from 0 to 32767.
   *]sz
  ls 1103515245 * 12345 + 4294967296 % ss
  ls 65536 / 32768 %

  d 32768 20 % >I  [Prevent modulo bias.]sz
 ]d SL x
 20 % 1 +         [Be from 1 to 20.]sz
 LLsz LIsz        [Restore L, I.]sz
]sr

5 sb           [b = Total rows]sz
5 sc           [c = Total columns]sz

[Fill array a[] with random numbers from 1 to 20.]sz
[              [Inner loop for j:]sz
 lrx            [Push random number.]sz
 li lc * lj +   [Push index of a[i, j].]sz
 :a             [Put in a[].]sz
 lj 1 + d sj    [j += 1]sz
 lc >I          [Loop while c > j.]sz
]sI
[              [Outer loop for i:]sz
 0 d sj         [j = 0]sz
 lc >I          [Enter inner loop.]sz
 li 1 + d si    [i += 1]sz
 lb >L          [Loop while b > i.]sz
]sL
0 d si         [i = 0]sz
lb >L          [Enter outer loop.]sz

[Find a 20.]sz
[              [If detecting a 20:]sz
 li lj + 3 + Q  [Break outer loop.]sz
]sD
[              [Inner loop for j:]sz
 li lc * lj +   [Push index of a[i,j].]sz
 ;a             [Push value from a[].]sz
 p              [Print value and a newline.]sz
 20 =D          [Detect a 20.]sz
 lj 1 + d sj    [j += 1]sz
 lc >I          [Loop while c > j.]sz
]sI
[              [Outer loop for i:]sz
 0 d sj         [j = 0]sz
 lc >I          [Enter inner loop.]sz
 [==
]P              [Print "==" and a newline.]sz
 li 1 + d si    [i += 1]sz
 lb >L          [Loop while b > i.]sz
]sL
0 d si         [i = 0]sz
lb >L          [Enter outer loop.]sz


with javascript_semantics
function matrix_mul(sequence a, sequence b)
    if length(a[1]) != length(b) then
        return 0
    end if
    sequence c = repeat(repeat(0,length(b[1])),length(a))
    for i=1 to length(a) do
        for j=1 to length(b[1]) do
            for k=1 to length(a[1]) do
                c[i][j] += a[i][k]*b[k][j]
            end for
        end for
    end for
    return c
end function

function pivotize(sequence m)
    integer n = length(m)
    sequence im = repeat(repeat(0,n),n)
    for i=1 to n do
        im[i][i] = 1
    end for
    for i=1 to n do
        atom mx = m[i][i]
        integer row = i
        for j=i to n do
            if m[j][i]>mx then
                mx = m[j][i]
                row = j
            end if
        end for
        if i!=row then
            {im[i],im[row]} = {im[row],im[i]}
        end if
    end for
    return im
end function

function lu(sequence a)
    integer n = length(a)
    sequence l = repeat(repeat(0,n),n),
             u = repeat(repeat(0,n),n),
             p = pivotize(a),
             a2 = matrix_mul(p,a)

    for j=1 to n do
        l[j][j] = 1.0
        for i=1 to j do
            atom sum1 = 0.0
            for k=1 to i do
                sum1 += u[k][j] * l[i][k]
            end for
            u[i][j] = a2[i][j] - sum1
        end for
        for i=j+1 to n do
            atom sum2 = 0.0
            for k=1 to j do
                sum2 += u[k][j] * l[i][k]
            end for
            l[i][j] = (a2[i][j] - sum2) / u[j][j]
        end for
    end for
    return {a, l, u, p}
end function

constant a = {{{1, 3, 5},
               {2, 4, 7},
               {1, 1, 0}},
              {{11, 9,24, 2},
               { 1, 5, 2, 6},
               { 3,17,18, 1},
               { 2, 5, 7, 1}}}
for i=1 to length(a) do
    ?"== a,l,u,p: =="
    pp(lu(a[i]),{pp_Nest,2,pp_Pause,0})
end for


PROCEDURE DivBy2() =
  VAR i: INTEGER := 1024;
  BEGIN
    WHILE i > 0 DO
      IO.PutInt(i);
      IO.Put("\n");
      i := i DIV 2;
    END;
  END DivBy2;


var i := 1024
while (i > 0):
    traceln(i)
    i //= 2


i = 1024;
while (i > 0)
  player:tell(i);
  i /= 2;
endwhile


var
  matrix: array[1..10,1..10] of Integer;
  row, col: Integer;
  broken: Boolean;
begin
  // Launch random number generator
  randomize;
  // Filling matrix with random numbers
  for row := 1 to 10 do
    for col := 1 to 10 do
      matrix[row, col] := Succ(Random(20));
  // Displaying values one by one, until at the end or reached number 20
  Broken := False;
  for row := 1 to 10 do
  begin
    for col := 1 to 10 do
    begin
      ShowMessage(IntToStr(matrix[row, col]));
      if matrix[row, col] = 20 then
      begin
        Broken := True;
        break;
      end;
    end;
    if Broken then break;
  end;
end;


(subscriptrange, fofl, size):                         /* 2 Nov. 2013 */
LU_Decomposition: procedure options (main);
   declare a1(3,3) float (18) initial ( 1,  3,  5,
                                        2,  4,  7,
                                        1,  1,  0);
   declare a2(4,4) float (18) initial (11,  9, 24, 2,
                                        1,  5,  2, 6,
                                        3, 17, 18, 1,
                                        2,  5,  7, 1);
   call check(a1);
   call check(a2);

/* In-situ decomposition */
LU: procedure(a, p);
   declare a(*,*) float (18);
   declare p(*)   fixed binary;
   declare (maximum, rtemp) float (18);
   declare (n, i, j, k, ii, temp) fixed binary;

   n = hbound(a,1);
   do i = 1 to n; p(i) = i; end;

   do k = 1 to n-1;

      maximum = 0; ii = k;
      do i = k to n;
         if maximum < abs(a(p(i),k)) then
            do; maximum = abs(a(p(i),k)); ii = i; end;
      end;
      if ii ^= k then do; temp = p(k); p(k) = p(ii); p(ii) = temp; end;

      do i = k+1 to n; a(p(i),k) = a(p(i),k) / a(p(k),k); end;

      do j = k+1 to n;
         do i = k+1 to n;
            a(p(i),j) = a(p(i),j) - a(p(i),k) * a(p(k),j);
         end;
      end;

   end;
end LU;

CHECK: procedure(a);
   declare a(*,*) float (18) nonassignable;

   declare aa(hbound(a,1), hbound(a,2)) float (18);
   declare  L(hbound(a,1), hbound(a,2)) float (18);
   declare  U(hbound(a,1), hbound(a,2)) float (18);
   declare (p(hbound(a,1), hbound(a,2)), ipiv(hbound(a,1)) ) fixed binary;
   declare pp(hbound(a,1), hbound(a,2)) fixed binary;
   declare (i, j, n, temp(hbound(a,1))) fixed binary;

   n = hbound(a,1);
   aa = A; /* work with a copy */
   P = 0; L = 0; U = 0;
   do i = 1 to n;
      p(i,i) = 1; L(i,i) = 1; /* convert permutation vector to a matrix */
   end;

   call LU(aa, ipiv);

   do i = 1 to n;
      do j = 1 to i-1; L(i,j) = aa(ipiv(i),j); end;
      do j = i to n;   U(i,j) = aa(ipiv(i),j); end;
   end;

   pp = p;
   do i = 1 to n;
      p(ipiv(i), *) = pp(i,*);
   end;

   put skip list ('A');
   put edit (A) (skip, (n) f(10,5));

   put skip list ('P');
   put edit (P) (skip, (n) f(11));

   put skip list ('L');
   put edit (L) (skip, (n) f(10,5));

   put skip list ('U');
   put edit (U) (skip, (n) f(10,5));

end CHECK;

end LU_Decomposition;


from pprint import pprint

def matrixMul(A, B):
    TB = zip(*B)
    return [[sum(ea*eb for ea,eb in zip(a,b)) for b in TB] for a in A]

def pivotize(m):
    """Creates the pivoting matrix for m."""
    n = len(m)
    ID = [[float(i == j) for i in xrange(n)] for j in xrange(n)]
    for j in xrange(n):
        row = max(xrange(j, n), key=lambda i: abs(m[i][j]))
        if j != row:
            ID[j], ID[row] = ID[row], ID[j]
    return ID

def lu(A):
    """Decomposes a nxn matrix A by PA=LU and returns L, U and P."""
    n = len(A)
    L = [[0.0] * n for i in xrange(n)]
    U = [[0.0] * n for i in xrange(n)]
    P = pivotize(A)
    A2 = matrixMul(P, A)
    for j in xrange(n):
        L[j][j] = 1.0
        for i in xrange(j+1):
            s1 = sum(U[k][j] * L[i][k] for k in xrange(i))
            U[i][j] = A2[i][j] - s1
        for i in xrange(j, n):
            s2 = sum(U[k][j] * L[i][k] for k in xrange(j))
            L[i][j] = (A2[i][j] - s2) / U[j][j]
    return (L, U, P)

a = [[1, 3, 5], [2, 4, 7], [1, 1, 0]]
for part in lu(a):
    pprint(part, width=19)
    print
print
b = [[11,9,24,2],[1,5,2,6],[3,17,18,1],[2,5,7,1]]
for part in lu(b):
    pprint(part)
    print


import morfa.io.print;

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


$n = 1024
while ($n > 0)
    println $n
    $n = $n/2
end while


let array = [[2, 12, 10, 4], [18, 11, 20, 2]]

for row in array {
    break when {
        for element in row {
            print("\(element)")
            if element == 20 {
                break true
            }
        }
    }
}
print("*Done")


def array := accum [] for i in 1..5 { _.with(accum [] for i in 1..5 { _.with(entropy.nextInt(20) + 1) }) }

escape done {
    for row in array {
        for x in row {
            print(`$x$\t`)
            if (x == 20) {
                done()
            }
        }
        println()
    }
}
println("done.")


mutable x = 1024;
while (x > 0)
{
    WriteLine($"$x");
    x /= 2;
}


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

  say
  say 'Loops/While'

  x_ = 1024
  loop while x_ > 0
    say x_.right(6)
    x_ = x_ % 2 -- integer division
    end


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


for (  [1, 3, 5], # Test Matrices
       [2, 4, 7],
       [1, 1, 0]
    ),
    (  [11,  9, 24,  2],
       [ 1,  5,  2,  6],
       [ 3, 17, 18,  1],
       [ 2,  5,  7,  1]
    )
    -> @test {
    say-it 'A Matrix', @test;
    say-it( $_[0], @($_[1]) ) for 'P Matrix', 'Aʼ Matrix', 'L Matrix', 'U Matrix' Z, lu @test;
}

sub lu (@a) {
    die unless @a.&is-square;
    my $n = +@a;
    my @P = pivotize @a;
    my @Aʼ = mmult @P, @a;
    my @L = matrix-ident $n;
    my @U = matrix-zero  $n;
    for ^$n -> $i {
        for ^$n -> $j {
            if $j >= $i {
                @U[$i][$j] =  @Aʼ[$i][$j] - [+] map { @U[$_][$j] * @L[$i][$_] }, ^$i
            } else {
                @L[$i][$j] = (@Aʼ[$i][$j] - [+] map { @U[$_][$j] * @L[$i][$_] }, ^$j) / @U[$j][$j];
            }
        }

    }
    return @P, @Aʼ, @L, @U;
}

sub pivotize (@m) {
    my $size = +@m;
    my @id = matrix-ident $size;
    for ^$size -> $i {
        my $max = @m[$i][$i];
        my $row = $i;
        for $i ..^ $size -> $j {
            if @m[$j][$i] > $max {
                $max = @m[$j][$i];
                $row = $j;
            }
        }
        if $row != $i {
            @id[$row, $i] = @id[$i, $row]
        }
    }
    @id
}

sub is-square (@m) { so @m == all @m[*] }

sub matrix-zero ($n, $m = $n) { map { [ flat 0 xx $n ] }, ^$m }

sub matrix-ident ($n) { map { [ flat 0 xx $_, 1, 0 xx $n - 1 - $_ ] }, ^$n }

sub mmult(@a,@b) {
    my @p;
    for ^@a X ^@b[0] -> ($r, $c) {
        @p[$r][$c] += @a[$r][$_] * @b[$_][$c] for ^@b;
    }
    @p
}

sub rat-int ($num) {
    return $num unless $num ~~ Rat;
    return $num.narrow if $num.narrow.WHAT ~~ Int;
    $num.nude.join: '/';
}

sub say-it ($message, @array) {
    say "\n$message";
    $_».&rat-int.fmt("%7s").say for @array;
}


var n: int = 1024
while n > 0:
  echo(n)
  n = n div 2


10 I=1024
20 IF I=0 THEN END
30 PRINT I
40 I=I/2
50 GOTO 20


PROCEDURE DivBy2*();
  VAR i: INTEGER;
BEGIN
  i := 1024;
  WHILE i > 0 DO
    Out.Int(i,0);
    Out.Ln;
    i := i DIV 2;
  END;
END DivBy2;


defmodule Loops do
  def nested do
    list = Enum.shuffle(1..20) |> Enum.chunk(5)
    IO.inspect list, char_lists: :as_lists
    try do
      nested(list)
    catch
      :find -> IO.puts "done"
    end
  end

  def nested(list) do
    Enum.each(list, fn row ->
      Enum.each(row, fn x ->
        IO.write "#{x} "
        if x == 20, do: throw(:find)
      end)
      IO.puts ""
    end)
  end
end

Loops.nested


-module( loops_nested ).

-export( [task/0] ).

task() ->
       Size = 20,
       Two_dimensional_array = [random_array(Size) || _X <- lists:seq(1, Size)],
       print_until_found( [], 20, Two_dimensional_array ).

print_until_found( [], N, [Row | T] ) -> print_until_found( print_until_found_row(N, Row), N, T );
print_until_found( _Found, _N, _Two_dimensional_array ) -> io:fwrite( "~n" ).

print_until_found_row( _N, [] ) -> [];
print_until_found_row( N, [N | T] ) -> [N | T];
print_until_found_row( N, [H | T] ) ->
        io:fwrite( "~p ", [H] ),
        print_until_found_row( N, T ).

random_array( Size ) -> [random:uniform(Size) || _X <- lists:seq(1, Size)].


/*REXX program creates a  matrix  from console input, performs/shows  LU  decomposition.*/
#= 0;    P.= 0;    PA.= 0;     L.= 0;     U.= 0  /*initialize some variables to zero.   */
parse arg x                                      /*obtain matrix elements from the C.L. */
                  call bldAMat;       call showMat 'A'    /*build and display A  matrix.*/
                  call bldPmat;       call showMat 'P'    /*  "    "     "    P     "   */
                  call multMat;       call showMat 'PA'   /*  "    "     "    PA    "   */
  do y=1  for N;  call bldUmat;       call bldLmat        /*build     U  and  L     "   */
  end   /*y*/
                  call showMat 'L';   call showMat 'U'    /*display   L  and  U     "   */
exit                                             /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
bldAMat: ?= words(x);  do N=1  for ?  until N**2>=?                /*find matrix size.  */
                       end  /*N*/
         if N**2\==?  then do;  say '***error*** wrong # of elements entered:'  ?;  exit 9
                           end
                  do    r=1  for N                                 /*build   A   matrix.*/
                     do c=1  for N;        #= # + 1;     _= word(x, #);        A.r.c= _
                     if \datatype(_, 'N')  then call er "element isn't numeric: "  _
                     end   /*c*/
                  end      /*r*/;          return
/*──────────────────────────────────────────────────────────────────────────────────────*/
bldLmat:          do    r=1  for N                                 /*build lower matrix.*/
                     do c=1  for N;        if r==c  then do;   L.r.c= 1;   iterate;    end
                     if c\==y | r==c | c>r  then iterate
                     _= PA.r.c
                                           do k=1  for c-1;    _= _   -   U.k.c * L.r.k
                                           end  /*k*/
                     L.r.c= _ / U.c.c
                     end   /*c*/
                  end      /*r*/;          return
/*──────────────────────────────────────────────────────────────────────────────────────*/
bldPmat: c= N;    do r=N  by -1  for N;    P.r.c= 1;     c= c + 1  /*build perm. matrix.*/
                  if c>N  then c= N%2;     if c==N  then c= 1
                  end   /*r*/;             return
/*──────────────────────────────────────────────────────────────────────────────────────*/
bldUmat:          do    r=1  for N;        if r\==y  then iterate  /*build upper matrix.*/
                     do c=1  for N;        if c<r    then iterate
                     _= PA.r.c
                                           do k=1  for r-1;     _= _   -   U.k.c * L.r.k
                                           end   /*k*/
                     U.r.c= _ / 1
                     end   /*c*/
                  end      /*r*/;          return
/*──────────────────────────────────────────────────────────────────────────────────────*/
multMat:          do      i=1  for N                 /*multiply matrix  P and A  ──► PA */
                     do   j=1  for N
                       do k=1  for N;      pa.i.j=  (pa.i.j   +   p.i.k * a.k.j)    /    1
                       end   /*k*/
                     end     /*j*/                   /*÷ by one does normalization [↑]. */
                  end        /*i*/;        return
/*──────────────────────────────────────────────────────────────────────────────────────*/
showMat: parse arg mat,rows,cols;   say;   rows= word(rows N,1);   cols= word(cols rows,1)
         w= 0;    do    r=1  for rows
                     do c=1  for cols;     w= max(w,  length( value( mat'.'r"."c ) ) )
                     end  /*c*/
                  end     /*r*/
         say center(mat  'matrix',  cols * (w + 1) + 7,  "─")      /*display the header.*/
                  do    r=1  for rows;     _=
                     do c=1  for cols;     _= _ right( value(mat'.'r"."c),   w + 1)
                     end   /*c*/
                  say _
                  end      /*r*/;       return


import io

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


let n = ref 1024;;
while !n > 0 do
  Printf.printf "%d\n" !n;
  n := !n / 2
done;;


DIM A%[10,10]                      ! in declaration part
.............
PRINT(CHR$(12);) !CLS
FOR ROW=1 TO 10 DO
   FOR COL=1 TO 10 DO
     A%[ROW,COL]=INT(RND(1)*20)+1  ! INT and RND are ERRE predeclared functions
                                   ! RND generates random numbers between 0 and 1
   END FOR
END FOR

FOR ROW=1 TO 10 DO
   FOR COL=1 TO 10 DO
     PRINT(A%[ROW,COL])
     EXIT IF A%[ROW,COL]=20
   END FOR
   EXIT IF A%[ROW,COL]=20  ! EXIT breaks the current loop only: you must repeat it,
                           ! use a boolean variable or a GOTO label statement
END FOR


sequence a
a = rand(repeat(repeat(20, 10), 10))

integer wantExit
wantExit = 0

for i = 1 to 10 do
    for j = 1 to 10 do
	printf(1, "%g ", {a[i][j]})
	if a[i][j] = 20 then
	    wantExit = 1
	    exit
	end if
    end for
    if wantExit then
	exit
    end if
end for


require 'matrix'

class Matrix
  def lu_decomposition
    p = get_pivot
    tmp = p * self
    u = Matrix.zero(row_size).to_a
    l = Matrix.identity(row_size).to_a
    (0 ... row_size).each do |i|
      (0 ... row_size).each do |j|
        if j >= i
          # upper
          u[i][j] = tmp[i,j] - (0 ... i).inject(0.0) {|sum, k| sum + u[k][j] * l[i][k]}
        else
          # lower
          l[i][j] = (tmp[i,j] - (0 ... j).inject(0.0) {|sum, k| sum + u[k][j] * l[i][k]}) / u[j][j]
        end
      end
    end
    [ Matrix[*l], Matrix[*u], p ]
  end

  def get_pivot
    raise ArgumentError, "must be square" unless square?
    id = Matrix.identity(row_size).to_a
    (0 ... row_size).each do |i|
      max = self[i,i]
      row = i
      (i ... row_size).each do |j|
        if self[j,i] > max
          max = self[j,i]
          row = j
        end
      end
      id[i], id[row] = id[row], id[i]
    end
    Matrix[*id]
  end

  def pretty_print(format, head=nil)
    puts head if head
    puts each_slice(column_size).map{|row| format*row_size % row}
  end
end

puts "Example 1:"
a = Matrix[[1,  3,  5],
           [2,  4,  7],
           [1,  1,  0]]
a.pretty_print(" %2d", "A")
l, u, p = a.lu_decomposition
l.pretty_print(" %8.5f", "L")
u.pretty_print(" %8.5f", "U")
p.pretty_print(" %d",    "P")

puts "\nExample 2:"
a = Matrix[[11, 9,24,2],
           [ 1, 5, 2,6],
           [ 3,17,18,1],
           [ 2, 5, 7,1]]
a.pretty_print(" %2d", "A")
l, u, p = a.lu_decomposition
l.pretty_print(" %8.5f", "L")
u.pretty_print(" %8.5f", "U")
p.pretty_print(" %d",    "P")


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


main: func {
  value := 1024
  while (value > 0) {
    value toString() println()
    value /= 2
  }
}


//Nigel Galloway: November 10th., 2017
let n = System.Random()
let g = Array2D.init 8 8 (fun _ _ -> 1+n.Next()%20)
Array2D.iter (fun n -> printf "%d " n) g; printfn ""
g |> Seq.cast<int> |> Seq.takeWhile(fun n->n<20) |> Seq.iter (fun n -> printf "%d " n)


USING: io kernel math.ranges prettyprint random sequences ;

10 [ 20 [ 20 [1,b] random ] replicate ] replicate    ! make a table of random values
[ [ dup pprint bl 20 = ] find nl drop ] find 2drop   ! print values until 20 is found


#![allow(non_snake_case)]
use ndarray::{Array, Axis, Array2, arr2, Zip, NdFloat, s};

fn main() {
    println!("Example 1:");
    let A: Array2<f64> = arr2(&[
        [1.0, 3.0, 5.0],
        [2.0, 4.0, 7.0],
        [1.0, 1.0, 0.0],
    ]);
    println!("A \n {}", A);
    let (L, U, P) = lu_decomp(A);
    println!("L \n {}", L);
    println!("U \n {}", U);
    println!("P \n {}", P);

    println!("\nExample 2:");
    let A: Array2<f64> = arr2(&[
        [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],
    ]);
    println!("A \n {}", A);
    let (L, U, P) = lu_decomp(A);
    println!("L \n {}", L);
    println!("U \n {}", U);
    println!("P \n {}", P);
}

fn pivot<T>(A: &Array2<T>) -> Array2<T>
where T: NdFloat {
    let matrix_dimension = A.rows();
    let mut P: Array2<T> = Array::eye(matrix_dimension);
    for (i, column) in A.axis_iter(Axis(1)).enumerate() {
        // find idx of maximum value in column i
        let mut max_pos = i;
        for j in i..matrix_dimension {
            if column[max_pos].abs() < column[j].abs() {
                max_pos = j;
            }
        }
        // swap rows of P if necessary
        if max_pos != i {
            swap_rows(&mut P, i, max_pos);
        }
    }
    P
}

fn swap_rows<T>(A: &mut Array2<T>, idx_row1: usize, idx_row2: usize)
where T: NdFloat {
    // to swap rows, get two ArrayViewMuts for the corresponding rows
    // and apply swap elementwise using ndarray::Zip
    let (.., mut matrix_rest) = A.view_mut().split_at(Axis(0), idx_row1);
    let (row0, mut matrix_rest) = matrix_rest.view_mut().split_at(Axis(0), 1);
    let (_matrix_helper, mut matrix_rest) = matrix_rest.view_mut().split_at(Axis(0), idx_row2 - idx_row1 - 1);
    let (row1, ..) = matrix_rest.view_mut().split_at(Axis(0), 1);
    Zip::from(row0).and(row1).apply(std::mem::swap);
}

fn lu_decomp<T>(A: Array2<T>) -> (Array2<T>, Array2<T>, Array2<T>)
where T: NdFloat {

    let matrix_dimension = A.rows();
    assert_eq!(matrix_dimension, A.cols(), "Tried LU decomposition with a non-square matrix.");
    let P = pivot(&A);
    let pivotized_A = P.dot(&A);

    let mut L: Array2<T> = Array::eye(matrix_dimension);
    let mut U: Array2<T> = Array::zeros((matrix_dimension, matrix_dimension));
    for idx_col in 0..matrix_dimension {
        // fill U
        for idx_row in 0..idx_col+1 {
            U[[idx_row, idx_col]] = pivotized_A[[idx_row, idx_col]] -
                U.slice(s![0..idx_row,idx_col]).dot(&L.slice(s![idx_row,0..idx_row]));
        }
        // fill L
        for idx_row in idx_col+1..matrix_dimension {
            L[[idx_row, idx_col]] = (pivotized_A[[idx_row, idx_col]] -
                U.slice(s![0..idx_col,idx_col]).dot(&L.slice(s![idx_row,0..idx_col]))) /
                U[[idx_col, idx_col]];
        }
    }
    (L, U, P)
}


func is_square(m) { m.all { .len == m.len } }
func matrix_zero(n, m=n) { m.of { n.of(0) } }
func matrix_ident(n) { n.of {|i| n.of {|j| i==j ? 1 : 0 } } }

func pivotize(m) {
    var size = m.len
    var id = matrix_ident(size)
    for i (^size) {
        var max = m[i][i]
        var row = i
        for j (i .. size-1) {
            if (m[j][i] > max) {
                max = m[j][i]
                row = j
            }
        }
        if (row != i) {
            id.swap(row, i)
        }
    }
    return id
}

func mmult(a, b) {
    var p = []
    for r,c (^a ~X ^b[0]) {
        for i (^b) {
            p[r][c] := 0 += (a[r][i] * b[i][c])
        }
    }
    return p
}

func lu(a) {
    is_square(a) || die "Defined only for square matrices!";
    var n = a.len
    var P = pivotize(a)
    var Aʼ = mmult(P, a)
    var L = matrix_ident(n)
    var U = matrix_zero(n)
    for i,j (^n ~X ^n) {
        if (j >= i) {
            U[i][j] = (Aʼ[i][j] - ({ U[_][j] * L[i][_] }.map(^i).sum))
        } else {
            L[i][j] = (Aʼ[i][j] - ({ U[_][j] * L[i][_] }.map(^j).sum))/U[j][j]
        }
    }
    return [P, Aʼ, L, U]
}

func say_it(message, array) {
    say "\n#{message}"
    array.each { |row|
        say row.map{"%7s" % .as_rat}.join(' ')
    }
}

var t = [[
   %n(1 3 5),
   %n(2 4 7),
   %n(1 1 0),
],[
   %n(11  9 24  2),
   %n( 1  5  2  6),
   %n( 3 17 18  1),
   %n( 2  5  7  1),
]]

for test (t) {
    say_it('A Matrix', test);
    for a,b (['P Matrix', 'Aʼ Matrix', 'L Matrix', 'U Matrix'] ~Z lu(test)) {
        say_it(a, b)
    }
}


for I in 1024; I>0; I div 2 do
   {Show I}
end


fun half(a) type integer->integer a.divide(2)
1024.trans(func:half).gt(0) nl


dim x%:rem an integer

x%=1024

while x%>0

     print x%
     x%=x%/2

end_while

rem output starts with 1024 and ends with 1.

terminate


class Main
{
  public static Void main ()
  {
    rows := 10
    cols := 10
    // create and fill an array of given size with random numbers
    Int[][] array := [,]
    rows.times
    {
      row := [,]
      cols.times { row.add(Int.random(1..20)) }
      array.add (row)
    }
    // now do the search
    try
    {
      for (i := 0; i < rows; i++)
      {
        for (j := 0; j < cols; j++)
        {
          echo ("now at ($i, $j) which is ${array[i][j]}")
          if (array[i][j] == 20) throw (Err("found it"))
        }
      }
    }
    catch (Err e)
    {
      echo (e.msg)
      return // and finish
    }
    echo ("No 20")
  }
}


include random.fs

10 constant X
10 constant Y

: ,randoms ( range n -- ) 0 do dup random 1+ , loop drop ;

create 2darray 20 X Y * ,randoms

: main
  Y 0 do
    cr
    X 0 do
      j X * i + cells 2darray + @
      dup .
      20 = if unloop unloop exit then
    loop
  loop ;


package require Tcl 8.5
namespace eval matrix {
    namespace path {::tcl::mathfunc ::tcl::mathop}

    # Construct an identity matrix of the given size
    proc identity {order} {
	set m [lrepeat $order [lrepeat $order 0]]
	for {set i 0} {$i < $order} {incr i} {
	    lset m $i $i 1
	}
	return $m
    }

    # Produce the pivot matrix for a given matrix
    proc pivotize {matrix} {
	set n [llength $matrix]
	set p [identity $n]
	for {set j 0} {$j < $n} {incr j} {
	    set max [lindex $matrix $j $j]
	    set row $j
	    for {set i $j} {$i < $n} {incr i} {
		if {[lindex $matrix $i $j] > $max} {
		    set max [lindex $matrix $i $j]
		    set row $i
		}
	    }
	    if {$j != $row} {
		# Row swap inlined; too trivial to have separate procedure
		set tmp [lindex $p $j]
		lset p $j [lindex $p $row]
		lset p $row $tmp
	    }
	}
	return $p
    }

    # Decompose a square matrix A by PA=LU and return L, U and P
    proc luDecompose {A} {
	set n [llength $A]
	set L [lrepeat $n [lrepeat $n 0]]
	set U $L
	set P [pivotize $A]
	set A [multiply $P $A]

	for {set j 0} {$j < $n} {incr j} {
	    lset L $j $j 1
	    for {set i 0} {$i <= $j} {incr i} {
		lset U $i $j [- [lindex $A $i $j] [SumMul $L $U $i $j $i]]
	    }
	    for {set i $j} {$i < $n} {incr i} {
		set sum [SumMul $L $U $i $j $j]
		lset L $i $j [/ [- [lindex $A $i $j] $sum] [lindex $U $j $j]]
	    }
	}

	return [list $L $U $P]
    }

    # Helper that makes inner loop nicer; multiplies column and row,
    # possibly partially...
    proc SumMul {A B i j kmax} {
	set s 0.0
	for {set k 0} {$k < $kmax} {incr k} {
	    set s [+ $s [* [lindex $A $i $k] [lindex $B $k $j]]]
	}
	return $s
    }
}


program divby2(output);

var
  i: integer;

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


Local string &CRLF;
Local number &LoopNumber;
&LoopNumber = 1024;
&CRLF = Char(10) | Char(13);

While &LoopNumber > 0;
 WinMessage(&LoopNumber | &CRLF);
 &LoopNumber = &LoopNumber / 2;
End-While;


      PROGRAM LOOPNESTED
        INTEGER A, I, J, RNDINT

C       Build a two-dimensional twenty-by-twenty array.
        DIMENSION A(20,20)

C       It doesn't matter what number you put here.
        CALL SDRAND(123)

C       Fill the array with random numbers.
        DO 20 I = 1, 20
          DO 10 J = 1, 20
            A(I, J) = RNDINT(1, 20)
   10     CONTINUE
   20   CONTINUE

C       Print the numbers.
        DO 40 I = 1, 20
          DO 30 J = 1, 20
            WRITE (*,5000) I, J, A(I, J)

C           If this number is twenty, break out of both loops.
            IF (A(I, J) .EQ. 20) GOTO 50
   30     CONTINUE
   40   CONTINUE

C       If we had gone to 40, the DO loop would have continued. You can
C       label STOP instead of adding another CONTINUE, but it is good
C       form to only label CONTINUE statements as much as possible.
   50   CONTINUE
        STOP

C       Print the value so that it looks like one of those C arrays that
C       makes everybody so comfortable.
 5000   FORMAT('A[', I2, '][', I2, '] is ', I2)
      END

C FORTRAN 77 does not come with a random number generator, but it is
C easy enough to type "fortran 77 random number generator" into your
C preferred search engine and to copy and paste what you find.
C The following code is a slightly-modified version of:
C
C     http://www.tat.physik.uni-tuebingen.de/
C         ~kley/lehre/ftn77/tutorial/subprograms.html
      SUBROUTINE SDRAND (IRSEED)
        COMMON  /SEED/ UTSEED, IRFRST
        UTSEED = IRSEED
        IRFRST = 0
        RETURN
      END
      INTEGER FUNCTION RNDINT (IFROM, ITO)
        INTEGER IFROM, ITO
        PARAMETER (MPLIER=16807, MODLUS=2147483647,                     &
     &              MOBYMP=127773, MOMDMP=2836)
        COMMON  /SEED/ UTSEED, IRFRST
        INTEGER HVLUE, LVLUE, TESTV, NEXTN
        SAVE    NEXTN
        IF (IRFRST .EQ. 0) THEN
          NEXTN = UTSEED
          IRFRST = 1
        ENDIF
        HVLUE = NEXTN / MOBYMP
        LVLUE = MOD(NEXTN, MOBYMP)
        TESTV = MPLIER*LVLUE - MOMDMP*HVLUE
        IF (TESTV .GT. 0) THEN
          NEXTN = TESTV
        ELSE
          NEXTN = TESTV + MODLUS
        ENDIF
        IF (NEXTN .GE. 0) THEN
          RNDINT = MOD(MOD(NEXTN, MODLUS), ITO - IFROM + 1) + IFROM
        ELSE
          RNDINT = MOD(MOD(NEXTN, MODLUS), ITO - IFROM + 1) + ITO + 1
        ENDIF
        RETURN
      END


Option Base 1
Private Function pivotize(m As Variant) As Variant
    Dim n As Integer: n = UBound(m)
    Dim im() As Double
    ReDim im(n, n)
    For i = 1 To n
        For j = 1 To n
            im(i, j) = 0
        Next j
        im(i, i) = 1
    Next i
    For i = 1 To n
        mx = Abs(m(i, i))
        row_ = i
        For j = i To n
            If Abs(m(j, i)) > mx Then
                mx = Abs(m(j, i))
                row_ = j
            End If
        Next j
        If i <> Row Then
            For j = 1 To n
                tmp = im(i, j)
                im(i, j) = im(row_, j)
                im(row_, j) = tmp
            Next j
        End If
    Next i
    pivotize = im
End Function

Private Function lu(a As Variant) As Variant
    Dim n As Integer: n = UBound(a)
    Dim l() As Double
    ReDim l(n, n)
    For i = 1 To n
        For j = 1 To n
            l(i, j) = 0
        Next j
    Next i
    u = l
    p = pivotize(a)
    a2 = WorksheetFunction.MMult(p, a)
    For j = 1 To n
        l(j, j) = 1#
        For i = 1 To j
            sum1 = 0#
            For k = 1 To i
                sum1 = sum1 + u(k, j) * l(i, k)
            Next k
            u(i, j) = a2(i, j) - sum1
        Next i
        For i = j + 1 To n
            sum2 = 0#
            For k = 1 To j
                sum2 = sum2 + u(k, j) * l(i, k)
            Next k
            l(i, j) = (a2(i, j) - sum2) / u(j, j)
        Next i
    Next j
    Dim res(4) As Variant
    res(1) = a
    res(2) = l
    res(3) = u
    res(4) = p
    lu = res
End Function

Public Sub main()

    a = [{1, 3, 5; 2, 4, 7; 1, 1, 0}]
    Debug.Print "== a,l,u,p: =="
    result = lu(a)
    For i = 1 To 4
        For j = 1 To UBound(result(1))
            For k = 1 To UBound(result(1), 2)
                Debug.Print result(i)(j, k),
            Next k
            Debug.Print
        Next j
        Debug.Print
    Next i
    a = [{11, 9,24, 2; 1, 5, 2, 6; 3,17,18, 1; 2, 5, 7, 1}]
    Debug.Print "== a,l,u,p: =="
    result = lu(a)
    For i = 1 To 4
        For j = 1 To UBound(result(1))
            For k = 1 To UBound(result(1), 2)
                Debug.Print Format(result(i)(j, k), "0.#####"),
            Next k
            Debug.Print
        Next j
        Debug.Print
    Next i
End Sub


integer i = 1024
while i!=0 do
    ?i
    i = floor(i/2)  -- (see note)
end while


' FB 1.05.0 Win64

Randomize
Dim a(1 To 20, 1 To 20) As Integer
For i As Integer = 1 To 20
  For j As Integer = 1 To 20
    a(i, j) = Int(Rnd * 20) + 1
  Next j
Next i

For i As Integer = 1 To 20
  For j As Integer = 1 To 20
    Print Using "##"; a(i, j);
    Print " ";
    If a(i, j) = 20 Then Exit For, For '' Exits both for loops
  Next j
  Print
Next i

Print
Print "Press any key to quit"
Sleep


array = new array[[10,10], {|x,y| random[1,20]}]

println["array is:\n" + formatTable[array, "right"] + "\n"]

[rows,cols] = array.dimensions[]

ROW:
for r = 0 to rows-1
   for c = 0 to cols-1
   {
      print[[email protected]@c + " " ]
      if [email protected]@c == 20
         break ROW
   }


import "/matrix" for Matrix
import "/fmt" for Fmt

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

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

for (array in arrays) {
    var m = Matrix.new(array)
    System.print("A\n")
    Fmt.mprint(m, 2, 0)
    System.print("\nL\n")
    var lup = m.lup
    Fmt.mprint(lup[0], 8, 5)
    System.print("\nU\n")
    Fmt.mprint(lup[1], 8, 5)
    System.print("\nP\n")
    Fmt.mprint(lup[2], 2, 0)
    System.print()
}


go =>
 N = 1024,
 while (N > 0)
   println(N),
   N := N // 2
 end.


(let N 1024
   (while (gt0 N)
      (println N)
      (setq N (/ N 2)) ) )


declare i fixed binary initial (1024);

do while (i>0);
   put skip list (i);
   i = i / 2;
end;


Public Sub Main()
Dim siArray As New Short[5, 5]
Dim siCount0, siCount1 As Short
Dim bBreak As Boolean

For siCount0 = 0 To 4
  For siCount1 = 0 To 4
    siArray[siCount0, siCount1] = Rand(1, 20)
    siArray[siCount0, siCount1] = Rand(1, 20)
  Next
Next

For siCount0 = 0 To 4
  For siCount1 = 0 To 4
    If siArray[siCount0, siCount1] = 20 Then
      bBreak = True
      Break
    Endif
  Next
  If bBreak Then Break
Next

Print "Row " & Str(siCount0) & " column " & Str(siCount1) & " = 20"

End


var [const] GSL=Import("zklGSL");	// libGSL (GNU Scientific Library)
fcn luTask(A){
   A.LUDecompose();	//  in place, contains L & U
   L:=A.copy().lowerTriangle().setDiagonal(0,0,1);
   U:=A.copy().upperTriangle();
   return(L,U);
}

A:=GSL.Matrix(3,3).set(1,3,5,  2,4,7,   1,1,0);  // example 1
L,U:=luTask(A);
println("L:\n",L.format(),"\nU:\n",U.format());

A:=GSL.Matrix(4,4).set(11.0,  9.0, 24.0, 2.0,	// example 2
			1.0,  5.0,  2.0, 6.0,
			3.0, 17.0, 18.0, 1.0,
			2.0,  5.0,  7.0, 1.0);
L,U:=luTask(A);
println("L:\n",L.format(8,4),"\nU:\n",U.format(8,4));


SET serveroutput ON
DECLARE
  n NUMBER := 1024;
BEGIN
  WHILE n > 0 LOOP
    DBMS_OUTPUT.put_line(n);
    n := TRUNC(n / 2);
  END LOOP;
END;
/


To run:
Start up.
Show the halvings of 1024.
Wait for the escape key.
Shut down.

To show the halvings of a number:
If the number is 0, exit.
Convert the number to a string.
Write the string to the console.
Divide the number by 2.
Repeat.


lvars i = 1024;
while i > 0 do
    printf(i, '%p\n');
    i div 2 -> i;
endwhile;


# You can't break an outer loop unless you return from the whole function.
n := 40;
a := List([1 .. n], i -> List([1 .. n], j -> Random(1, 20)));;

Find := function(a, x)
    local i, j, n;
    n := Length(a);
    for i in [1 .. n] do
        for j in [1 .. n] do
            if a[i][j] = x then
                return [i, j];
            fi;
        od;
    od;
    return fail;
end;

Find(a, 20);


package main

import (
    "fmt"
    "math/rand"
    "time"
)

func main() {
    rand.Seed(time.Now().UnixNano())

    values := make([][]int, 10)
    for i := range values {
        values[i] = make([]int, 10)
        for j := range values[i] {
            values[i][j] = rand.Intn(20) + 1
        }
    }

outerLoop:
    for i, row := range values {
        fmt.Printf("%3d)", i)
        for _, value := range row {
            fmt.Printf(" %3d", value)
            if value == 20 {
                break outerLoop
            }
        }
        fmt.Printf("\n")
    }
    fmt.Printf("\n")
}


1024
{
    dup 0 le     % check whether still greater than 0
    { pop exit } % if not, exit the loop
    if
    dup =        % print the number
    2 idiv       % divide by two
}
loop


while(0) :- !.
while(X) :-
    writeln(X),
    X1 is X // 2,
    while(X1).


If OpenConsole()

  x.i = 1024
  While x > 0
    PrintN(Str(x))
    x / 2
  Wend

  Print(#CRLF$ + #CRLF$ + "Press ENTER to exit")
  Input()
  CloseConsole()
EndIf


final random = new Random()
def a = []
(0..<10).each {
    def row = []
    (0..<10).each {
        row << (random.nextInt(20) + 1)
    }
    a << row
}

a.each { println it }
println ()

Outer:
for (i in (0..<a.size())) {
    for (j in (0..<a[i].size())) {
        if (a[i][j] == 20){
            println ([i:i, j:j])
            break Outer
        }
    }
}


F is_prime(n)
   L(x) (2, 3)
      I n % x == 0
         R n == x
   Int64 d = 5
   L d * d <= n
      L(x) (2, 4)
         I n % d == 0
            R 0B
         d += x
   R 1B

Int64 i = 42
V n = 0
L n < 42
   I is_prime(i)
      n++
      print(‘n = #2 #16’.format(n, i))
      i += i - 1
   i++


L(i) 1..10
   print(i, end' ‘’)
   I !L.last_iteration
      print(‘, ’, end' ‘’)


n = 1024
while n > 0:
    print n
    n //= 2


Dim n As Integer
n = 1024
While n > 0
    Print n
    n = n \ 2
Wend


1024
[ dup 0 > while
  dup echo cr 2 /
  again ]
drop


*        Loops/For with a specified step     12/08/2015
LOOPFORS CSECT
         USING  LOOPFORS,R12
         LR     R12,R15
*     == Algol style ================ test at the beginning
         LA     R3,BUF             idx=0
         LA     R5,0               from 5 (from-step=0)
         LA     R6,5               step 5
         LA     R7,25              to 25
LOOPI    BXH    R5,R6,ELOOPI       for i=5 to 25 step 5
         XDECO  R5,XDEC              edit i
         MVC    0(4,R3),XDEC+8       output i
         LA     R3,4(R3)             idx=idx+4
         B      LOOPI              next i
ELOOPI   XPRNT  BUF,80             print buffer
         BR     R14
BUF      DC     CL80' '            buffer
XDEC     DS     CL12               temp for edit
         YREGS
         END    LOOPFORS


define ArrayPointerLo $00   ;define some helpful labels.
define ArrayPointerHi $01
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
setArray:      ;Easy6502 doesn't let us define arbitrary bytes so the best option is to fill the range at runtime.
lda #$10
ldx #0
loop_setArray:
sta $1200,x
clc
adc #$10
inx
cpx #$08
bcc loop_setArray
; stores this sequence of hex values starting at $1200: $10 $20 $30 $40 $50 $60 $70 $80

ClearMem:      ;clear $D000-$D0FF
lda #0
ldx #0
loop_clearMem:
sta $D000,x
inx
bne loop_clearMem
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; end of prep work, the real code begins here.

lda #$12              ;high byte of array address
sta ArrayPointerHi
lda #$00              ;low byte of array address
sta ArrayPointerLo    ;these are used to look up the array rather than hard-code it in.

ldx #$0E              ;the loop counter, gets decremented twice per iteration to skip the odd addresses.
ldy #7                ;the index into the source array.

;on the 6502 looping backwards is almost always faster.

loop_fill:
lda (ArrayPointerLo),y ;loads from the array's base address, plus Y
sta $D000,x            ;store at $D000+X
dey                    ;decrement array index
dex
dex                    ;decrement destination index twice
bpl loop_fill          ;if destination index equals #$FF, we are done.

brk                    ;end of program


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

/*******************************************/
/* Constantes file                         */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"

.equ MAXI,   20
/*********************************/
/* Initialized data              */
/*********************************/
.data
szMessResult:  .asciz "Counter =  @ \n"      // message result

/*********************************/
/* UnInitialized data            */
/*********************************/
.bss
sZoneConv:             .skip 24
/*********************************/
/*  code section                 */
/*********************************/
.text
.global main
main:                           // entry of program
    mov x4,0                    // init counter
1:                              // begin loop
    mov x0,x4
    ldr x1,qAdrsZoneConv        // display value
    bl conversion10             // call function with 2 parameter (x0,x1)
    ldr x0,qAdrszMessResult
    ldr x1,qAdrsZoneConv
    bl strInsertAtCharInc       // insert result at first @ character
    bl affichageMess            // display message
    add x4,x4,2                 // increment counter by 2
    cmp x4,MAXI                 //
    ble 1b                      // loop

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
/********************************************************/
/*        File Include fonctions                        */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"


import Data.List
breakIncl :: (a -> Bool) -> [a] -> [a]
breakIncl p =  uncurry ((. take 1). (++)). break p

taskLLB k = map (breakIncl (==k)). breakIncl (k `elem`)


REAL :: n=20, array(n,n)

array = NINT( RAN(10,10) )

DO row = 1, n
  DO col = 1, n
    WRITE(Name) row, col, array(row,col)
    IF( array(row, col) == 20 ) GOTO 99
  ENDDO
ENDDO

99 END


*        Loops/Increment loop index within loop body - 16/07/2018
LOOPILWB PROLOG
         SR     R6,R6              i=0
         ZAP    N,=P'42'           n=42
       DO WHILE=(C,R6,LT,IMAX)     do while(i<imax)
         BAL    R14,ISPRIME          call isprime(n)
       IF C,R0,EQ,=F'1' THEN         if n is prime then
         LA     R6,1(R6)               i=i+1
         XDECO  R6,XDEC                edit i
         MVC    PG+2(2),XDEC+10        output i
         MVC    ZN,EM                  load edit mask
         ED     ZN,N                   edit n
         MVC    PG+7(L'ZN),ZN          output n
         XPRNT  PG,L'PG                print buffer
         ZAP    WP,N                   n
         AP     WP,N                   +n
         SP     WP,=P'1'               +1
         ZAP    N,WP                   n=n+n-1
       ENDIF    ,                    endif
         ZAP    WP,N                 n
         AP     WP,=P'1'             +1
         ZAP    N,WP                 n=n+1
       ENDDO    ,                  enddo
         EPILOG
ISPRIME  EQU    *                  isprime(n) -----------------------
         CP     N,=P'2'            if n=2
         BE     RETURN1            then return(1)
         CP     N,=P'3'            if n=3
         BE     RETURN1            then return(1)
         ZAP    WDP,N              n
         DP     WDP,=PL8'2'        /2
         CP     WDP+8(8),=P'0'     if mod(n,2)=0
         BE     RETURN0            then return(0)
         ZAP    WDP,N              n
         DP     WDP,=PL8'3'        /3
         CP     WDP+8(8),=P'0'     if mod(n,3)=0
         BE     RETURN0            then return(0)
         ZAP    J,=P'5'            j=5
LWHILE   ZAP    WP,J               j
         MP     WP,J               *j
         CP     WP,N               while(j*j<=n)
         BH     EWHILE             ~
         ZAP    WDP,N                n
         DP     WDP,J                /j
         CP     WDP+8(8),=P'0'       if mod(n,j)=0
         BE     RETURN0              then return(0)
         ZAP    WP,J                 j
         AP     WP,=P'2'             +2
         ZAP    WDP,N                n
         DP     WDP,WP               n/(j+2)
         CP     WDP+8(8),=P'0'       if mod(n,j+2)=0
         BE     RETURN0              then return(0)
         ZAP    WP,J                 j
         AP     WP,=P'6'             +6
         ZAP    J,WP                 j=j+6
         B      LWHILE             loopwhile
EWHILE   B      RETURN1            return(1)
RETURN0  LA     R0,0               rc=0
         B      RETURNX
RETURN1  LA     R0,1               rc=1
RETURNX  BR     R14                return to caller -----------------
IMAX     DC     F'42'              limit
EM       DC     XL20'402020206B2020206B2020206B2020206B202120'  mask
N        DS     PL8                n
J        DS     PL8                j
PG       DC     CL80'i=00 :  000,000,000,000,000'   buffer
XDEC     DS     CL12               temp for XDECO
WP       DS     PL8                temp for AP,SP,MP
WDP      DS     PL16               temp for DP
CW       DS     CL16               temp for UNPK
ZN       DS     CL20
         REGEQU
         END    LOOPILWB


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

/*******************************************/
/* Constantes file                         */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"

/*********************************/
/* Initialized data              */
/*********************************/
.data
szMessOverflow:     .asciz "Error: overflow !!!!"
sMessResult:        .asciz "Index  : @ Value  : @ \n"
szCarriageReturn:   .asciz "\n"

/*********************************/
/* UnInitialized data            */
/*********************************/
.bss
sZoneConv:                .skip 24
/*********************************/
/*  code section                 */
/*********************************/
.text
.global main
main:                             // entry of program
    mov x20,0                     // counter
    mov x21,42                    // start index
1:                                // begin loop
    mov x0,x21
    bl isPrime                    // prime ?
    bcs 100f                      // error overflow ?
    cbnz x0,2f                    // is prime ?
    add x21,x21,1                 // no -> increment index
    b 1b                          // and loop
2:                                // display index and prime
    add x20,x20,1                 // increment counter
    mov x0,x20
    ldr x1,qAdrsZoneConv          // conversion index
    bl conversion10
    ldr x0,qAdrsMessResult
    ldr x1,qAdrsZoneConv
    bl strInsertAtCharInc         // insert result at first @ character
    mov x10,x0
    mov x0,x21                    // conversion value
    ldr x1,qAdrsZoneConv
    bl conversion10               // decimal conversion  ascii
    mov x0,x10
    ldr x1,qAdrsZoneConv
    bl strInsertAtCharInc         // insert result at second @ character
    bl affichageMess

    add x21,x21,x21
    cmp x20,42                    // end ?
    blt 1b                        // no loop

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
qAdrszCarriageReturn:     .quad szCarriageReturn
qAdrsMessResult:          .quad sMessResult
/***************************************************/
/*   Verification si un nombre est premier         */
/***************************************************/
/* x0 contient le nombre à verifier */
/* x0 retourne 1 si premier  0 sinon */
isPrime:
    stp x1,lr,[sp,-16]!        // save  registres
    stp x2,x3,[sp,-16]!        // save  registres
    mov x2,x0
    sub x1,x0,#1
    cmp x2,0
    beq 99f                    // retourne zéro
    cmp x2,2                   // pour 1 et 2 retourne 1
    ble 2f
    mov x0,#2
    bl moduloPuR64
    bcs 100f                   // erreur overflow
    cmp x0,#1
    bne 99f                    // Pas premier
    cmp x2,3
    beq 2f
    mov x0,#3
    bl moduloPuR64
    blt 100f                   // erreur overflow
    cmp x0,#1
    bne 99f

    cmp x2,5
    beq 2f
    mov x0,#5
    bl moduloPuR64
    bcs 100f                   // erreur overflow
    cmp x0,#1
    bne 99f                    // Pas premier

    cmp x2,7
    beq 2f
    mov x0,#7
    bl moduloPuR64
    bcs 100f                   // erreur overflow
    cmp x0,#1
    bne 99f                    // Pas premier

    cmp x2,11
    beq 2f
    mov x0,#11
    bl moduloPuR64
    bcs 100f                   // erreur overflow
    cmp x0,#1
    bne 99f                    // Pas premier

    cmp x2,13
    beq 2f
    mov x0,#13
    bl moduloPuR64
    bcs 100f                   // erreur overflow
    cmp x0,#1
    bne 99f                    // Pas premier
2:
    cmn x0,0                   // carry à zero pas d'erreur
    mov x0,1                   // premier
    b 100f
99:
    cmn x0,0                   // carry à zero pas d'erreur
    mov x0,#0                  // Pas premier
100:
    ldp x2,x3,[sp],16          // restaur des  2 registres
    ldp x1,lr,[sp],16          // restaur des  2 registres
    ret                        // retour adresse lr x30

/********************************************************/
/*   Calcul modulo de b puissance e modulo m  */
/*    Exemple 4 puissance 13 modulo 497 = 445         */
/********************************************************/
/* x0  nombre  */
/* x1 exposant */
/* x2 modulo   */
moduloPuR64:
    stp x1,lr,[sp,-16]!        // save  registres
    stp x3,x4,[sp,-16]!        // save  registres
    stp x5,x6,[sp,-16]!        // save  registres
    stp x7,x8,[sp,-16]!        // save  registres
    stp x9,x10,[sp,-16]!       // save  registres
    cbz x0,100f
    cbz x1,100f
    mov x8,x0
    mov x7,x1
    mov x6,1                   // resultat
    udiv x4,x8,x2
    msub x9,x4,x2,x8           // contient le reste
1:
    tst x7,1
    beq 2f
    mul x4,x9,x6
    umulh x5,x9,x6
    mov x6,x4
    mov x0,x6
    mov x1,x5
    bl divisionReg128U
    cbnz x1,99f                 // overflow
    mov x6,x3
2:
    mul x8,x9,x9
    umulh x5,x9,x9
    //cbnz x5,99f
    mov x0,x8
    mov x1,x5
    bl divisionReg128U
    cbnz x1,99f                 // overflow
    mov x9,x3
    lsr x7,x7,1
    cbnz x7,1b
    mov x0,x6                  // result
    cmn x0,0                   // carry à zero pas d'erreur
    b 100f
99:
    ldr x0,qAdrszMessOverflow
    bl   affichageMess
    cmp x0,0                   // carry à un car erreur
    mov x0,-1                  // code erreur

100:
    ldp x9,x10,[sp],16         // restaur des  2 registres
    ldp x7,x8,[sp],16          // restaur des  2 registres
    ldp x5,x6,[sp],16          // restaur des  2 registres
    ldp x3,x4,[sp],16          // restaur des  2 registres
    ldp x1,lr,[sp],16          // restaur des  2 registres
    ret                        // retour adresse lr x30
qAdrszMessOverflow:         .quad  szMessOverflow
/***************************************************/
/*   division d un nombre de 128 bits par un nombre de 64 bits */
/***************************************************/
/* x0 contient partie basse dividende */
/* x1 contient partie haute dividente */
/* x2 contient le diviseur */
/* x0 retourne partie basse quotient */
/* x1 retourne partie haute quotient */
/* x3 retourne le reste */
divisionReg128U:
    stp x6,lr,[sp,-16]!        // save  registres
    stp x4,x5,[sp,-16]!        // save  registres
    mov x5,#0                  // raz du reste R
    mov x3,#128                // compteur de boucle
    mov x4,#0                  // dernier bit
1:
    lsl x5,x5,#1               // on decale le reste de 1
    tst x1,1<<63               // test du bit le plus à gauche
    lsl x1,x1,#1               // on decale la partie haute du quotient de 1
    beq 2f
    orr  x5,x5,#1              // et on le pousse dans le reste R
2:
    tst x0,1<<63
    lsl x0,x0,#1               // puis on decale la partie basse
    beq 3f
    orr x1,x1,#1               // et on pousse le bit de gauche dans la partie haute
3:
    orr x0,x0,x4               // position du dernier bit du quotient
    mov x4,#0                  // raz du bit
    cmp x5,x2
    blt 4f
    sub x5,x5,x2                // on enleve le diviseur du reste
    mov x4,#1                   // dernier bit à 1
4:
                               // et boucle
    subs x3,x3,#1
    bgt 1b
    lsl x1,x1,#1               // on decale le quotient de 1
    tst x0,1<<63
    lsl x0,x0,#1               // puis on decale la partie basse
    beq 5f
    orr x1,x1,#1
5:
    orr x0,x0,x4                  // position du dernier bit du quotient
    mov x3,x5
100:
    ldp x4,x5,[sp],16          // restaur des  2 registres
    ldp x6,lr,[sp],16          // restaur des  2 registres
    ret                        // retour adresse lr x30
/********************************************************/
/*        File Include fonctions                        */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"


with Ada.Text_IO;         use Ada.Text_IO;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;
with Ada.Text_IO.Editing; use Ada.Text_IO.Editing;
with Ada.Numerics.Generic_Elementary_Functions;

procedure Main is
   type nums is delta 0.1 digits 15;
   format : String  := "zz_zzz_zzz_zzz_zzz_zz9.9";
   pic    : picture := To_Picture (format);
   package Nums_io is new Decimal_Output (Nums);
   use Nums_IO;
   type U_64 is mod 2**64;

   package mod_io is new Modular_IO (U_64);
   use mod_io;

   function Is_Prime (Num : U_64) return boolean is
      package Flt_Funcs is new Ada.Numerics.Generic_Elementary_Functions
        (Float);
      use Flt_Funcs;

      T     : U_64          := 2;
      Limit : constant U_64 := U_64 (Sqrt (Float (Num)));
   begin
      if Num = 2 then
         return True;
      end if;
      while T <= Limit loop
         if Num mod T = 0 then
            return False;
         end if;
         T := T + (if T > 2 then 2 else 1);
      end loop;
      return True;
   end Is_Prime;
   Prime_Count : natural := 0;
   Prime_Test  : U_64    := 42;
begin
   loop
      if Is_Prime (Prime_Test) then
         Prime_Count := Prime_Count + 1;
         Put ("n =");
         Put (Item => Prime_Count, Width => 3);
         Put (Item => Nums (Prime_Test), Pic => pic);
         New_Line;
         Prime_Test := (Prime_Test * 2) - 1;
      end if;
      Prime_Test := Prime_Test + 1;
      exit when Prime_Count = 42;
   end loop;
end Main;


*        Loops/N plus one half     13/08/2015
LOOPHALF CSECT         USING  LOOPHALF,R12
         LR     R12,R15
BEGIN    LA     R3,MVC
         SR     R5,R5
         LA     R6,1
         LA     R7,10
LOOPI    BXH    R5,R6,ELOOPI       for i=1 to 10
         XDECO  R5,XDEC
         MVC    0(4,R3),XDEC+8
         LA     R3,4(R3)
         CH     R5,=H'10'
         BNL    NEXTI
         MVC    0(2,R3),=C', '
         LA     R3,2(R3)
NEXTI    B      LOOPI              next i
ELOOPI   XPRNT  MVC,80
         XR     R15,R15
         BR     R14
MVC      DC     CL80' '
XDEC     DS     CL12
         YREGS
         END    LOOPHALF


    .model small
    .stack 1024

    .data   ;no data needed

    .code

start:
	mov ax,0000h
	mov cx,0FFFFh	;this value doesn't matter as long as it's greater than decimal 10.

repeatPrinting:
	add ax,1 ;it was easier to start at zero and add here than to start at 1 and add after printing.
	aaa	 ;ascii adjust for addition, corrects 0009h+1 from 000Ah to 0100h
	call PrintBCD_IgnoreLeadingZeroes
	cmp ax,0100h		;does AX = BCD 10?
	je exitLoopEarly	;if so, we're done now. Don't finish the loop.
	push ax
		mov dl,","       ;print a comma
		mov ah,02h
		int 21h

		mov dl,20h	;print a blank space
		mov ah,02h
		int 21h
	pop ax
	loop repeatPrinting
exitLoopEarly:
	mov ax,4C00h
	int 21h			;return to DOS

PrintBCD_IgnoreLeadingZeroes:
	push ax
		cmp ah,0
		jz skipLeadingZero
			or ah,30h                      ;converts a binary-coded-decimal value to an ASCII numeral
			push dx
			push ax
				mov al,ah
				mov ah,0Eh
				int 10h			;prints AL to screeen
			pop ax
			pop dx
skipLeadingZero:
		or al,30h
		push dx
		push ax
			mov ah,0Eh
			int 10h				;prints AL to screen
		pop ax
		pop dx
	pop ax
	ret
        end start ;EOF


#lang racket
(let loop ([n 1024])
  (when (positive? n)
    (displayln n)
    (loop (quotient n 2))))


my $n = 1024; while $n > 0 { say $n; $n div= 2 }


rebol [
	Title: "Loop/While"
	URL: http://rosettacode.org/wiki/Loop/While
]

value: 1024
while [value > 0][
	print value
	value: to-integer value / 2
]


let n = ref(1024)
while n.contents > 0 {
  Js.log(n.contents)
  n := n.contents / 2
}


PROC Main()
  BYTE i

  FOR i=0 TO 70 STEP 7
  DO
    PrintF("%B ",i)
  OD
RETURN


with Loopers;
use Loopers;

procedure For_Main is
begin
        Looper_1;
        Looper_2;
        Looper_3;
end For_Main;

package Loopers is
        procedure Looper_1;
        procedure Looper_2;
        procedure Looper_3;
end Loopers;

with Ada.Text_IO, Ada.Integer_Text_IO;
use Ada.Text_IO, Ada.Integer_Text_IO;

package body Loopers is
        procedure Looper_1 is
                Values : array(1..5) of Integer := (2,4,6,8,10);
        begin
                for I in Values'Range loop
                        Put(Values(I),0);
                        if I = Values'Last then
                                Put_Line(".");
                        else
                                Put(",");
                        end if;
                end loop;
        end Looper_1;

        procedure Looper_2 is
                E : Integer := 5;
        begin
                for I in 1..E loop
                        Put(I*2,0);
                        if I = E then
                                Put_Line(".");
                        else
                                Put(",");
                        end if;
                end loop;
        end Looper_2;

        procedure Looper_3 is
                Values : array(1..10) of Integer := (1,2,3,4,5,6,7,8,9,10);
                Indices : array(1..5) of Integer := (2,4,6,8,10);
        begin
                for I in Indices'Range loop
                        Put(Values(Indices(I)),0);
                        if I = Indices'Last then
                                Put_Line(".");
                        else
                                Put(",");
                        end if;
                end loop;
        end Looper_3;

end Loopers;


procedure main()

every !(!(L  := list(10)) := list(10))  := ?20   # setup a 2d array of random numbers up to 20

every i := 1 to *L do                            # using nested loops
   every j := 1 to *L[i] do
      if L[i,j] = 20 then
         break break write("L[",i,",",j,"]=20")

end


BEGIN
    # returns TRUE if n is prime, FALSE otherwise #
    PROC is prime = ( LONG INT n )BOOL:
         IF   n MOD 2 = 0 THEN n = 2
         ELIF n MOD 3 = 0 THEN n = 3
         ELSE
            LONG INT d := 5;
            BOOL result := TRUE;
            WHILE IF   d * d > n   THEN FALSE
                  ELIF n MOD d = 0 THEN result := FALSE
                  ELIF d +:= 2;
                       n MOD d = 0 THEN result := FALSE
                  ELSE d +:= 4; TRUE
                  FI
            DO SKIP OD;
            result
         FI # is prime # ;

    LONG INT i := 42;
    LONG INT n := 0;
    WHILE n < 42 DO
        IF is prime( i ) THEN
            n +:= 1;
            print( ( "n = "
                   , whole( n,  -2 )
                   , "  "
                   , whole( i, -19 )
                   , newline
                   )
                 );
            i +:= i - 1
        FI;
        i +:= 1
    OD
END


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

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

/*********************************/
/* Initialized data              */
/*********************************/
.data
szMessMultOver:     .asciz "Multiplication 64 : Dépassement de capacité.\n"
sMessResult:        .ascii "Index  : "
sMessIndex:         .fill 11, 1, ' '            @ size => 11
                    .ascii "Value  : "
sMessValeur:        .fill 21, 1, ' '            @ size => 21
szCarriageReturn:   .asciz "\n"

/*********************************/
/* UnInitialized data            */
/*********************************/
.bss
/*********************************/
/*  code section                 */
/*********************************/
.text
.global main
main:                                              @ entry of program
    mov r7,#0                                      @ counter
    mov r5,#42                                     @ start index low bits
    mov r6,#0                                      @ start index high bits
1:                                                 @ begin loop
    mov r0,r5
    mov r1,r6
    bl isPrime                                     @ prime ?
    bcs 100f                                       @ error overflow ?
    cmp r0,#1                                      @ is prime ?
    beq 2f                                         @ yes
    adds r5,#1                                     @ no -> increment index
    addcs r6,#1
    b 1b                                           @ and loop
2:                                                 @ display index and prime
    add r7,#1                                      @ increment counter
    mov r0,r7
    ldr r1,iAdrsMessIndex                          @ conversion index
    bl conversion10
    mov r0,r5
    mov r1,r6                                      @ conversion value
    ldr r2,iAdrsMessValeur
    bl conversionRegDoubleU                        @ conversion double -> ascii
    ldr r0,iAdrsMessResult
    bl affichageMess

    adds r5,r5
    add r6,r6
    addcs r6,#1
    cmp r7,#42                                     @ end ?
    blt 1b                                         @ no loop

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

iAdrsMessIndex:           .int sMessIndex
iAdrsMessValeur:          .int sMessValeur
iAdrszCarriageReturn:     .int szCarriageReturn
iAdrsMessResult:          .int sMessResult

/******************************************************************/
/*     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
/***************************************************/
/*   number is prime ?              */
/***************************************************/
/* r0 contains low bytes of double */
/* r1 contains high bytes of double */
/* r0 returns 1 if prime else 0  */
@2147483647
@4294967297
@131071
isPrime:
    push {r1-r5,lr}                      @ save registers
    mov r4,r0                            @ save double
    mov r5,r1
    subs r2,r0,#1                        @ exposant n - 1
    sbcs r3,r1,#0

    mov r0,#2                            @ base  2
    mov r1,#0
    bl moduloPuR96                       @ compute modulo
    bcs 100f                             @ overflow error
    cmp r0,#1                            @ modulo <> 1 -> no prime
    bne 90f

    mov r0,#3                            @ base 3
    mov r1,#0
    bl moduloPuR96
    bcs 100f                             @ overflow error
    cmp r0,#1
    bne 90f

    mov r0,#5                            @ base 5
    mov r1,#0
    bl moduloPuR96
    bcs 100f                             @ overflow error
    cmp r0,#1
    bne 90f

    mov r0,#7                            @ base 7
    mov r1,#0
    bl moduloPuR96
    bcs 100f                             @ overflow error
    cmp r0,#1
    bne 90f

    mov r0,#11                           @ base 11
    mov r1,#0
    bl moduloPuR96
    bcs 100f                             @ overflow error
    cmp r0,#1
    bne 90f

    mov r0,#13                           @ base 13
    mov r1,#0
    bl moduloPuR96
    bcs 100f                             @ overflow error
    cmp r0,#1
    bne 90f

    mov r0,#17                           @ base 17
    mov r1,#0
    bl moduloPuR96
    bcs 100f                             @ overflow error
    cmp r0,#1
    bne 90f
    mov r0,#1                            @ is prime
    msr     cpsr_f, #0                   @ no error overflow zero -> flags
    b 100f
90:
    mov r0,#0                            @ no prime
    msr     cpsr_f, #0                   @ no error overflow zero -> flags
100:                                     @ fin standard de la fonction
    pop {r1-r5,lr}                       @ restaur registers
    bx lr                                @ return

/********************************************************/
/*   compute  b pow e modulo m  */
/*                                             */
/********************************************************/
/* r0 base double low bits */
/* r1 base double high bits */
/* r2 exposant low bitss  */
/* r3 exposant high bits */
/* r4 modulo low bits */
/* r5 modulo high bits */
/* r0 returns result low bits */
/* r1 returns result high bits */
/* if overflow , flag carry is set else is clear */
moduloPuR96:
    push {r2-r12,lr}                       @ save registers
    cmp r0,#0                              @ control low byte <> zero
    bne 1f
    cmp r1,#0                              @ control high bytes <> zero
    beq 100f
1:
    mov r9,r4                              @ modulo PB
    mov r10,r5                             @ modulo PH
    mov r5,r2                              @ exposant **
    mov r6,r3                              @ exposant
    mov r7,r0                              @ base PB
    mov r8,r1                              @ base PH
    mov r2,#0
    mov r3,r9
    mov r4,r10
    mov r11,#1                             @ result PB
    mov r12,#0                             @ result PH
/* r0 contient partie basse dividende */
/* r1 contient partie moyenne dividende */
/* r2 contient partie haute du diviseur */
/* r3 contient partie basse diviseur  */
/* r4 contient partie haute diviseur  */
/* r0 retourne partie basse du quotient */
/* r1 retourne partie moyenne du quotient */
/* r2 retourne partie haute du quotient */
/* r3 retourne partie basse du reste */
/* r4 retourne partie haute du reste */
    bl divisionReg96DU
    mov r7,r3                               @ base <- remainder
    mov r8,r4
2:
    tst r5,#1                               @ test du bit 0
    beq 3f
    mov r0,r7
    mov r1,r8
    mov r2,r11
    mov r3,r12
    bl multiplicationR96U
    bcs 100f                                @ error overflow
    mov r3,r9
    mov r4,r10
    bl divisionReg96DU
    mov r11,r3                              @ result <- remainder
    mov r12,r4
3:
    mov r0,r7
    mov r1,r8
    mov r2,r7
    mov r3,r8
    bl multiplicationR96U
    bcs 100f                                @ error overflow
    mov r3,r9
    mov r4,r10
    bl divisionReg96DU
    mov r7,r3                               @ base <- remainder
    mov r8,r4

    lsr r5,#1
    lsrs r6,#1
    orrcs r5,#0x80000000
    cmp r5,#0
    bne 2b
    cmp r6,#0
    bne 2b
    mov r0,r11
    mov r1,r12
    msr     cpsr_f, #0                       @ no error overflow zero -> flags
100:                                         @ end function
   	pop {r2-r12,lr}                          @ restaur registers
    bx lr                                    @ return
/***************************************************/
/*   multiplication 2 registers (64 bits) unsigned */
/*   result in 3 registers 96 bits                 */
/***************************************************/
/* r0 low bits number 1    */
/* r1 high bits number 1    */
/* r2 low bits number 2    */
/* r3 high bits number 2    */
/* r0 returns low bits résult   */
/* r1 returns median bits résult */
/* r2 returns high bits résult  */
/* if overflow , flag carry is set else is clear */
multiplicationR96U:
    push {r3-r8,lr}           @ save registers
    umull r5,r6,r0,r2         @ mult low bits
    umull r4,r8,r0,r3         @ mult low bits 1 high bits 2
    mov r0,r5                 @ result low bits ok
    adds r4,r6                @ add results
    addcs  r8,#1              @ carry
    umull r6,r7,r1,r2         @ mult high bits 1 low bits 2
    adds r4,r6                @ add results
    addcs  r8,#1              @ carry
    adds r8,r7                @ add results
    bcs 99f                   @ overflow ?
    umull r6,r7,r1,r3         @ mult high bits 1 high bits 2
    cmp r7,#0                 @ error overflow ?
    bne 99f
    adds r8,r6                @ add results
    bcs 99f                   @ error overflow
    mov r1,r4                 @ return median bytes
    mov r2,r8                 @ return high bytes
    msr cpsr_f, #0            @ no error overflow zero -> flags
    b 100f
99:                           @ display message overflow
	ldr r0,iAdrszMessMultOver @
	bl affichageMess
    mov r0,#0
    mov r1,#0
    msr cpsr_f, #1<<29        @ maj flag carry à 1  et tous les autres à 0
100:                          @ end function
   	pop {r3-r8,lr}            @ restaur registers
    bx lr                     @ return
iAdrszMessMultOver:         .int szMessMultOver
/***************************************************/
/*   division number (3 registers) 92 bits by number (2 registers) 64 bits */
/*           unsigned                            */
/***************************************************/
/* r0 low bits dividende */
/* r1 median bits dividende */
/* r2 high bits dividende */
/* r3 low bits divisor  */
/* r4 high bits divis0r  */
/* r0 returns low bits quotient */
/* r1 returns median bits quotient */
/* r2 returns high bits quotien */
/* r3 returns low bits remainder */
/* r4 returns high bits remainder */
/* remainder do not is 3 registers */
divisionReg96DU:
    push {r5-r10,lr}    @ save registers
    mov r7,r3           @ low bits divisor
    mov r8,r4           @ high bits divisor
    mov r4,r0           @ low bits dividende -> low bits quotient
    mov r5,r1           @ median bits dividende  -> median bits quotient
    mov r6,r2           @ high bits dividende -> high bits quotient

                        @
    mov r0,#0           @ low bits remainder
    mov r1,#0           @ median bits remainder
    mov r2,#0           @ high bits remainder (not useful)
    mov r9,#96          @ counter loop (32 bits * 3)
    mov r10,#0          @ last bit
1:
    lsl   r2,#1         @ shift left high bits remainder
    lsls  r1,#1         @ shift left median bits remainder
    orrcs r2,#1         @ left bit median -> right bit high
    lsls r0,#1          @ shift left low bits remainder
    orrcs r1,#1         @ left bit low -> right bit median
    lsls r6,#1          @ shift left high bits quotient
    orrcs r0,#1         @ left bit high -> right bit low remainder
    lsls r5,#1          @ shift left median bits quotient
    orrcs r6,#1         @ left bit median -> right bit high
    lsls r4,#1          @ shift left low bits quotient
    orrcs r5,#1         @ left bit low -> right bit median
    orr r4,r10          @ last bit -> bit 0 quotient
    mov r10,#0          @ raz du bit
                        @ compare  remainder and divisor
    cmp r2,#0           @ high bit remainder
    bne 2f
    cmp r1,r8           @ compare median bits
    blo 3f              @ lower
    bhi 2f              @ highter
    cmp r0,r7           @ equal -> compare low bits
    blo 3f              @ lower
2:                      @ remainder > divisor
    subs r0,r7          @ sub divisor of remainder
    sbcs r1,r8
    mov r10,#0          @ reuse ponctuelle  r10
    sbc r2,r2,r10       @ carry
    mov r10,#1          @ last bit à 1
3:
    subs r9,#1          @ increment counter loop
    bgt 1b              @ and loop
    lsl r6,#1           @ shift left high bits quotient
    lsls r5,#1          @ shift left median bits quotient
    orrcs r6,#1         @ left bit median -> right bit high
    lsls r4,#1          @ shift left low bits quotient
    orrcs r5,#1         @ left bit low -> right bit median
    orr r4,r10          @ last bit -> bit 0 quotient
    mov r3,r0           @ low bits remainder
    mov r0,r4           @ low bits quotient
    mov r4,r1           @ high bits remainder
    mov r1,r5           @ median bits quotient
    //mov r5,r2
    mov r2,r6           @ high bits quotient

100:                    @ end function
   	pop {r5-r10,lr}     @ restaur registers
    bx lr               @ return

/***************************************************/
/*   Conversion double integer 64bits in ascii     */
/***************************************************/
/* r0 contains low bits     */
/* r1 contains high bits    */
/* r2 contains address area */
conversionRegDoubleU:
    push {r0-r5,lr}         @ save registers
    mov r5,r2
    mov r4,#19              @ start location
    mov r2,#10              @ conversion decimale
1:                          @ begin loop
    bl divisionReg64U       @ division by 10
    add r3,#48              @ -> digit ascii
    strb r3,[r5,r4]         @ store digit in area index r4
    sub r4,r4,#1            @ decrement index
    cmp r0,#0               @ low bits quotient = zero ?
    bne 1b	                @ no -> loop
    cmp r1,#0               @ high bits quotient = zero ?
    bne 1b                  @ no -> loop
                            @ spaces -> begin area
    mov r3,#' '             @ space
2:
    strb r3,[r5,r4]         @ store space in area
    subs r4,r4,#1           @ decrement index
    bge 2b                  @ and loop if > zéro

100:                        @ end fonction
   	pop {r0-r5,lr}          @ restaur registers
    bx lr                   @ return
/***************************************************/
/*   division number 64 bits / number 32 bits      */
/***************************************************/
/* r0 contains low bits dividende  */
/* r1 contains high bits dividente */
/* r2 contains divisor             */
/* r0 returns low bits quotient    */
/* r1 returns high bits quotient   */
/* r3 returns remainder            */
divisionReg64U:
    push {r4,r5,lr}    @ save registers
    mov r5,#0          @ raz remainder R
    mov r3,#64         @ loop counter
    mov r4,#0          @ last bit
1:
    lsl r5,#1          @ shift left remainder one bit
    lsls r1,#1         @ shift left high bits quotient one bit
    orrcs r5,#1        @ and bit -> remainder
    lsls r0,#1         @ shift left low bits quotient one bit
    orrcs r1,#1        @ and left bit -> high bits
    orr r0,r4          @ last bit  quotient
    mov r4,#0          @ raz last bit
    cmp r5,r2          @ compare remainder divisor
    subhs r5,r2        @ if highter sub divisor of remainder
    movhs r4,#1        @  and 1 -> last bit
3:
    subs r3,#1         @ decrement counter loop
    bgt 1b             @ and loop if not zero
    lsl r1,#1          @ else shift left higt bits quotient
    lsls r0,#1         @ and shift  left low bits
    orrcs r1,#1
    orr r0,r4          @ last bit quotient
    mov r3,r5
100:                   @ end function
    pop {r4,r5,lr}     @ restaur registers
    bx lr              @ return


/* ARM assembly AARCH64 Raspberry PI 3B */
/*  program loopnplusone64.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
szMessComma:       .asciz ", "
szCarriageReturn:  .asciz "\n"
/*********************************/
/* UnInitialized data            */
/*********************************/
.bss
sZoneConv:              .skip 24
/*********************************/
/*  code section                 */
/*********************************/
.text
.global main
main:                                     // entry of program
    mov x20,1                             // loop counter
1:                                        // begin loop
    mov x0,x20
    ldr x1,qAdrsZoneConv                  // display value
    bl conversion10                       // decimal conversion
    ldr x0,qAdrszMessResult
    ldr x1,qAdrsZoneConv                  // display value
    bl strInsertAtCharInc                 // insert result at @ character
    bl affichageMess                      // display message
    ldr x0,qAdrszMessComma
    bl affichageMess                      // display comma
    add x20,x20,1                             // increment counter
    cmp x20,10                            // end ?
    blt 1b                                // no ->begin loop one
    mov x0,x20
    ldr x1,qAdrsZoneConv                  // display value
    bl conversion10                       // decimal conversion
    ldr x0,qAdrszMessResult
    ldr x1,qAdrsZoneConv                  // display value
    bl strInsertAtCharInc                 // insert result at @ character
    bl affichageMess                      // display message
    ldr x0,qAdrszCarriageReturn
    bl affichageMess                      // display return line

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
qAdrszMessComma:          .quad szMessComma
qAdrszCarriageReturn:     .quad szCarriageReturn

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


(defun print-list (xs)
   (progn$ (cw "~x0" (first xs))
           (if (endp (rest xs))
               (cw (coerce '(#\Newline) 'string))
               (progn$ (cw ", ")
                       (print-list (rest xs))))))


PROC Main()
  BYTE i=[1]

  DO
    PrintB(i)
    IF i=10 THEN
      EXIT
    FI
    Print(", ")
    i==+1
  OD
RETURN


/*REXX program demonstrates a  DO WHILE  with index reduction construct.*/
j=1024                                 /*define the initial value of  J.*/
        do  while  j>0                 /*test if made at the top of  DO.*/
        say j
        j=j%2                          /*in REXX, % is integer division.*/
        end
                                       /*stick a fork in it, we're done.*/


i = 1024
while i > 0
      see i + nl
      i = floor(i / 2)
end


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


for i from 2 to 8 by 2 do
    print( i )
od


integer i;

i = 0;
while (i < 10) {
    o_winteger(2, i);
    i += 2;
}

o_newline();


for i:=5 step 5 until 25 do
  OUTINTEGER(i)


 [ for index ] [ from first ] [ by increment ] [ to last ] [ while condition ] do statements od
 The minimum form of a "loop clause" is thus: do statements od # an infinite loop #


import java.util.Random;

public class NestedLoopTest {
    public static final Random gen = new Random();
    public static void main(String[] args) {
        int[][] a = new int[10][10];
        for (int i = 0; i < a.length; i++)
            for (int j = 0; j < a[i].length; j++)
                a[i][j] = gen.nextInt(20) + 1;

        Outer:for (int i = 0; i < a.length; i++) {
            for (int j = 0; j < a[i].length; j++) {
                System.out.print(" " + a[i][j]);
                if (a[i][j] == 20)
                    break Outer; //adding a label breaks out of all loops up to and including the labelled loop
            }
            System.out.println();
        }
        System.out.println();
    }
}


i: 42
n: 0

while [n<42][
	if? prime? i [
		n: n+1
		print ["n =" pad to :string n 2 pad to :string i 20]
		i: i + i
	]
	else [
		i: i + 1
	]
]


i:= 42, n:= 1, result := ""
while (n<43){
	if isPrime(i)
		result .= n ":`t" RegExReplace(i, "\B(?=(\d{3})+$)", ",") "`n", i*=2, n++
	else
		i++
}
MsgBox, 262208, , % result
return

isPrime(num){
	if !Mod(num, 2) || !Mod(num, 3)
		return false
	lim := Sqrt(num),	i := 5
	while (i<lim){
		if !Mod(num, i)
			return false
		i+=2
	}
	return true
}


# syntax: GAWK -f LOOPS_INCREMENT_LOOP_INDEX_WITHIN_LOOP_BODY.AWK
BEGIN {
    limit = 42
    n = 0
    for (i=limit; n<limit; i++) {
      if (is_prime(i)) {
        printf("%2d %19'd\n",++n,i)
        i += i - 1
      }
    }
    exit(0)
}
function is_prime(n,  d) {
    if (n % 2 == 0) { return(n == 2) }
    if (n % 3 == 0) { return(n == 3) }
    d = 5
    while (d*d <= n) {
      if (n % d == 0) { return(0) }
      d += 2
      if (n % d == 0) { return(0) }
      d += 4
    }
    return(1)
}


with Ada.Text_IO;

procedure LoopsAndHalf is
begin
  for i in 1 .. 10 loop
    Ada.Text_IO.put (i'Img);
    exit when i = 10;
    Ada.Text_IO.put (",");
  end loop;
  Ada.Text_IO.new_line;
end LoopsAndHalf;


integer i;

i = 0;
while (1) {
    i += 1;
    o_integer(i);
    if (i == 10) {
        break;
    }
    o_text(", ");
}
o_text("\n");


'BEGIN'
  'COMMENT' Loops N plus one half - Algol60 - 20/06/2018;
  'INTEGER' I;
  'FOR' I:=1 'STEP' 1 'UNTIL' 10 'DO' 'BEGIN'
    OUTINTEGER(1,I);
    'IF' I 'NOTEQUAL' 10 'THEN' OUTSTRING(1,'(', ')')
  'END'
'END'


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


data _null_;
n=1024;
do while(n>0);
  put n;
  n=int(n/2);
end;
run;


class MAIN is
  main is
    i ::= 1024;
    loop while!(i > 0);
      #OUT + i + "\n";
      i := i / 2;
    end;
  end;
end;


begin
    for i := 3 step 2 until 9 do write( i )
end.


BEGIN
    INTEGER I;
    FOR I := 1 STEP 3 UNTIL 19 DO
        WRITE( I );
END


repeat with i from 2 to 10 by 2
	log i
end repeat


# Given an m x n matrix,
# produce a stream of the matrix elements (taken row-wise)
# up to but excluding the first occurrence of $max
def stream($max):
  . as $matrix
  | length as $m
  | (.[0] | length) as $n
  | label $ok
  | {i: range(0;$m), j: range(0;$n)}
  | $matrix[.i][.j] as $m
  | if $m == $max then break $ok else $m end ;


function isPrime(number)
	if (number % 2 = 0) or (number % 3 = 0) then return false
	lim = sqr(number)

	for i = 5 to lim step 2
		if number % i = 0 then return false
	next i

	return true
end function

i = 42
counter = 0
while counter < 42
	if isPrime(i) then
		counter += 1
		print "n = "; counter, i
		i += i - 1
	end if
	i += 1
end while
end


#include <stdio.h>
#include <locale.h>

#define LIMIT 42

int is_prime(long long n) {
    if (n % 2 == 0) return n == 2;
    if (n % 3 == 0) return n == 3;
    long long d = 5;
    while (d * d <= n) {
        if (n % d == 0) return 0;
        d += 2;
        if (n % d == 0) return 0;
        d += 4;
    }
    return 1;
}

int main() {
    long long i;
    int n;
    setlocale(LC_NUMERIC, "");
    for (i = LIMIT, n = 0; n < LIMIT; i++)
        if (is_prime(i)) {
            n++;
            printf("n = %-2d  %'19lld\n", n, i);
            i += i - 1;
        }
    return 0;
}


using System;
using System.Globalization;

namespace PrimeNumberLoopcs
{
    class Program
    {
        static bool isPrime(double number)
        {
            for(double i = number - 1; i > 1; i--)
            {
                if (number % i == 0)
                    return false;
            }
            return true;
        }
        static void Main(string[] args)
        {
            NumberFormatInfo nfi = new CultureInfo("en-US", false).NumberFormat;
            nfi.NumberDecimalDigits = 0;
            double i = 42;
            int n = 0;
            while (n < 42)
            {
                if (isPrime(i))
                {
                    n++;
                    Console.WriteLine("n = {0,-20} {1,20}", n, i.ToString("N", nfi));
                    i += i - 1;
                }
                i++;
            }
        }
    }
}


begin
    integer i;
    i := 0;
    while
        begin
           i := i + 1;
           writeon( i );
           i < 10
        end
    do
    begin
       writeon( "," )
    end
end.


PROC main()
  DEF i
  FOR i := 1 TO 10
    WriteF('\d', i)
    EXIT i = 10
    WriteF(', ')
  ENDFOR
ENDPROC


/* ARM assembly Raspberry PI  */
/*  program loopnplusone.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, ' '
szMessComma:       .asciz ","
szCarriageReturn:  .asciz "\n"
/*********************************/
/* UnInitialized data            */
/*********************************/
.bss
/*********************************/
/*  code section                 */
/*********************************/
.text
.global main
main:                                       @ entry of program
    mov r4,#1                               @ 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,iAdrszMessComma
    bl affichageMess                        @ display comma
    add r4,#1                               @ increment counter
    cmp r4,#10                              @ end ?
    blt 1b                                  @ no ->begin loop one
    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

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
iAdrszMessComma:          .int szMessComma
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
    sub r2,#1                               @ previous position
    cmp r0,#0                               @ stop if quotient = 0
    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


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


(do ((n 1024 (quotient n 2)))
    ((<= n 0))
    (display n)
    (newline))


i=1024
while i>0
    printf("%4d\n",i)
    i=int(i/2)
end