package main

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

// function, per task description
func largest(a []int) (lg int, ok bool) {
    if len(a) == 0 {
        return
    }
    lg = a[0]
    for _, e := range a[1:] {
        if e > lg {
            lg = e
        }
    }
    return lg, true
}

func main() {
    // random size slice
    rand.Seed(time.Now().UnixNano())
    a := make([]int, rand.Intn(11))
    for i := range a {
        a[i] = rand.Intn(101) - 100 // fill with random numbers
    }

    fmt.Println(a)
    lg, ok := largest(a)
    if ok {
        fmt.Println(lg)
    } else {
        fmt.Println("empty list.  no maximum.")
    }
}


      DEF FN_GCD_Iterative_Euclid(A%, B%)
      LOCAL C%
      WHILE B%
        C% = A%
        A% = B%
        B% = C% MOD B%
      ENDWHILE
      = ABS(A%)


define even(a)
{
  if ( a % 2 == 0 ) {
    return(1);
  } else {
    return(0);
  }
}

define abs(a)
{
  if (a<0) {
    return(-a);
  } else {
    return(a);
  }
}


/*
This is a code implementation for finding one or more contiguous subsequences in a general sequence with the maximum sum of its elements.
p_list      -- List of elements of the general sequence of integers separated by a delimiter.
p_delimiter -- proper delimiter
*/

WITH
  FUNCTION greatest_subsequential_sum(p_list IN varchar2, p_delimiter IN varchar2) RETURN varchar2 IS
    -- Variablen
    v_list       varchar2(32767) := TRIM(BOTH p_delimiter FROM p_list);
    v_substr_i   varchar2(32767);
    v_substr_j   varchar2(32767);
    v_substr_out varchar2(32767);
    v_res        INTEGER := 0;
    v_res_out    INTEGER := 0;
    --
  BEGIN
     --
     v_list := regexp_replace(v_list,''||chr(92)||p_delimiter||'{2,}',p_delimiter);
     --
     FOR i IN 1..nvl(regexp_count(v_list,'[^'||p_delimiter||']+'),0)
     loop
       v_substr_i := substr(v_list,regexp_instr(v_list,'[^'||p_delimiter||']+',1,i));
       --
       FOR j IN reverse 1..regexp_count(v_substr_i,'[^'||p_delimiter||']+')
       loop
         --
         v_substr_j := TRIM(BOTH p_delimiter FROM substr(v_substr_i,1,regexp_instr(v_substr_i,'[^'||p_delimiter||']+',1,j,1)));
         EXECUTE immediate 'select sum('||REPLACE(v_substr_j,p_delimiter,'+')||') from dual' INTO v_res;
         --
         IF v_res > v_res_out THEN
            v_res_out := v_res;
            v_substr_out := '{'||v_substr_j||'}';
         elsif v_res = v_res_out THEN
            v_res_out := v_res;
            v_substr_out := v_substr_out||',{'||v_substr_j||'}';
         END IF;
         --
      END loop;
      --
   END loop;
   --
   v_substr_out := TRIM(BOTH ',' FROM nvl(v_substr_out,'{}'));
   v_substr_out := CASE WHEN regexp_count(v_substr_out,'},{')>0 THEN 'subsequences '||v_substr_out ELSE 'a subsequence '||v_substr_out END;
   RETURN 'The maximum sum '||v_res_out||' belongs to '||v_substr_out||' of the main sequence {'||p_list||'}';
END;

--Test
SELECT greatest_subsequential_sum('-1|-2|-3|-4|-5|', '|') AS "greatest subsequential sum" FROM dual
UNION ALL
SELECT greatest_subsequential_sum('', '') FROM dual
UNION ALL
SELECT greatest_subsequential_sum('     ', ' ') FROM dual
UNION ALL
SELECT greatest_subsequential_sum(';;;;;;+1;;;;;;;;;;;;;2;+3;4;;;;-5;;;;', ';') FROM dual
UNION ALL
SELECT greatest_subsequential_sum('-1,-2,+3,,,,,,,,,,,,+5,+6,-2,-1,+4,-4,+2,-1', ',') FROM dual
UNION ALL
SELECT greatest_subsequential_sum(',+7,-6,-8,+5,-2,-6,+7,+4,+8,-9,-3,+2,+6,-4,-6,,', ',') FROM dual
UNION ALL
SELECT greatest_subsequential_sum('01 +2 3 +4 05 -8 -9 -20 40 25 -5', ' ') FROM dual
UNION ALL
SELECT greatest_subsequential_sum('1 2 3 0 0  -99 02 03 00001 -99 3 2 1 -99 3 1 2 0', ' ') FROM dual
UNION ALL
SELECT greatest_subsequential_sum('0,0,1,0', ',') FROM dual
UNION ALL
SELECT greatest_subsequential_sum('0,0,0', ',') FROM dual
UNION ALL
SELECT greatest_subsequential_sum('1,-1,+1', ',') FROM dual;


{$-1=}:max;
[1 4 8 42 6 3]max # Example usage


get "libhdr"

let gcd(m,n) = n=0 -> m, gcd(n, m rem n)

let show(m,n) be
    writef("gcd(%N, %N) = %N*N", m, n, gcd(m, n))

let start() be
$(  show(18,12)
    show(1071,1029)
    show(3528,3780)
$)


val maxsubseq = let
  fun loop (_, _, maxsum, maxseq) [] = (maxsum, rev maxseq)
    | loop (sum, seq, maxsum, maxseq) (x::xs) = let
        val sum = sum + x
        val seq = x :: seq
      in
        if sum < 0 then
          loop (0, [], maxsum, maxseq) xs
        else if sum > maxsum then
          loop (sum, seq, sum, seq) xs
        else
          loop (sum, seq, maxsum, maxseq) xs
      end
in
  loop (0, [], 0, [])
end;

maxsubseq [~1, ~2, 3, 5, 6, ~2, ~1, 4, ~4, 2, ~1]


func maxSubseq(sequence: [Int]) -> (Int, Int, Int) {
    var maxSum = 0, thisSum = 0, i = 0
    var start = 0, end = -1
    for (j, seq) in sequence.enumerated() {
        thisSum += seq
        if thisSum < 0 {
            i = j + 1
            thisSum = 0
        } else if (thisSum > maxSum) {
            maxSum = thisSum
            start = i
            end = j
        }
    }
    return start <= end && start >= 0 && end >= 0
        ? (start, end + 1, maxSum) : (0, 0, 0)
}

let a = [-1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1]
let (start, end, maxSum) = maxSubseq(sequence: a)
print("Max sum = \(maxSum)")
print(a[start..<end])


package require Tcl 8.5
set a {-1 -2 3 5 6 -2 -1 4 -4 2 -1}

# from the Perl solution
proc maxsumseq1 {a} {
    set len [llength $a]
    set maxsum 0

    for {set start 0} {$start < $len} {incr start} {
        for {set end $start} {$end < $len} {incr end} {
            set sum 0
            incr sum [expr [join [lrange $a $start $end] +]]
            if {$sum > $maxsum} {
                set maxsum $sum
                set maxsumseq [lrange $a $start $end]
            }
        }
    }
    return $maxsumseq
}

# from the Python solution
proc maxsumseq2 {sequence} {
    set start -1
    set end -1
    set maxsum_ 0
    set sum_ 0
    for {set i 0} {$i < [llength $sequence]} {incr i} {
        set x [lindex $sequence $i]
        incr sum_ $x
        if {$maxsum_ < $sum_} {
            set maxsum_ $sum_
            set end $i
        } elseif {$sum_ < 0} {
            set sum_ 0
            set start $i
        }
    }
    assert {$maxsum_ == [maxsum $sequence]}
    assert {$maxsum_ == [sum [lrange $sequence [expr {$start + 1}] $end]]}
    return [lrange $sequence [expr {$start + 1}] $end]
}

proc maxsum {sequence} {
    set maxsofar 0
    set maxendinghere 0
    foreach x $sequence {
        set maxendinghere [expr {max($maxendinghere + $x, 0)}]
        set maxsofar [expr {max($maxsofar, $maxendinghere)}]
    }
    return $maxsofar
}

proc assert {condition {message "Assertion failed!"}} {
    if { ! [uplevel 1 [list expr $condition]]} {
        return -code error $message
    }
}

proc sum list {
    expr [join $list +]
}

puts "sequence:  $a"
puts "maxsumseq1: [maxsumseq1 $a]"
puts [time {maxsumseq1 $a} 1000]
puts "maxsumseq2: [maxsumseq2 $a]"
puts [time {maxsumseq2 $a} 1000]


fun greatest a
  let l len a
  let max a[0]
  for let i 1; i < l; i++
    if max < a[i]
      let max a[i]
    endif
  endfor
  return max
endfun


   max_value = MAX( -123,  234.56, 345.678, -456E3, -455) ! built-in function MAX(...)

! or for an array:
   max_value = MAX( array_of_values )

! or to find a maximum value in a file named filename:
   CHARACTER List, filename='Greatest element of a list.hic' ! filename contains this script
   REAL values(1) ! unknown number of values, allocate more below

   OPEN(FIle=filename, BINary, LENgth=len)
   ALLOCATE(values, len/2) ! number of values <= half byte count of file
   ! read all values, returns item count in values_found:
   READ(FIle=filename, ItemS=values_found, CLoSe=1) values ! no Format needed for plain text numbers

   max_value = MAX(values)

   ! write values found in filename and result to spreadsheet type dialog window:
   DLG(Text=values, Text=max_value, TItle=values_found)

   WRITE(ClipBoard, Name) max_value, values_found, values ! pasted to line below
   ! max_value=345.678; values_found=30; values(1)=-123; values(2)=234.56; values(3)=345.678; values(4)=-456E3; values(5)=-455; values(6)=1; values(7)=2; values(8)=1; values(9)=0; values(10)=0; ...truncated
 END


int
gcd_iter(int u, int v) {
  if (u < 0) u = -u;
  if (v < 0) v = -v;
  if (v) while ((u %= v) && (v %= u));
  return (u + v);
}


#import std
#import int

max_subsequence = zleq$^l&r/&+ *aayK33PfatPRTaq ^/~& sum:-0

#cast %zL

example = max_subsequence <-1,-2,3,5,6,-2,-1,4,-4,2,-1>


include c:\cxpl\codes;
int Array, Size, Sum, Best, I, Lo, Hi, BLo, BHi;

[Array:= [-1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1];
Size:= 11;
Best:= -100000;
for Lo:= 0 to Size-1 do
    for Hi:= Lo to Size-1 do
        [Sum:= 0;
        for I:= Lo to Hi do
                Sum:= Sum + Array(I);
        if Sum > Best then
                [Best:= Sum;  BLo:= Lo;  BHi:= Hi];
        ];
Text(0, "Sequence = ");
for I:= 0 to Size-1 do
        [IntOut(0, Array(I)); Text(0, " ")];
CrLf(0);
Text(0, "Greatest = ");
for I:= BLo to BHi do
        [IntOut(0, Array(I)); Text(0, " ")];
CrLf(0);
Text(0, "Sum = ");  IntOut(0, Best);  CrLf(0);
]


var gss = Fn.new { |s|
    var best = 0
    var start = 0
    var end = 0
    var sum = 0
    var sumStart = 0
    var i = 0
    for (x in s) {
        sum = sum + x
        if (sum > best) {
            best = sum
            start = sumStart
            end = i + 1
        } else if (sum < 0) {
            sum = 0
            sumStart = i + 1
        }
        i = i + 1
    }
    return [s[start...end], best]
}

var tests = [
    [-1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1],
    [-1, 1, 2, -5, -6],
    [],
    [-1, -2, -1]
]
for (test in tests) {
    System.print("Input:   %(test)")
    var res = gss.call(test)
    var subSeq = res[0]
    var sum = res[1]
    System.print("Sub seq: %(subSeq)")
    System.print("Sum:     %(sum)\n")
}


:-  %say
|=  [^ [a=(list ,@) ~] ~]
:-  %noun
  (snag 0 (sort a gte))


concept largest(l) {
	large = l[0]
	for element in l
		if element > large
			large = element
		end
	end
	return large
}

software {
	print(largest([23, 1313, 21, 35757, 4, 434, 232, 2, 2342]))
}


procedure main()
   local l
   l := [7,8,6,9,4,5,2,3,1]
   write(max(l))
end

procedure max(l)
   local max
   max := l[1]
   every max <:= !l
   return max
end


static void Main()
{
	Console.WriteLine("GCD of {0} and {1} is {2}", 1, 1, gcd(1, 1));
	Console.WriteLine("GCD of {0} and {1} is {2}", 1, 10, gcd(1, 10));
	Console.WriteLine("GCD of {0} and {1} is {2}", 10, 100, gcd(10, 100));
	Console.WriteLine("GCD of {0} and {1} is {2}", 5, 50, gcd(5, 50));
	Console.WriteLine("GCD of {0} and {1} is {2}", 8, 24, gcd(8, 24));
	Console.WriteLine("GCD of {0} and {1} is {2}", 36, 17, gcd(36, 17));
	Console.WriteLine("GCD of {0} and {1} is {2}", 36, 18, gcd(36, 18));
	Console.WriteLine("GCD of {0} and {1} is {2}", 36, 19, gcd(36, 19));
	for (int x = 1; x < 36; x++)
	{
		Console.WriteLine("GCD of {0} and {1} is {2}", 36, x, gcd(36, x));
	}
	Console.Read();
}

/// <summary>
/// Greatest Common Denominator using Euclidian Algorithm
/// </summary>
static int gcd(int a, int b)
{
    while (b != 0) b = a % (a = b);
    return a;
}


fcn maxsubseq(s){
   s.reduce(fcn([(sum, seq, maxsum, maxseq)], x){
      sum=sum+x; seq=T(x).extend(seq);
      if(sum < 0)     return(0,T,maxsum,maxseq);
      if (sum>maxsum) return(sum, seq, sum, seq);
		      return(sum, seq, maxsum, maxseq);
   },
   T(0,T,0,T))[3].reverse();   // -->maxseq.reverse()
}


1000 DEF FINDMAX(REF ARR)
1010   LET MX=ARR(LBOUND(ARR))
1020   FOR I=LBOUND(ARR)+1 TO UBOUND(ARR)
1030     LET MX=MAX(MX,ARR(I))
1040   NEXT
1050   LET FINDMAX=MX
1060 END DEF


(def elems @[3 1 3 2])

# Use extreme function from stdlib with > function.
(extreme > elems)

# Unpack list as arguments to max function.
(max ;elems)


#include <iostream>
#include <numeric>

int main() {
    std::cout << "The greatest common divisor of 12 and 18 is " << std::gcd(12, 18) << " !\n";
}


(defn gcd
  "(gcd a b) computes the greatest common divisor of a and b."
  [a b]
  (if (zero? b)
    a
    (recur b (mod a b))))


public static float max(float[] values) throws NoSuchElementException {
    if (values.length == 0)
        throw new NoSuchElementException();
    float themax = values[0];
    for (int idx = 1; idx < values.length; ++idx) {
        if (values[idx] > themax)
            themax = values[idx];
    }
    return themax;
}


gcd = proc (a, b: int) returns (int)
    while b~=0 do
        a, b := b, a//b
    end
    return(a)
end gcd

start_up = proc()
    po: stream := stream$primary_input()
    as: array[int] := array[int]$[18, 1071, 3528]
    bs: array[int] := array[int]$[12, 1029, 3780]
    for i: int in array[int]$indexes(as) do
        stream$putl(po, "gcd(" || int$unparse(as[i]) || ", "
            || int$unparse(bs[i]) || ") = "
            || int$unparse(gcd(as[i], bs[i])))
    end
end start_up


       IDENTIFICATION DIVISION.
       PROGRAM-ID. GCD.

       DATA DIVISION.
       WORKING-STORAGE SECTION.
       01 A        PIC 9(10)   VALUE ZEROES.
       01 B        PIC 9(10)   VALUE ZEROES.
       01 TEMP     PIC 9(10)   VALUE ZEROES.

       PROCEDURE DIVISION.
       Begin.
           DISPLAY "Enter first number, max 10 digits."
           ACCEPT A
           DISPLAY "Enter second number, max 10 digits."
           ACCEPT B
           IF A < B
             MOVE B TO TEMP
             MOVE A TO B
             MOVE TEMP TO B
           END-IF

           PERFORM UNTIL B = 0
             MOVE A TO TEMP
             MOVE B TO A
             DIVIDE TEMP BY B GIVING TEMP REMAINDER B
           END-PERFORM
           DISPLAY "The gcd is " A
           STOP RUN.


julia> maximum([1,3,3,7])
7

julia> maximum([pi,e+2/5,cos(6)/5,sqrt(91/10)])
3.141592653589793

julia> maximum([1,6,Inf])
Inf

julia> maximum(Float64[])
maximum: argument is empty
at In[138]:1
 in maximum at abstractarray.jl:1591


include ..\Utilitys.tlhy

( "1" "1234" "62" "234" "12" "34" "6" )

dup "Alphabetic order: " print lmax ?

:f tonum ;

@f map

"Numeric order: " print lmax ?

" " input


class Rosetta
	def gcd(u as number, v as number) as number
		u, v = u.abs, v.abs
		while v > 0
			u, v = v, u % v
		return u

	def main
		print "gcd of [12] and [8] is [.gcd(12, 8)]"
		print "gcd of [12] and [-8] is [.gcd(12, -8)]"
		print "gcd of [96] and [27] is [.gcd(27, 96)]"
		print "gcd of [51] and [34] is [.gcd(34, 51)]"


gcd = (x, y) ->
  if y == 0 then x else gcd y, x % y


// version 1.0.5-2
fun main(args: Array<String>) {
    print("Number of values to be input = ")
    val n = readLine()!!.toInt()
    val array = DoubleArray(n)
    for (i in 0 until n) {
         print("Value ${i + 1} = ")
         array[i] = readLine()!!.toDouble()
    }
    println("\nThe greatest element is ${array.max()}")
}


1) using the builtin primitive

{max 556 1 7344 4 7 52 22 55 88 122 55 99 1222 578}
-> 7344

2) buidling a function

{def my-max
 {def max-h
  {lambda {:l :greatest}
   {if {A.empty? :l}
    then :greatest
    else {max-h {A.rest :l}
                {if {> {A.first :l} :greatest}
                 then {A.first :l}
                 else :greatest}}}}}
 {lambda {:l}
  {if {A.empty? :l} then empty else {max-h :l {A.first :l}}}}}
-> my-max

{my-max {A.new 556 1 7344 4 7 52 22 55 88 122 55 99 1222 578}}
-> 7344


MODULE Operations;
IMPORT StdLog,Args,Strings;

PROCEDURE Gcd(a,b: LONGINT):LONGINT;
VAR
	r: LONGINT;
BEGIN
	LOOP
		r := a MOD b;
		IF r = 0 THEN RETURN b END;
		a := b;b := r
	END
END Gcd;

PROCEDURE DoGcd*;
VAR
	x,y,done: INTEGER;
	p: Args.Params;
BEGIN
	Args.Get(p);
	IF p.argc >= 2 THEN
		Strings.StringToInt(p.args[0],x,done);
		Strings.StringToInt(p.args[1],y,done);
		StdLog.String("gcd("+p.args[0]+","+p.args[1]+")=");StdLog.Int(Gcd(x,y));StdLog.Ln
	END
END DoGcd;

END Operations.


aList$= "1 15 -5 6 39 1.5 14"

maxVal = val(word$(aList$, 1))
token$ = "?"
while token$ <> ""
    index = index + 1
    token$ = word$(aList$, index)
    aVal = val(token$)
    if aVal > maxVal then maxVal = aVal
wend

print "maxVal = ";maxVal


import std.stdio, std.numeric;

long myGCD(in long x, in long y) pure nothrow @nogc {
    if (y == 0)
        return x;
    return myGCD(y, x % y);
}

void main() {
    gcd(15, 10).writeln; // From Phobos.
    myGCD(15, 10).writeln;
}


to max :a :b
output ifelse :a > :b [:a] [:b]
end

print reduce "max [...]


proc nonrec gcd(word m, n) word:
    word t;
    while n ~= 0 do
        t := m;
        m := n;
        n := t % n
    od;
    m
corp

proc nonrec show(word m, n) void:
    writeln("gcd(", m, ", ", n, ") = ", gcd(m, n))
corp

proc nonrec main() void:
    show(18, 12);
    show(1071, 1029);
    show(3528, 3780)
corp


max([X| Xs], Max) :-
    max(Xs, X, Max).

max([], Max, Max).
max([X| Xs], Aux, Max) :-
    (   X @> Aux ->
        max(Xs, X, Max)
    ;   max(Xs, Aux, Max)
    ).


-- Table to store values
local values = {}
-- Read in the first number from stdin
local new_val = io.read"*n"
-- Append all numbers passed in
-- until there are no more numbers (io.read'*n' = nil)
while new_val do
  values[#values+1] = new_val
  new_val = io.read"*n"
end

-- Print the max
print(math.max(unpack(values)))


Module TestThis {
      Print "Search a tuple type list (is an array also)"
      A=(,)
      For i=1 to Random(1,10)
      Append A, (Random(1,100),)
      Next
      Print Len(A)
      Print A
      Print A#max()

      Print "Search an array"
      B=lambda->Random(1,100)
      Rem Dim A(1 to Random(1,10))<<B()
      Dim A(1 to Random(1,10))<<lambda->{=Random(1,100)}()
      Print Len(A())
      Print A()
      Print A()#max()

      \\ #max() skip non numeric values
      Rem Print (1,"100",3)#max()=3

      Print "Search an inventory list"
      Inventory C
      for i=1 to Random(1,10)
            do
                  key=random(10000)
            until not exist(c, key)
            \\ we can put a number as string
            if random(1,2)=1 then Append c, key:=B() else Append c, key:=str$(B())
      Next

      \\ if inventory item is string with a number work fine
      Function MaxItem(a) {
            k=each(a,2)
            val=a(0!)
            while k
                  \\ using stack of values
                  \\ over -equal to over 1 - copy value from 1 to top, means double the top value
                  \\ number - pop top value
                  \\ drop -equal to drop 1 : drop top value
                  Push a(k^!): Over : If Number>val then Read Val else drop
                  Rem If a(k^!)>Val Then Val=a(k^!)
            end while
            =val
      }
      Print Len(C)
      Print C
      Print MaxItem(C)

      Print "Search a stack object"
      \\ a stack object is the same as the stack of values
      \\ which always is present
      D=stack
      I=0
      J=Random(1,10)
      \\ Stack stackobjext {}
      \\ hide current stack and attach the D stack
      Stack D {
            Push B() : I++ : IF I>J Else Loop
      }
      \\ if stack item isn't numeric we get a run time error
      Function MaxItemStack(a) {
            Stack a {env$=envelope$()}
            if replace$("N","", env$)<>"" then error "only numbers allowed"
            k=each(a,2)
            val=Stackitem(a,1)
            while k
                  If Stackitem(k)>val then Val=stackitem(k)
            end while
            =val
      }
      Print Len(D)
      Print D
      Print MaxItemStack(D)
}
TestThis


func gcd(a, b) {
    func bgcd(a, b, res) {
        if a == b {
            return res * a
        } else if a % 2 == 0 && b % 2 == 0 {
            return bgcd(a/2, b/2, 2*res)
        } else if a % 2 == 0 {
            return bgcd(a/2, b, res)
        } else if b % 2 == 0 {
            return bgcd(a, b/2, res)
        } else if a > b {
            return bgcd(a-b, b, res)
        } else {
            return bgcd(a, b-a, res)
        }
    }
    return bgcd(a, b, 1)
}

var testdata = [
    (a: 33, b: 77),
    (a: 49865, b: 69811)
]

for v in testdata {
    print("gcd(\(v.a), \(v.b)) = \(gcd(v.a, v.b))")
}


> max( { 1, 2,  Pi, exp(1) } ); # set
                                   Pi

> max( [ 1, 2,  Pi, exp(1) ] ); # list
                                   Pi

> max( 1, 2,  Pi, exp(1) ); # sequence
                                   Pi

> max( Array( [ 1, 2,  Pi, exp(1) ] ) ); # Array
                                   Pi


function [maxValue] = findmax(setOfValues)
   maxValue = max(setOfValues);


def gcd(var u :int, var v :int) {
    while (v != 0) {
        def r := u %% v
        u := v
        v := r
    }
    return u.abs()
}


func gcd a b . res .
  while b <> 0
    h = b
    b = a mod b
    a = h
  .
  res = a
.
call gcd 120 35 r
print r


u : makelist(random(1000), 50)$

/* Three solutions */
lreduce(max, u);

apply(max, u);

lmax(u);


fn MaxValue AnArray =
(
	if AnArray.count != 0 then
	(
		local maxVal = 0
		for i in AnArray do if i > maxVal then maxVal = i
		maxVal
	)
	else undefined
)


 [Greatest common divisor for Rosetta Code.
  Program for EDSAC, Initial Orders 2.]

 [Library subroutine R2. Reads positive integers during input of orders,
    and is then overwritten (so doesn't take up any memory).
  Negative numbers can be input by adding 2^35.
  Each integer is followed by 'F', except the last is followed by '#TZ'.]
            T   45 K [store address in location 45
                    values are then accessed by code letter H]
            P  220 F [<------ address here]
  [email protected]@[email protected]@E13Z
            T     #H  [Tell R2 the storage location defined above]

 [Integers to be read by R2. First item is count, then pairs for GCD algo.]
  4F 1066F 2019F 1815F 1914F 103785682F 167928761F 109876463F 177777648#TZ

 [----------------------------------------------------------------------
  Library subroutine P7.
  Prints long strictly positive integer at 0D.
  10 characters, right justified, padded left with spaces.
  Closed, even; 35 storage locations; working position 4D.]
            T   56 K
  [email protected]#@[email protected]@[email protected]@SFLDUFOFFFSFL4F
  [email protected]@XFT28#[email protected][email protected]@

 [---------------------------------------------------------------
  Subroutine to return GCD of two non-negative 35-bit integers.
  Input:  Integers at 4D, 6D.
  Output: GCD at 4D; changes 6D.
  41 locations; working location 0D.]
            T  100 K
            G      K
            A    3 F  [plant link]
            T   39 @
            S    4 D  [test for 4D = 0]
            E   37 @  [if so, quick exit, GCD = 6D]
            T   40 @  [clear acc]
      [5]   A    4 D  [load divisor]
      [6]   T      D  [initialize shifted divisor]
            A    6 D  [load dividend]
            R      D  [shift 1 right]
            S      D  [shifted divisor > dividend/2 yet?]
            G   15 @  [yes, start subtraction]
            T   40 @  [no, clear acc]
            A      D  [shift divisor 1 more]
            L      D
            E    6 @  [loop back (always, since acc = 0)]
     [15]   T   40 @  [clear acc]
     [16]   A    6 D  [load remainder (initially = dividend)]
            S      D  [trial subtraction]
            G   20 @  [skip if can't subtract]
            T    6 D  [update remainder]
     [20]   T   40 @  [clear acc]
            A    4 D  [load original divisor]
            S      D  [is shifted divisor back to original?]
            E   29 @  [yes, jump out with acc = 0]
            T   40 @  [no, clear acc]
            A      D  [shift divisor 1 right]
            R      D
            T      D
            E   16 @  [loop back (always, since acc = 0)]
         [Here when finished dividing 6D by 4D.
          Remainder is at 6D; acc = 0.]
     [29]   S    6 D  [test for 6D = 0]
            E   39 @  [if so, exit with GCD in 4D]
            T      D  [else swap 4D and 6D]
            A    4 D
            T    6 D
            S      D
            T    4 D
            E    5 @  [loop back]
     [37]   A    6 D  [here if 4D = 0 at start; GCD is 6D]
            T    4 D  [return in 4D as GCD]
     [39]   E      F
     [40]   P      F  [junk word, to clear accumulator]

 [----------------------------------------------------------------------
  Main routine]
            T  150 K
            G      K
  [Variable]
      [0]   P      F
  [Constants]
      [1]   P      D [single-word 1]
      [2]   A    2#H [order to load first number of first pair]
      [3]   P    2 F [to inc addresses by 2]
      [4]   #      F [figure shift]
      [5]   K 2048 F [letter shift]
      [6]   G      F [letters to print 'GCD']
      [7]   C      F
      [8]   D      F
      [9]   V      F [equals sign (in figures mode)]
     [10]   !      F [space]
     [11]   @      F [carriage return]
     [12]   &      F [line feed]
     [13]   K 4096 F [null char]
         [Enter here with acc = 0]
     [14]   O    4 @ [set teleprinter to figures]
            S      H [negative of number of pairs]
            T      @ [initialize counter]
            A    2 @ [initial load order]
     [18]   U   23 @ [plant order to load 1st integer]
            U   32 @
            A    3 @ [inc address by 2]
            U   28 @ [plant order to load 2nd integer]
            T   34 @
     [23]   A     #H [load 1st integer (order set up at runtime)]
            T      D [to 0D for printing]
            A   25 @ [for return from print subroutine]
            G   56 F [print 1st number]
            O   10 @ [followed by space]
     [28]   A     #H [load 2nd integer (order set up at runtime)]
            T      D [to 0D for printing]
            A   30 @ [for return from print subroutine]
            G   56 F [print 2nd number]
     [32]   A     #H [load 1st integer (order set up at runtime)]
            T    4 D [to 4D for GCD subroutine]
     [34]   A     #H [load 2nd integer (order set up at runtime)]
            T    6 D [to 6D for GCD subroutine]
     [36]   A   36 @ [for return from subroutine]
            G  100 F [call subroutine for GCD]
         [Cosmetic printing, add '  GCD = ']
            O   10 @
            O   10 @
            O    5 @
            O    6 @
            O    7 @
            O    8 @
            O    4 @
            O   10 @
            O    9 @
            O   10 @
            A    4 D [load GCD]
            T      D [to 0D for printing]
            A   50 @ [for return from print subroutine]
            G   56 F [print GCD]
            O   11 @ [followed by new line]
            O   12 @
          [On to next pair]
            A      @ [load negative count of c.f.s]
            A    1 @ [add 1]
            E   62 @ [exit if count = 0]
            T      @ [store back]
            A   23 @ [order to load first of pair]
            A    3 @ [inc address by 4 for next c.f.]
            A    3 @
            G   18 @ [loop back (always, since 'A' < 0)]
     [62]   O   13 @  [null char to flush teleprinter buffer]
            Z      F  [stop]
            E   14 Z  [define entry point]
            P      F  [acc = 0 on entry]


class
	APPLICATION

create
	make

feature -- Implementation

	gcd (x: INTEGER y: INTEGER): INTEGER
		do
			if y = 0 then
				Result := x
			else
				Result := gcd (y, x \\ y);
			end
		end

feature {NONE} -- Initialization

	make
			-- Run application.
		do
			print (gcd (15, 10))
			print ("%N")
		end

end


(
  'bool                             ;does the list have any elements?
  (-inf ('> 'pop 'nip if) reduce)   ;do if so
  ({"empty seq" :error "Cannot find the maximum element of an empty sequence" :message} raise)  ;do if not
  if
) :seq-max


list.max = function()
    if not self then return null
    result = self[0]
    for item in self
        if item > result then result = item
    end for
    return result
end function

print [47, 11, 42, 102, 13].max


GENERIC INTERFACE Maximum(Elem);

EXCEPTION Empty;

PROCEDURE Max(READONLY a: ARRAY OF Elem.T): Elem.T RAISES {Empty};

END Maximum.


import system'math;
import extensions;

gcd(a,b)
{
    var i := a;
    var j := b;
    while(j != 0)
    {
        var tmp := i;
        i := j;
        j := tmp.mod(j)
    };

    ^ i
}

printGCD(a,b)
{
    console.printLineFormatted("GCD of {0} and {1} is {2}", a, b, gcd(a,b))
}

public program()
{
    printGCD(1,1);
    printGCD(1,10);
    printGCD(10,100);
    printGCD(5,50);
    printGCD(8,24);
    printGCD(36,17);
    printGCD(36,18);
    printGCD(36,19);
    printGCD(36,33);
}


defmodule RC do
  def gcd(a,0), do: abs(a)
  def gcd(a,b), do: gcd(b, rem(a,b))
end

IO.puts RC.gcd(1071, 1029)
IO.puts RC.gcd(3528, 3780)


2 5 3 12 9 9 56 2 ARR

LEN VAR l .
0 VAR i .
FOR l
    GET i SWAP
    i 1 + VAR i .
ENDFOR .
STKLEN 1 - VAR st .
FOR st
    MAX
ENDFOR PRINT


MV(A,U)
 ;A is a list of values separated by the string U
 NEW MAX,T,I
 FOR I=1:1 SET T=$PIECE(A,U,I) QUIT:T=""  S MAX=$SELECT(($DATA(MAX)=0):T,(MAX<T):T,(MAX>=T):MAX)
 QUIT MAX


def max(list)
	if len(list) = 0
		return null
	end

	largest = list[0]
	for val in list
		if val > largest
			largest = val
		end
	end
	return largest
end


/**
 greatest element from a list (Neko Array)
 Tectonics:
   nekoc greatest-element.neko
   neko greatest-element
*/

var greatest = function(list) {
  var max, element;
  var pos = 1;

  if $asize(list) > 0  max = list[0];

  while pos < $asize(list) {
    element = list[pos];
    if max < element  max = element;
    pos += 1;
  }

  return max;
}

$print(greatest($array(5, 1, 3, 5)), "\n");
$print(greatest($array("abc", "123", "zyx", "def")), "\n");


(defun gcd (a b)
  (cond
   ((< a b) (gcd a (- b a)))
   ((> a b) (gcd (- a b) b))
   (t a)))


% Implemented by Arjun Sunel
-module(gcd).
-export([main/0]).

main() ->gcd(-36,4).

gcd(A, 0) -> A;

gcd(A, B) -> gcd(B, A rem B).


using System;
using Nemerle.Collections;
using System.Linq;
using System.Console;

module SeqMax
{
    SeqMax[T, U] (this seq : T) : U
      where T : Seq[U]
      where U : IComparable
    {
        $[s | s in seq].Fold(seq.First(), (x, y) => {if (x.CompareTo(y) > 0) x else y})
    }

    Main() : void
    {
        def numbers = [1, 12, 3, -5, 6, 23];
        def letters = ['s', 'p', 'a', 'm'];

        // using SeqMax() method (as task says to "create a function")
        WriteLine($"numbers.SeqMax() = $(numbers.SeqMax())");
        WriteLine($"letters.SeqMax() = $(letters.SeqMax())");

        // using the already available Max() method
        WriteLine($"numbers.Max() = $(numbers.Max())");
        WriteLine($"letters.Max() = $(letters.Max())")
    }
}


/* NetRexx */

options replace format comments java crossref savelog symbols binary

rn = Random()
maxElmts = 100
dlist = double[maxElmts]
rlist = Rexx[maxElmts]
loop r_ = 0 to maxElmts - 1
  nr = rn.nextGaussian * 100.0
  dlist[r_] = nr
  rlist[r_] = Rexx(nr)
  end r_

say 'Max double:' Rexx(getMax(dlist)).format(4, 9)
say 'Max   Rexx:' getMax(rlist).format(4, 9)

return

method getMax(dlist = double[]) public static binary returns double
  dmax = Double.MIN_VALUE
  loop n_ = 0 to dlist.length - 1
    if dlist[n_] > dmax then dmax = dlist[n_]
    end n_
  return dmax

method getMax(dlist = Rexx[]) public static binary returns Rexx
  dmax = Rexx(Double.MIN_VALUE)
  loop n_ = 0 to dlist.length - 1
    dmax = dlist[n_].max(dmax)
    end n_
  return dmax


PROGRAM EUCLIDE
! calculate G.C.D. between two integer numbers
! using Euclidean algorithm

!VAR J%,K%,MCD%,A%,B%

BEGIN
  PRINT(CHR$(12);"Input two numbers : ";)  !CHR$(147) in C-64 version
  INPUT(J%,K%)
  A%=J% B%=K%
  WHILE A%<>B% DO
    IF A%>B%
       THEN
         A%=A%-B%
       ELSE
         B%=B%-A%
    END IF
  END WHILE
  MCD%=A%
  PRINT("G.C.D. between";J%;"and";K%;"is";MCD%)
END PROGRAM


>ggt(123456795,1234567851)
 33
>function myggt (n:index, m:index) ...
$  if n<m then {n,m}={m,n}; endif;
$  repeat
$    k=mod(n,m);
$    if k==0 then return m; endif;
$    if k==1 then return 1; endif;
$    {n,m}={m,k};
$  end;
$  endfunction
>myggt(123456795,1234567851)
 33


function gcd_iter(integer u, integer v)
    integer t
    while v do
        t = u
        u = v
        v = remainder(t, v)
    end while
    if u < 0 then
        return -u
    else
        return u
    end if
end function


## இந்த நிரல் இரு எண்களுக்கு இடையிலான மீச்சிறு பொது மடங்கு (LCM), மீப்பெரு பொது வகுத்தி (GCD) என்ன என்று கணக்கிடும்

நிரல்பாகம் மீபொவ(எண்1, எண்2)

	@(எண்1 == எண்2) ஆனால்

  ## இரு எண்களும் சமம் என்பதால், அந்த எண்ணேதான் அதன் மீபொவ

		பின்கொடு எண்1

	@(எண்1 > எண்2) இல்லைஆனால்

		சிறியது = எண்2
		பெரியது = எண்1

	இல்லை

		சிறியது = எண்1
		பெரியது = எண்2

	முடி

	மீதம் = பெரியது % சிறியது

	@(மீதம் == 0) ஆனால்

  ## பெரிய எண்ணில் சிறிய எண் மீதமின்றி வகுபடுவதால், சிறிய எண்தான் மீப்பெரு பொதுவகுத்தியாக இருக்கமுடியும்

		பின்கொடு சிறியது

	இல்லை

		தொடக்கம் = சிறியது - 1

		நிறைவு = 1

		@(எண் = தொடக்கம், எண் >= நிறைவு, எண் = எண் - 1) ஆக

			மீதம்1 = சிறியது % எண்

			மீதம்2 = பெரியது % எண்

   ## இரு எண்களையும் மீதமின்றி வகுக்கக்கூடிய பெரிய எண்ணைக் கண்டறிகிறோம்

			@((மீதம்1 == 0) && (மீதம்2 == 0)) ஆனால்

				பின்கொடு எண்

			முடி

		முடி

	முடி

முடி

அ = int(உள்ளீடு("ஓர் எண்ணைத் தாருங்கள் "))
ஆ = int(உள்ளீடு("இன்னோர் எண்ணைத் தாருங்கள் "))

பதிப்பி "நீங்கள் தந்த இரு எண்களின் மீபொவ (மீப்பெரு பொது வகுத்தி, GCD) = ", மீபொவ(அ, ஆ)


let rec gcd a b =
  if b = 0
    then abs a
  else gcd b (a % b)

>gcd 400 600
val it : int = 200


MODULE GreatestElement1;
IMPORT
  ADT:ArrayList,
  Object:Boxed,
  Out;

VAR
  a: ArrayList.ArrayList(Boxed.LongInt);
  max: Boxed.LongInt;

  PROCEDURE Max(al: ArrayList.ArrayList(Boxed.LongInt)): Boxed.LongInt;
  VAR
    i: LONGINT;
    item, max: Boxed.LongInt;
  BEGIN
    max := NEW(Boxed.LongInt,MIN(LONGINT));

    i := 0;
    WHILE (i < al.size) DO
      item := al.Get(i);
      IF item.value > max.value THEN max := item END;
      INC(i)
    END;
    RETURN max
  END Max;

BEGIN
  a := NEW(ArrayList.ArrayList(Boxed.LongInt),5);
  a.Append(NEW(Boxed.LongInt,10));
  a.Append(NEW(Boxed.LongInt,32));
  a.Append(NEW(Boxed.LongInt,4));
  a.Append(NEW(Boxed.LongInt,43));
  a.Append(NEW(Boxed.LongInt,9));

  max := Max(a);
  Out.String("Max: ");Out.LongInt(max.value,4);Out.Ln
END GreatestElement1.


values := IntVector->New([4, 1, 42, 5]);
values->Max()->PrintLine();


: gcd ( a b -- c )
    [ abs ] [
        [ nip ] [ mod ] 2bi gcd
    ] if-zero ;


10 15$ [0=~][[email protected][email protected][email protected]\/*-$]#%. { gcd(10,15)=5 }


#import <Foundation/Foundation.h>

@interface NSArray (WithMaximum)
- (id)maximumValue;
@end

@implementation NSArray (WithMaximum)
- (id)maximumValue
{
  if ( [self count] == 0 ) return nil;
  id maybeMax = self[0];
  for ( id el in self ) {
    if ( [maybeMax respondsToSelector: @selector(compare:)] &&
	 [el respondsToSelector: @selector(compare:)]       &&
	 [el isKindOfClass: [NSNumber class]]               &&
	 [maybeMax isKindOfClass: [NSNumber class]] ) {
      if ( [maybeMax compare: el] == NSOrderedAscending )
	maybeMax = el;
    } else { return nil; }
  }
  return maybeMax;
}
@end


let my_max = function
    [] -> invalid_arg "empty list"
  | x::xs -> List.fold_left max x xs


class Main
{
  static Int gcd (Int a, Int b)
  {
    a = a.abs
    b = b.abs
    while (b > 0)
    {
      t := a
      a = b
      b = t % b
    }
    return a
  }

  public static Void main()
  {
    echo ("GCD of 51, 34 is: " + gcd(51, 34))
  }
}


: gcd ( a b -- n )
  begin dup while tuck mod repeat drop ;


; builtin function
(max 1 2 3 4 5) ; 5

(define x '(1 2 3 4 5))

; using to numbers list
(apply max x) ; 5

; using list reducing
(fold max (car x) x) ; 5

; manual lambda-comparator
(print (fold (lambda (a b)
   (if (less? a b) b a))
   (car x) x)) ; 5


recursive function gcd_rec(u, v) result(gcd)
    integer             :: gcd
    integer, intent(in) :: u, v

    if (mod(u, v) /= 0) then
        gcd = gcd_rec(v, mod(u, v))
    else
        gcd = v
    end if
end function gcd_rec


' version 17-06-2015
' compile with: fbc -s console

Function gcd(x As ULongInt, y As ULongInt) As ULongInt

    Dim As ULongInt t

    While y
        t = y
        y = x Mod y
        x = t
    Wend

    Return x

End Function

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

Dim As ULongInt a = 111111111111111
Dim As ULongInt b = 11111

Print : Print "GCD(";a;", ";b;") = "; gcd(a, b)
Print : Print "GCD(";a;", 111) = "; gcd(a, 111)

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


-- routine that will work with any ordered collection or sets and bags containing numbers.
::routine listMax
  use arg list
  items list~makearray   -- since we're dealing with different collection types, reduce to an array
  if items~isEmpty then return .nil   -- return a failure indicator.  could also raise an error, if desired
  largest = items[1]

  -- note, this method does call max one extra time.  This could also use the
  -- do i = 2 to items~size to avoid this
  do item over items
     largest = max(item, largest)
  end

  return largest


'Works on any list with element types which support '>' comparisons

macro max any(R,  A, N,   i)
============================
  scope
    indexbase 1
    int i
    R=A(1)
    for i=2 to N
      if A(i)>R
        R=A(i)
      endif
    next
  end scope
end macro

'DEMO
=====
redim double d(100)
d={ 1.1, 1.2, 5.5, -0.1, -12.0 }
double m=max(d,5)
print "greatest element of d(): " m '5.5


declare
  fun {Maximum X|Xr}         %% pattern-match on argument to make sure the list is not empty
     {FoldL Xr Value.max X}  %% fold the binary function Value.max over the list
  end
in
  {Show {Maximum [1 2 3 4 3]}}


module gcd.GCD where

pure native parseInt java.lang.Integer.parseInt :: String -> Int

gcd' a 0 = a
gcd' a b = gcd' b (a `mod` b)

main args = do
    (a:b:_) = args
    println $ gcd' (parseInt a) (parseInt b)


program GElemLIst;
{$IFNDEF FPC}
  {$Apptype Console}
{$else}
  {$Mode Delphi}
{$ENDIF}

uses
  sysutils;
const
  MaxCnt = 1000000;
type
   tMaxIntPos= record
                  mpMax,
                  mpPos : integer;
                end;
   tMaxfltPos= record
                  mpMax : double;
                  mpPos : integer;
                end;

function FindMaxInt(const ia: array of integer):tMaxIntPos;
//delivers the highest Element and position of integer array
var
  i  : NativeInt;
  tmp,max,ps: integer;
Begin
  max := -MaxInt-1;
  ps := -1;
  //i = index of last Element
  i := length(ia)-1;
  IF i>=0 then Begin
    max := ia[i];
    ps := i;
    dec(i);
    while i> 0 do begin
      tmp := ia[i];
      IF max< tmp then begin
        max := tmp;
        ps := i;
        end;
      dec(i);
      end;
    end;
  result.mpMax := Max;
  result.mpPos := ps;
end;

function FindMaxflt(const ia: array of double):tMaxfltPos;
//delivers the highest Element and position of double array
var
  i,
  ps: NativeInt;
  max : double;
  tmp : ^double;//for 32-bit version runs faster

Begin
  max := -MaxInt-1;
  ps := -1;
  //i = index of last Element
  i := length(ia)-1;
  IF i>=0 then Begin
    max := ia[i];
    ps := i;
    dec(i);
    tmp := @ia[i];
    while i> 0 do begin
      IF tmp^>max  then begin
        max := tmp^;
        ps := i;
        end;
      dec(i);
      dec(tmp);
      end;
    end;
  result.mpMax := Max;
  result.mpPos := ps;
end;

var
  IntArr : array of integer;
  fltArr : array of double;
  ErgInt : tMaxINtPos;
  ErgFlt : tMaxfltPos;
  i: NativeInt;
begin
  randomize;
  setlength(fltArr,MaxCnt); //filled with 0
  setlength(IntArr,MaxCnt); //filled with 0.0
  For i := High(fltArr) downto 0 do
    fltArr[i] := MaxCnt*random();
  For i := High(IntArr) downto 0 do
    IntArr[i] := round(fltArr[i]);

  ErgInt := FindMaxInt(IntArr);
  writeln('FindMaxInt ',ErgInt.mpMax,' @ ',ErgInt.mpPos);

  Ergflt := FindMaxflt(fltArr);
  writeln('FindMaxFlt ',Ergflt.mpMax:0:4,' @ ',Ergflt.mpPos);
end.


def
  gcd( 0, 0 ) = error( 'integers.gcd: gcd( 0, 0 ) is undefined' )
  gcd( a, b ) =
    def
      _gcd( a, 0 ) = a
      _gcd( a, b ) = _gcd( b, a%b )

    _gcd( abs(a), abs(b) )


sub max {
    my $max = shift;
    for (@_) { $max = $_ if $_ > $max }
    return $max;
}


with javascript_semantics
?max({1,1234,62,234,12,34,6})
?max({"ant", "antelope", "dog", "cat", "cow", "wolf", "wolverine", "aardvark"})


"1" "1234" "62" "234" "12" "34" "6" stklen tolist
dup "Alphabetic order: " print max print nl

len for
    var i
    i get tonum i set
endfor
"Numeric order: " print max print


window 1, @"Greatest Common Divisor", (0,0,480,270)

local fn gcd( a as short, b as short ) as short
  short result

  if ( b != 0 )
    result = fn gcd( b, a mod b)
  else
    result = abs(a)
  end if
end fn = result

print fn gcd( 6, 9 )

HandleEvents


# Built-in
GcdInt(35, 42);
# 7

# Euclidean algorithm
GcdInteger := function(a, b)
    local c;
    a := AbsInt(a);
    b := AbsInt(b);
    while b > 0 do
        c := a;
        a := b;
        b := RemInt(c, b);
    od;
    return a;
end;

GcdInteger(35, 42);
# 7


: (max 2 4 1 3)               # Return the maximal argument
-> 4
: (apply max (2 4 1 3))       # Apply to a list
-> 4
: (maxi abs (2 -4 -1 3))      # Maximum according to given function
-> -4


maximum = A(lbound(A,1));
do i = lbound(A,1)+1 to hbound(A,1);
  if maximum < A(i) then maximum = A(i);
end;


def gcd (u v)
    u = (abs u)
    v = (abs v)
    cond
       (equal? v 0) u
       else (gcd v (% u v))


'
' Greatest Common Divisor
'
a%=24
b%=112
PRINT "GCD of ";a%;" and ";b%;" is ";@gcd(a%,b%)
'
' Function computes gcd
'
FUNCTION gcd(a%,b%)
  LOCAL t%
  '
  WHILE b%<>0
    t%=a%
    a%=b%
    b%=t% MOD b%
  WEND
  '
  RETURN ABS(a%)
ENDFUNC


/findmax {
  dup 0 get exch    % put the first element underneath the array
  {max} forall      % replace it by the respective larger value if necessary
} def


FUNCTION PBMAIN()
    DIM x AS LONG, y AS LONG, z AS LONG
    RANDOMIZE TIMER

    FOR x = 1 TO 10
        y = INT(RND * 10000)
        z = MAX(y, z)
    NEXT

    ? STR$(z) & " was the highest value"
END FUNCTION


function Get-Maximum ($a) {
    return ($a | Measure-Object -Maximum).Maximum
}


 var n,m,r;
 n = max(argument0,argument1);
 m = min(argument0,argument1);
 while (m != 0)
 {
  r = n mod m;
  n = m;
  m = r;
 }
 return a;


gcd (a, b) = b == 0 ? a : gcd (b, a % b)


Procedure.f Max (Array a.f(1))
   Protected last, i, ret.f

   ret = a(0)
   last = ArraySize(a())
   For i = 1 To last
      If ret < a(i)
         ret = a(i)
      EndIf
   Next

   ProcedureReturn ret
EndProcedure


package main

import "fmt"

func gcd(a, b int) int {
    var bgcd func(a, b, res int) int

    bgcd = func(a, b, res int) int {
	switch {
	case a == b:
	    return res * a
	case a % 2 == 0 && b % 2 == 0:
	    return bgcd(a/2, b/2, 2*res)
	case a % 2 == 0:
	    return bgcd(a/2, b, res)
	case b % 2 == 0:
	    return bgcd(a, b/2, res)
	case a > b:
	    return bgcd(a-b, b, res)
	default:
	    return bgcd(a, b-a, res)
	}
    }

    return bgcd(a, b, 1)
}

func main() {
    type pair struct {
	a int
	b int
    }

    var testdata []pair = []pair{
	pair{33, 77},
	pair{49865, 69811},
    }

    for _, v := range testdata {
	fmt.Printf("gcd(%d, %d) = %d\n", v.a, v.b, gcd(v.a, v.b))
    }
}


[ behead swap witheach max ] is [max] ( [ --> n )


say max 10, 4, 5, -2, 11;
say max <zero one two three four five six seven eight nine>;

# Even when the values and number of values aren't known until runtime
my @list = flat(0..9,'A'..'H').roll((^60).pick).rotor(4,:partial)».join.words;
say @list, ': ', max @list;


def gcdR
gcdR = { m, n -> m = m.abs(); n = n.abs(); n == 0 ? m : m%n == 0 ? n : gcdR(n, m%n) }


functioni FindMax(...) as double
    dim x as integer

    for x = 1 to ParamValCount
        IF ParamVal(x) > Result THEN Result = ParamVal(x)
    next
End functioni

Print FindMax(50, 20, 65, 20, 105)


rascal>import List;
ok

rascal>max([1,2,3,4]);
int: 4


rebol [
    Title: "Maximum Value"
    URL: http://rosettacode.org/wiki/Maximum_Value
]

max: func [
	"Find maximum value in a list."
	values [series!] "List of values."
] [
	first maximum-of values
]

print ["Max of"  mold d: [5 4 3 2 1]  "is"  max d]
print ["Max of"  mold d: [-5 -4 -3 -2 -1]  "is"  max d]


10 INPUT A, B
20 IF A < 0 THEN A = -A
30 IF B < 0 THEN B = -B
40 GOTO 70
50 PRINT A
60 END
70 IF B = 0 THEN GOTO 50
80 TEMP = B
90 B = A MOD TEMP
100 A = TEMP
110 GOTO 70


gcd :: (Integral a) => a -> a -> a
gcd x y = gcd_ (abs x) (abs y)
  where
    gcd_ a 0 = a
    gcd_ a b = gcd_ b (a `rem` b)


Red []
list: [1 2 3 5 4]
print  last sort list


/*REXX program finds the  greatest element  in a list (of the first 25 reversed primes).*/
$ = reverse(2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97)
say 'list of numbers = '  $                      /*show the original list of numbers.   */
big=word($, 1)                                   /*choose an initial biggest number.    */
# = words($);        do j=2  to #                /*traipse through the list,  find max. */
                     big=max(big, word($, j) )   /*use the  MAX  BIF to find the biggie.*/
                     end   /*j*/
say                                              /*stick a fork in it,  we're all done. */
say 'the biggest value in a list of '     #      " numbers is: "     big


FUNCTION gcd(a, b)
   IF(b == 0) THEN
     gcd = ABS(a)
   ELSE
     aa = a
     gcd = b
     DO i = 1, 1E100
       r = ABS(MOD(aa, gcd))
       IF( r == 0 ) RETURN
       aa = gcd
       gcd = r
     ENDDO
   ENDIF
 END


link numbers   # gcd is part of the Icon Programming Library
procedure main(args)
    write(gcd(arg[1], arg[2])) | "Usage: gcd n m")
end


fn main() {
    let nums = [1,2,39,34,20];
    println!("{:?}", nums.iter().max());
    println!("{}", nums.iter().max().unwrap());
}


public static long gcd(long a, long b){
   long factor= Math.min(a, b);
   for(long loop= factor;loop > 1;loop--){
      if(a % loop == 0 && b % loop == 0){
         return loop;
      }
   }
   return 1;
}


def noSweat(list: Int*) = list.max
// Test
assert(noSweat(1, 3, 12, 7) == 12)


(max 1 2 3 4)
(apply max values) ; find max of a list


function gcd(a,b) {
  a = Math.abs(a);
  b = Math.abs(b);

  if (b > a) {
    var temp = a;
    a = b;
    b = temp;
  }

  while (true) {
    a %= b;
    if (a === 0) { return b; }
    b %= a;
    if (b === 0) { return a; }
  }
}


DEFINE gcd == [0 >] [dup rollup rem] while pop.


$ include "seed7_05.s7i";

const func integer: max (in array integer: values) is func
  result
    var integer: max is 0;
  local
    var integer: index is 0;
  begin
    max := values[1];
    for index range 2 to length(values) do
      if values[index] > max then
        max := values[index];
      end if;
    end for;
  end func;

const proc: main is func
  begin
    writeln(max([] (1, 2, 6, 4, 3)));
  end func;


(1 & 2 & 3 & 4 & 20 & 10 & 9 & 8) asVector reduceWith: [:a :b | a max: b] "returns 20"


def recursive_gcd(a; b):
  if b == 0 then a
  else recursive_gcd(b; a % b)
  end ;


julia> gcd(4,12)
4
julia> gcd(6,12)
6
julia> gcd(7,12)
1


while   a = trim(input)     :f(stop)
        max = gt(a,max) a   :(while)
stop    output = max
end


fun max_of_ints [] = raise Empty
  | max_of_ints (x::xs) = foldl Int.max x xs


if let x = [4,3,5,9,2,3].maxElement() {
  print(x) // prints 9
}


tailrec fun gcd(a: Int, b: Int): Int = if (b == 0) kotlin.math.abs(a) else gcd(b, a % b)


[1, 5, 20, 3, 9, 7] ... -> ..=Max&{by: :(), select: :()} -> !OUT::write
// outputs 20

// This is how the Max-collector is implemented in the standard library:
processor Max&{by:, select:}
  @:[];
  sink accumulate
    <?([email protected] <=[]>)
      | ?($(by) <[email protected]>)>  @Max: {max: $(by), result: $(select)};
  end accumulate
  source result
    [email protected] !
  end result
end Max


package require Tcl 8.5

set values {4 3 2 7 8 9}
::tcl::mathfunc::max {*}$values ;# ==> 9


#lang transd

MainModule: {
    _start: (λ
        (textout (max 9 6 2 11 3 4) " ")
        (with v [1, 45, 7, 274, -2, 34]
            (textout (max-element v) " ")
            (textout (max-element-idx v))
    ))
}


> (defun gcd
  "Get the greatest common divisor."
  ((a 0) a)
  ((a b) (gcd b (rem a b))))


'iterative Euclid algorithm
print GCD(-2,16)
end

function GCD(a,b)
    while b
        c = a
        a = b
        b = c mod b
    wend
    GCD = abs(a)
    end function


$$ MODE TUSCRIPT
LOOP n,list="2'4'0'3'1'2'-12"
IF (n==1)          greatest=VALUE(list)
IF (list>greatest) greatest=VALUE(list)
ENDLOOP
PRINT greatest


Push 13, 0, -6, 2, 37, -10, 12         ' Push values on the stack
Print "Maximum value = " ; FUNC(_FNmax(7))
End                                    ' We pushed seven values

_FNmax Param(1)
  Local(3)

  [email protected] = -(2^31)                         ' Set maximum to a tiny value

  For [email protected] = 1 To [email protected]                     ' Get all values from the stack
    [email protected] = Pop()
    If [email protected] > [email protected] THEN [email protected] = [email protected]            ' Change maximum if required
  Next
Return ([email protected])                            ' Return the maximum


max() {
  local m=$1
  shift
  while [ $# -gt 0 ]
  do
    [ "$m" -lt "$1" ] && m=$1
    shift
  done
  echo "$m"
}

max 10 9 11 57 1 12


gcd(x: int, y: int): int
{
	if(y == 0)
		return x;
	return gcd(y, x % y);
}


function gcd x,y
   repeat until y = 0
      put x mod y into z
      put y into x
      put z into y
   end repeat
   return x
end gcd


def max (int<> list)
	decl int max i
	set max list<0>

	for (set i 1) (< i (- (size list) 1)) (inc i)
		if (> list<i> max)
			set max list<i>
		end if
	end for

	return max
end max


Option Explicit

Sub Main()
Dim a
   a = Array(1, 15, 19, 25, 13, 0, -125, 9)
   Debug.Print Max_VBA(a)
End Sub

Function Max_VBA(Arr As Variant) As Long
Dim i As Long, temp As Long
   temp = Arr(LBound(Arr))
   For i = LBound(Arr) + 1 To UBound(Arr)
      If Arr(i) > temp Then temp = Arr(i)
   Next i
   Max_VBA = temp
End Function


to gcd :a :b
  if :b = 0 [output :a]
  output gcd :b  modulo :a :b
end


HAI 1.3

HOW IZ I gcd YR a AN YR b
	a R BIGGR OF a AN PRODUKT OF a AN -1   BTW  absolute value of a
	b R BIGGR OF b AN PRODUKT OF b AN -1   BTW  absolute value of b
	BOTH SAEM a AN b, O RLY?
		YA RLY
			FOUND YR a
		OIC
	BOTH SAEM a AN 0, O RLY?
		YA RLY
			FOUND YR b
		OIC
	BOTH SAEM b AN 0, O RLY?
		YA RLY
			FOUND YR a
		OIC
	BOTH SAEM b AN BIGGR OF a AN b, O RLY?       BTW  make sure a is the larger of (a, b)
		YA RLY
			I HAS A temp ITZ a
			a R b
			b R temp
		OIC

	IM IN YR LOOP
		I HAS A temp ITZ b
		b R MOD OF a AN b
		a R temp
		BOTH SAEM b AN 0, O RLY?
			YA RLY
				FOUND YR a
			OIC
	IM OUTTA YR LOOP
IF U SAY SO

VISIBLE I IZ gcd YR 40902 AN YR 24140 MKAY

KTHXBYE


Function greatest_element(arr)
	tmp_num = 0
	For i = 0 To UBound(arr)
		If i = 0 Then
			tmp_num = arr(i)
		ElseIf arr(i) > tmp_num Then
			tmp_num = arr(i)
		End If
	Next
	greatest_element = tmp_num
End Function

WScript.Echo greatest_element(Array(1,2,3,44,5,6,8))


Public Function ListMax(anArray())
    'return the greatest element in array anArray
    'use LBound and UBound to find its length
    n0 = LBound(anArray)
    n = UBound(anArray)
    theMax = anArray(n0)
    For i = (n0 + 1) To n
        If anArray(i) > theMax Then theMax = anArray(i)
    Next
    ListMax = theMax
End Function

Public Sub ListMaxTest()
    Dim b()
    'test function ListMax
    'fill array b with some numbers:
    b = Array(5992424433449#, 4534344439984#, 551344678, 99800000#)
    'print the greatest element
    Debug.Print "Greatest element is"; ListMax(b())
End Sub


fn max<T>(list []T) T {
    mut max := list[0]
    for i in 1..list.len {
        if list[i] > max {
            max = list[i]
        }
    }
    return max
}
fn main() {
    println('int max: ${max<int>([5,6,4,2,8,3,0,2])}')
    println('float max: ${max<f64>([1e4, 1e5, 1e2, 1e9])}')
}


(*
** MÉTHODE D'EUCLIDE POUR TROUVER LE PLUS GRAND DIVISEUR COMMUN D'UN
** NUMÉRATEUR ET D'UN DÉNOMINATEUR.
*)
PROCÉDURE &PGDC(ENTIER U, ENTIER V) : ENTIER LOCAL U, V
    ENTIER T
    TANT QUE U > 0 FAIRE
        SI U< V ALORS
            T<-U
            U<-V
            V<-T
        FIN SI
        U <- U - V
    BOUCLER
    RÉSULTAT V
FIN PROCÉDURE

PROCÉDURE &DEMO(ENTIER U, ENTIER V) LOCAL U, V
    AFFICHER ['Le PGDC de ',U,'/',U,' est ',U,/] U, V, &PGDC(U,V)
FIN PROCÉDURE

&DEMO(9,12)
&DEMO(6144,8192)
&DEMO(100,5)
&DEMO(7,23)


function gcd(a,b)
	if b ~= 0 then
		return gcd(b, a % b)
	else
		return math.abs(a)
	end
end

function demo(a,b)
	print("GCD of " .. a .. " and " .. b .. " is " .. gcd(a, b))
end

demo(100, 5)
demo(5, 100)
demo(7, 23)


def (best f seq)
  if seq
    ret winner car.seq
      each elem cdr.seq
        if (f elem winner)
          winner <- elem

def (max ... args)
  (best (>) args)


let s => import 'stream';
let a => import 'arrays';

let max list =>
  a.stream list
  -> s.extent 1 >
  -> at 0
  ;


gcd(n,m) where
   z = [% n, m %] fby if x > y then [% x - y, y %] else [% x, y - x%] fi;
   x = hd(z);
   y = hd(tl(z));
   gcd(n, m) = (x asa x*y eq 0) fby eod;
end


function gcd(a: int, b: int): int = (
   if a==0 then b
   else if b==0 then a
   else if a>b then gcd(b, a % b)
   else gcd(a, b % a)
)


include c:\cxpl\codes;                  \include 'code' declarations

def  Tab=$09, LF=$0A, CR=$0D, EOF=$1A;

int  CpuReg, Hand;
char CmdTail($80);
int  I, Max, C;

[\Copy file name on command line, which is in the Program Segment Prefix (PSP)
\ ES=CpuReg(11), to the CmdTail array, which is in our Data Segment = CpuReg(12)
CpuReg:= GetReg;                        \point to copy of CPU registers
Blit(CpuReg(11), $81, CpuReg(12), CmdTail, $7F);
Hand:= FOpen(CmdTail, 0);               \open file for input and get its handle
FSet(Hand, ^I);                         \assign handle to device 3
OpenI(3);                               \initialize file for input

Max:= 0;                                \scan file for longest line
repeat  I:= 0;
        repeat  C:= ChIn(3);
                case C of
                  CR, LF, EOF:  [];     \don't count these characters
                  Tab:  [I:= I+8 & ~7]  \(every 8th column)
                other   I:= I+1;        \count all other characters
        until   C=LF or C=EOF;
        if I > Max then Max:= I;
until   C = EOF;
Text(0, "Longest line = ");  IntOut(0, Max);  CrLf(0);
]


<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
	<xsl:output method="text"/>

	<xsl:template match="/">
		<xsl:for-each select="/*/*">
			<!-- without data-type="number", items are sorted alphabetically -->
			<xsl:sort data-type="number" order="descending"/>
			<xsl:if test="position() = 1">
				<xsl:value-of select="."/>
			</xsl:if>
		</xsl:for-each>
	</xsl:template>
</xsl:stylesheet>


l$ = "1,1234,62,234,12,34,6"

dim n$(1)

n = token(l$, n$(), ", ")

for i = 1 to n
	t$ = n$(i)
	if t$ > m$ then m$ = t$ end if            // or: if t$ > m$ m$ = t$
	if val(t$) > m then m = val(t$) end if	  // or: if val(t$) > m m = val(t$)
next

print "Alphabetic order: ", m$, ", numeric order: ", m


gcd=lambda (u as long, v as long) -> {
           =if(v=0&->abs(u), lambda(v, u mod v))
}
gcd_Iterative= lambda (m as long, n as long) -> {
   while m  {
       let old_m = m
       m = n mod m
       n = old_m
   }
   =abs(n)
}
Module CheckGCD (f){
      Print f(49865, 69811)=9973
      Def ExpType$(x)=Type$(x)
      Print ExpType$(f(49865, 69811))="Long"
}
CheckGCD gcd
CheckGCD gcd_Iterative


program: max
  case: 1
        input: [7,3,5,9,2,6]
        output: 9
  case: 2
        input: [1,5,3,2,7]
        output: 7


function [gcdValue] = greatestcommondivisor(integer1, integer2)
   gcdValue = gcd(integer1, integer2);


/* There is a function gcd(a, b) in Maxima, but one can rewrite it */
gcd2(a, b) := block([a: abs(a), b: abs(b)], while b # 0 do [a, b]: [b, mod(a, b)], a)$

/* both will return 2^97 * 3^48 */
gcd(100!, 6^100), factor;
gcd2(100!, 6^100), factor;


10 PRINT "Values"''
20 LET z=0
30 FOR x=1 TO INT (RND*10)+1
40 LET y=RND*10-5
50 PRINT y
60 LET z=(y AND y>z)+(z AND y<z)
70 NEXT x
80 PRINT '"Max. value = ";z


fn gcdIter a b =
(
    while b > 0 do
    (
        c = mod a b
        a = b
        b = c
    )
    abs a
)


:- module gcd.

:- interface.
:- import_module integer.

:- func gcd(integer, integer) = integer.

:- implementation.

:- pragma memo(gcd/2).
gcd(A, B) = (if B = integer(0) then A else gcd(B, A mod B)).


// Greatest common divisor
00 0E  GCD:   ENT  R0
01 1E         ENT  R1
02 21  Again: R2 = R1
03 10  Loop:  R1 = R0
04 02         R0 = R2
05 2D  Minus: DEC  R2
06 8A         JZ   Stop
07 1D         DEC  R1
08 C5         JNZ  Minus
09 83         JZ   Loop
0A 1D  Stop:  DEC  R1
0B C2         JNZ  Again
0C 80         JZ   GCD   // Display GCD in R0


gcd = function(a, b)
    while b
        temp = b
        b = a % b
        a = temp
    end while
    return abs(a)
end function

print gcd(18,12)


function var int: gcd(int:a2,int:b2) =
  let {
    int:a1 = max(a2,b2);
    int:b1 = min(a2,b2);
    array[0..a1,0..b1] of var int: gcd;
    constraint forall(a in 0..a1)(
      forall(b in 0..b1)(
        gcd[a,b] ==
        if (b == 0) then
          a
        else
          gcd[b, a mod b]
        endif
      )
    )
  } in gcd[a1,b1];

var int: gcd1 = gcd(8,12);
solve satisfy;
output [show(gcd1),"\n"];


gcd:
  # a0 and a1 are the two integer parameters
  # return value is in v0
  move $t0, $a0
  move $t1, $a1
loop:
  beq $t1, $0, done
  div $t0, $t1
  move $t0, $t1
  mfhi $t1
  j loop
done:
  move $v0, $t0
  jr $ra


ИПA	ИПB	/	П9	КИП9	ИПA	ИПB	ПA	ИП9	*
-	ПB	x=0	00	ИПA	С/П


fun gcd (a, 0) = a
      | (0, b) = b
      | (a, b) where (a < b)
               = gcd (a, b rem a)
      | (a, b) = gcd (b, a rem b)


MODULE ggTkgV;

FROM    InOut           IMPORT  ReadCard, WriteCard, WriteLn, WriteString, WriteBf;

VAR   x, y, u, v        : CARDINAL;

BEGIN
  WriteString ("x = ");         WriteBf;        ReadCard (x);
  WriteString ("y = ");         WriteBf;        ReadCard (y);
  u := x;
  v := y;
  WHILE  x # y  DO
    (*  ggT (x, y) = ggT (x0, y0), x * v + y * u = 2 * x0 * y0          *)
    IF  x > y  THEN
      x := x - y;
      u := u + v
    ELSE
      y := y - x;
      v := v + u
    END
  END;
  WriteString ("ggT =");        WriteCard (x, 6);               WriteLn;
  WriteString ("kgV =");        WriteCard ((u+v) DIV 2, 6);     WriteLn;
  WriteString ("u =");          WriteCard (u, 6);               WriteLn;
  WriteString ("v =");          WriteCard (v , 6);              WriteLn
END ggTkgV.


MODULE GCD EXPORTS Main;

IMPORT IO, Fmt;

PROCEDURE GCD(a, b: CARDINAL): CARDINAL =
  BEGIN
    IF a = 0 THEN
      RETURN b;
    ELSIF b = 0 THEN
      RETURN a;
    ELSIF a > b THEN
      RETURN GCD(b, a MOD b);
    ELSE
      RETURN GCD(a, b MOD a);
    END;
  END GCD;

BEGIN
  IO.Put("GCD of 100, 5 is " & Fmt.Int(GCD(100, 5)) & "\n");
  IO.Put("GCD of 5, 100 is " & Fmt.Int(GCD(5, 100)) & "\n");
  IO.Put("GCD of 7, 23 is " & Fmt.Int(GCD(7, 23)) & "\n");
END GCD.


GCD(A,B)
 QUIT:((A/1)'=(A\1))!((B/1)'=(B\1)) 0
 SET:A<0 A=-A
 SET:B<0 B=-B
 IF B'=0
 FOR  SET T=A#B,A=B,B=T QUIT:B=0 ;ARGUEMENTLESS FOR NEEDS TWO SPACES
 QUIT A


DROP FUNCTION IF EXISTS gcd;
DELIMITER |

CREATE FUNCTION gcd(x INT, y INT)
RETURNS INT
BEGIN
  SET @dividend=GREATEST(ABS(x),ABS(y));
  SET @divisor=LEAST(ABS(x),ABS(y));
  IF @divisor=0 THEN
    RETURN @dividend;
  END IF;
  SET @gcd=NULL;
  SELECT gcd INTO @gcd FROM
    (SELECT @tmp:=@dividend,
            @dividend:=@divisor AS gcd,
            @divisor:=@tmp % @divisor AS remainder
       FROM mysql.help_relation WHERE @divisor>0) AS x
    WHERE remainder=0;
  RETURN @gcd;
END;|

DELIMITER ;

SELECT gcd(12345, 9876);


def gcd(a, b)
	factor = a.min(b)

	for loop in range(factor, 2)
		if (a % loop = 0) and (b % loop = 0)
			return loop
		end
	end

	return 1
end


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

numeric digits 2000
runSample(arg)
return

-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- Euclid's algorithm - iterative implementation
method gcdEucidI(a_, b_) public static
  loop while b_ > 0
    c_ = a_ // b_
    a_ = b_
    b_ = c_
    end
  return a_

-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- Euclid's algorithm - recursive implementation
method gcdEucidR(a_, b_) public static
  if b_ \= 0 then a_ = gcdEucidR(b_, a_ // b_)
  return a_

-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method runSample(arg) private static
  -- pairs of numbers, each number in the pair separated by a colon, each pair separated by a comma
  parse arg tests
  if tests = '' then
    tests = '0:0, 6:4, 7:21, 12:36, 33:77, 41:47, 99:51, 100:5, 7:23, 1989:867, 12345:9876, 40902:24140, 49865:69811, 137438691328:2305843008139952128'

  -- most of what follows is for formatting
  xiterate = 0
  xrecurse = 0
  ll_ = 0
  lr_ = 0
  lgi = 0
  lgr = 0
  loop i_ = 1 until tests = ''
    xiterate[0] = i_
    xrecurse[0] = i_
    parse tests pair ',' tests
    parse pair l_ ':' r_ .

    -- get the GCDs
    gcdi = gcdEucidI(l_, r_)
    gcdr = gcdEucidR(l_, r_)

    xiterate[i_] = l_ r_ gcdi
    xrecurse[i_] = l_ r_ gcdr
    ll_ = ll_.max(l_.strip.length)
    lr_ = lr_.max(r_.strip.length)
    lgi = lgi.max(gcdi.strip.length)
    lgr = lgr.max(gcdr.strip.length)
    end i_
  -- save formatter sizes in stems
  xiterate[-1] = ll_ lr_ lgi
  xrecurse[-1] = ll_ lr_ lgr

  -- present results
  showResults(xiterate, 'Euclid''s algorithm - iterative')
  showResults(xrecurse, 'Euclid''s algorithm - recursive')
  say
  if verifyResults(xiterate, xrecurse) then
    say 'Success: Results of iterative and recursive methods match'
  else
    say 'Error:   Results of iterative and recursive methods do not match'
  say
  return

-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method showResults(stem, title) public static
  say
  say title
  parse stem[-1] ll lr lg
  loop v_ = 1 to stem[0]
    parse stem[v_] lv rv gcd .
    say lv.right(ll)',' rv.right(lr) ':' gcd.right(lg)
    end v_
  return

-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method verifyResults(stem1, stem2) public static returns boolean
  if stem1[0] \= stem2[0] then signal BadArgumentException
  T = (1 == 1)
  F = \T
  verified = T
  loop i_ = 1 to stem1[0]
    if stem1[i_] \= stem2[i_] then do
      verified = F
      leave i_
      end
    end i_
  return verified


func gcd_recursive*(u, v: SomeSignedInt): int64 =
    if u mod v != 0:
        result = gcd_recursive(v, u mod v)
    else:
        result = abs(v)

when isMainModule:
  import strformat
  let (x, y) = (49865, 69811)
  echo &"gcd({x}, {y}) = {gcd_recursive(49865, 69811)}"


MODULE GCD;
(* Greatest Common Divisor *)
IMPORT
  Out;

  PROCEDURE Gcd(a,b: LONGINT):LONGINT;
  VAR
    r: LONGINT;
  BEGIN
    LOOP
      r := a MOD b;
      IF r = 0 THEN RETURN b END;
      a := b;b := r
    END
  END Gcd;
BEGIN
  Out.String("GCD of    12 and     8 : ");Out.LongInt(Gcd(12,8),4);Out.Ln;
  Out.String("GCD of   100 and     5 : ");Out.LongInt(Gcd(100,5),4);Out.Ln;
  Out.String("GCD of     7 and    23 : ");Out.LongInt(Gcd(7,23),4);Out.Ln;
  Out.String("GCD of    24 and  -112 : ");Out.LongInt(Gcd(12,8),4);Out.Ln;
  Out.String("GCD of 40902 and 24140 : ");Out.LongInt(Gcd(40902,24140),4);Out.Ln
END GCD.


bundle Default {
  class GDC {
    function : Main(args : String[]), Nil {
      for(x := 1; x < 36; x += 1;) {
        IO.Console->GetInstance()->Print("GCD of ")->Print(36)->Print(" and ")->Print(x)->Print(" is ")->PrintLine(GDC(36, x));
      };
    }

    function : native : GDC(a : Int, b : Int), Int {
      t : Int;

      if(a > b) {
        t := b;  b := a;  a := t;
      };

      while (b <> 0) {
        t := a % b;  a := b;  b := t;
      };

      return a;
    }
  }
}


let rec gcd a b =
  if      a = 0 then b
  else if b = 0 then a
  else if a > b then gcd b (a mod b)
  else               gcd a (b mod a)


#include <order/interpreter.h>

#define ORDER_PP_DEF_8gcd ORDER_PP_FN( \
8fn(8U, 8V,                            \
    8if(8isnt_0(8V), 8gcd(8V, 8remainder(8U, 8V)), 8U)))
// No support for negative numbers


declare
  fun {UnsafeGCD A B}
     if B == 0 then
        A
     else
        {UnsafeGCD B A mod B}
     end
  end

  fun {GCD A B}
     if A == 0 andthen B == 0 then
        raise undefined(gcd 0 0) end
     else
        {UnsafeGCD {Abs A} {Abs B}}
     end
  end
in
  {Show {GCD 456 ~632}}


PROGRAM EXRECURGCD.PAS;

{$IFDEF FPC}
    {$mode objfpc}{$H+}{$J-}{R+}
{$ELSE}
    {$APPTYPE CONSOLE}
{$ENDIF}

(*)
    Free Pascal Compiler version 3.2.0 [2020/06/14] for x86_64
    The free and readable alternative at C/C++ speeds
    compiles natively to almost any platform, including raspberry PI
(*)

FUNCTION gcd_recursive(u, v: longint): longint;

    BEGIN
        IF ( v = 0 ) THEN Exit ( u ) ;
        result := gcd_recursive ( v, u MOD v ) ;
    END;

BEGIN

    WriteLn ( gcd_recursive ( 231, 7 ) ) ;

END.


function gcd(object u, atom v=0)
atom t
    if sequence(u) then
        v = u[1]                        -- (for the typecheck)
        t = floor(abs(v))
        for i=2 to length(u) do
            v = u[i]                    -- (for the typecheck)
            t = gcd(t,v)
        end for
        return t
    end if
    u = floor(abs(u))
    v = floor(abs(v))
    while v do
        t = u
        u = v
        v = remainder(t, v)
    end while
    return u
end function


function gcdIter($n, $m) {
    while(true) {
        if($n == $m) {
            return $m;
        }
        if($n > $m) {
            $n -= $m;
        } else {
            $m -= $n;
        }
    }
}


(de gcd (A B)
   (until (=0 B)
      (let M (% A B)
         (setq A B B M) ) )
   (abs A) )


GCD: procedure (a, b) returns (fixed binary (31)) recursive;
   declare (a, b) fixed binary (31);

   if b = 0 then return (a);

   return (GCD (b, mod(a, b)) );

end GCD;


/gcd {
{
    {0 gt} {dup rup mod} {pop exit} ifte
} loop
}.


function Get-GCD ($x, $y)
{
  if ($x -eq $y) { return $y }
  if ($x -gt $y) {
    $a = $x
    $b = $y
  }
  else {
    $a = $y
    $b = $x
  }
  while ($a % $b -ne 0) {
    $tmp = $a % $b
    $a = $b
    $b = $tmp
  }
  return $b
}


gcd(X, 0, X):- !.
gcd(0, X, X):- !.
gcd(X, Y, D):- X > Y, !, Z is X mod Y, gcd(Y, Z, D).
gcd(X, Y, D):- Z is Y mod X, gcd(X, Z, D).


Procedure GCD(x, y)
  Protected r
  While y <> 0
    r = x % y
    x = y
    y = r
  Wend
  ProcedureReturn y
EndProcedure


data Iterate = f => FoldNat <const id, g => $g . $f>

data Sub = Iterate Pred
data IsZero = <const True, const False> . UnNat

data Eq = FoldNat
          <
              const IsZero,
              eq => n => IfThenElse (IsZero $n)
                         False
                         ($eq (Pred $n))
          >

data step = gcd => n => m =>
                    IfThenElse (Eq $m $n)
                        (Pair $m $n)
                        (IfThenElse (Compare Leq $n $m)
                            ($gcd (Sub $m $n) $m)
                            ($gcd (Sub $n $m) $n))

data gcd = Iterate (gcd => uncurry (step (curry $gcd)))


  [ [ dup while
      tuck mod again ]
    drop abs ]         is gcd ( n n --> n )


(define gcd
  A 0 -> A
  A B -> (gcd B (MOD A B)))


"%gcd%" <- function(u, v) {
  ifelse(u %% v != 0, v %gcd% (u%%v), v)
}


sub gcd (Int $a is copy, Int $b is copy) {
   $a & $b == 0 and fail;
   ($a, $b) = ($b, $a % $b) while $b;
   return abs $a;
}


public int gcd_iterative(int a, b){
	if(a == 0) return b;
	while(b != 0){
		if(a > b) a -= b;
		else b -= a;}
	return a;
}


define gcd use $u, $v
   $v 0 > if
      $u $v %   $v  gcd
   else
      $u abs

24140 40902 gcd


gcd: func [
    {Returns the greatest common divisor of m and n.}
    m [integer!]
    n [integer!]
    /local k
] [
    ; Euclid's algorithm
    while [n > 0] [
        k: m
        m: n
        n: k // m
    ]
    m
]


: gcd ( ab-n ) [ tuck mod dup ] while drop ;


/*REXX program calculates the  GCD (Greatest Common Divisor)  of any number of integers.*/
numeric digits 2000                              /*handle up to 2k decimal dig integers.*/
call gcd 0 0            ;    call gcd 55 0     ;       call gcd 0    66
call gcd 7,21           ;    call gcd 41,47    ;       call gcd 99 , 51
call gcd 24, -8         ;    call gcd -36, 9   ;       call gcd -54, -6
call gcd 14 0 7         ;    call gcd 14 7 0   ;       call gcd 0  14 7
call gcd 15 10 20 30 55 ;    call gcd 137438691328  2305843008139952128 /*◄──2 perfect#s*/
exit                                             /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
gcd: procedure;  $=;              do i=1 for  arg();  $=$ arg(i);  end       /*arg list.*/
     parse var $ x z .;  if x=0  then x=z;   x=abs(x)                        /* 0 case? */

        do j=2  to words($);   y=abs(word($,j));       if y=0  then iterate  /*is zero? */
              do until _==0;  _=x//y;  x=y;  y=_;  end /* ◄────────── the heavy lifting.*/
        end   /*j*/

     say 'GCD (Greatest Common Divisor) of '   translate(space($),",",' ')   "  is  "   x
     return x


see gcd (24, 32)
func gcd gcd, b
     while b
           c   = gcd
           gcd = b
           b   = c % b
     end
     return gcd


print abs(gcd(-220,160))
function gcd(gcd,b)
    while b
        c   = gcd
        gcd = b
        b   = c mod b
    wend
end function


extern crate num;
use num::integer::gcd;


@function gcd($a,$b) {
	@while $b > 0 {
		$c: $a % $b;
		$a: $b;
		$b: $c;
	}
	@return $a;
}


class MATH is

  gcd_iter(u, v:INT):INT is
    loop while!( v.bool );
      t ::= u; u := v; v := t % v;
    end;
    return u.abs;
  end;

  gcd(u, v:INT):INT is
    if v.bool then return gcd(v, u%v); end;
    return u.abs;
  end;

  private swap(inout a, inout b:INT) is
    t ::= a;
    a := b;
    b := t;
  end;

  gcd_bin(u, v:INT):INT is
    t:INT;

    u := u.abs; v := v.abs;
    if u < v then swap(inout u, inout v); end;
    if v = 0 then return u; end;
    k ::= 1;
    loop while!( u.is_even and v.is_even );
      u := u / 2; v := v / 2;
      k := k * 2;
    end;
    if u.is_even then
      t := -v;
    else
      t := u;
    end;
    loop while!( t.bool );
      loop while!( t.is_even );
        t := t / 2;
      end;
      if t > 0 then
        u := t;
      else
        v := -t;
      end;
      t := u - v;
    end;
    return u * k;
  end;

end;


rem - return p mod q
function mod(p, q = integer) = integer
end = p - q * (p / q)

rem - return greatest common divisor of x and y
function gcd(x, y = integer) = integer
  var r, temp = integer
  if x < y then
    begin
      temp = x
      x = y
      y = temp
    end
  r = mod(x, y)
  while r <> 0 do
    begin
      x = y
      y = r
      r = mod(x, y)
    end
end =  y

rem - exercise the function

print "The GCD of 21 and 35 is"; gcd(21,35)
print "The GCD of 23 and 35 is"; gcd(23,35)
print "The GCD of 1071 and 1029 is"; gcd(1071, 1029)
print "The GCD of 3528 and 3780 is"; gcd(3528,3780)

end


def gcd(a: Int, b: Int): Int = if (b == 0) a.abs else gcd(b, a % b)


(define (gcd a b)
  (if (= b 0)
      a
      (gcd b (modulo a b))))


#! /bin/sed -nf

# gcd.sed Copyright (c) 2010        by Paweł Zuzelski <[email protected]>
# dc.sed  Copyright (c) 1995 - 1997 by Greg Ubben <[email protected]>

# usage:
#
#     echo N M | ./gcd.sed
#
# Computes the greatest common divisor of N and M integers using euclidean
# algorithm.

s/^/|P|K0|I10|O10|?~/

s/$/ [lalb%sclbsalcsblb0<F]sF sasblFxlap/

:next
s/|?./|?/
s/|?#[	 -}]*/|?/
/|?!*[lLsS;:<>=]\{0,1\}$/N
/|?!*[-+*/%^<>=]/b binop
/^|.*|?[dpPfQXZvxkiosStT;:]/b binop
/|?[_0-9A-F.]/b number
/|?\[/b string
/|?l/b load
/|?L/b Load
/|?[sS]/b save
/|?c/ s/[^|]*//
/|?d/ s/[^~]*~/&&/
/|?f/ s//&[pSbz0<aLb]dSaxsaLa/
/|?x/ s/\([^~]*~\)\(.*|?x\)~*/\2\1/
/|?[KIO]/ s/.*|\([KIO]\)\([^|]*\).*|?\1/\2~&/
/|?T/ s/\.*0*~/~/
#  a slow, non-stackable array implementation in dc, just for completeness
#  A fast, stackable, associative array implementation could be done in sed
#  (format: {key}value{key}value...), but would be longer, like load & save.
/|?;/ s/|?;\([^{}]\)/|?~[s}s{L{s}q]S}[S}l\1L}1-d0>}s\1L\1l{xS\1]dS{xL}/
/|?:/ s/|?:\([^{}]\)/|?~[s}L{s}L{s}L}s\1q]S}S}S{[L}1-d0>}S}l\1s\1L\1l{xS\1]dS{x/
/|?[ ~	cdfxKIOT]/b next
/|?\n/b next
/|?[pP]/b print
/|?k/ s/^\([0-9]\{1,3\}\)\([.~].*|K\)[^|]*/\2\1/
/|?i/ s/^\(-\{0,1\}[0-9]*\.\{0,1\}[0-9]\{1,\}\)\(~.*|I\)[^|]*/\2\1/
/|?o/ s/^\(-\{0,1\}[1-9][0-9]*\.\{0,1\}[0-9]*\)\(~.*|O\)[^|]*/\2\1/
/|?[kio]/b pop
/|?t/b trunc
/|??/b input
/|?Q/b break
/|?q/b quit
h
/|?[XZz]/b count
/|?v/b sqrt
s/.*|?\([^Y]\).*/\1 is unimplemented/
s/\n/\\n/g
l
g
b next

:print
/^-\{0,1\}[0-9]*\.\{0,1\}[0-9]\{1,\}~.*|?p/!b Print
/|O10|/b Print

#  Print a number in a non-decimal output base.  Uses registers a,b,c,d.
#  Handles fractional output bases (O<-1 or O>=1), unlike other dc's.
#  Converts the fraction correctly on negative output bases, unlike
#  UNIX dc.  Also scales the fraction more accurately than UNIX dc.
#
s,|?p,&KSa0kd[[-]Psa0la-]Sad0>a[0P]sad0=a[A*2+]saOtd0>a1-ZSd[[[[ ]P]sclb1\
!=cSbLdlbtZ[[[-]P0lb-sb]sclb0>c1+]sclb0!<c[0P1+dld>c]scdld>cscSdLbP]q]Sb\
[t[1P1-d0<c]scd0<c]ScO_1>bO1!<cO[16]<bOX0<b[[q]sc[dSbdA>c[A]sbdA=c[B]sbd\
B=c[C]sbdC=c[D]sbdD=c[E]sbdE=c[F]sb]xscLbP]~Sd[dtdZOZ+k1O/Tdsb[.5]*[.1]O\
X^*dZkdXK-1+ktsc0kdSb-[Lbdlb*lc+tdSbO*-lb0!=aldx]dsaxLbsb]sad1!>a[[.]POX\
+sb1[SbO*dtdldx-LbO*dZlb!<a]dsax]sadXd0<asbsasaLasbLbscLcsdLdsdLdLak[]pP,
b next

:Print
/|?p/s/[^~]*/&\
~&/
s/\(.*|P\)\([^|]*\)/\
\2\1/
s/\([^~]*\)\n\([^~]*\)\(.*|P\)/\1\3\2/
h
s/~.*//
/./{ s/.//; p; }
#  Just s/.//p would work if we knew we were running under the -n option.
#  Using l vs p would kind of do \ continuations, but would break strings.
g

:pop
s/[^~]*~//
b next

:load
s/\(.*|?.\)\(.\)/\20~\1/
s/^\(.\)0\(.*|r\1\([^~|]*\)~\)/\1\3\2/
s/.//
b next

:Load
s/\(.*|?.\)\(.\)/\2\1/
s/^\(.\)\(.*|r\1\)\([^~|]*~\)/|\3\2/
/^|/!i\
register empty
s/.//
b next

:save
s/\(.*|?.\)\(.\)/\2\1/
/^\(.\).*|r\1/ !s/\(.\).*|/&r\1|/
/|?S/ s/\(.\).*|r\1/&~/
s/\(.\)\([^~]*~\)\(.*|r\1\)[^~|]*~\{0,1\}/\3\2/
b next

:quit
t quit
s/|?[^~]*~[^~]*~/|?q/
t next
#  Really should be using the -n option to avoid printing a final newline.
s/.*|P\([^|]*\).*/\1/
q

:break
s/[0-9]*/&;987654321009;/
:break1
s/^\([^;]*\)\([1-9]\)\(0*\)\([^1]*\2\(.\)[^;]*\3\(9*\).*|?.\)[^~]*~/\1\5\6\4/
t break1
b pop

:input
N
s/|??\(.*\)\(\n.*\)/|?\2~\1/
b next

:count
/|?Z/ s/~.*//
/^-\{0,1\}[0-9]*\.\{0,1\}[0-9]\{1,\}$/ s/[-.0]*\([^.]*\)\.*/\1/
/|?X/ s/-*[0-9A-F]*\.*\([0-9A-F]*\).*/\1/
s/|.*//
/~/ s/[^~]//g

s/./a/g
:count1
	s/a\{10\}/b/g
	s/b*a*/&a9876543210;/
	s/a.\{9\}\(.\).*;/\1/
	y/b/a/
/a/b count1
G
/|?z/ s/\n/&~/
s/\n[^~]*//
b next

:trunc
#  for efficiency, doesn't pad with 0s, so 10k 2 5/ returns just .40
#  The X* here and in a couple other places works around a SunOS 4.x sed bug.
s/\([^.~]*\.*\)\(.*|K\([^|]*\)\)/\3;9876543210009909:\1,\2/
:trunc1
	s/^\([^;]*\)\([1-9]\)\(0*\)\([^1]*\2\(.\)[^:]*X*\3\(9*\)[^,]*\),\([0-9]\)/\1\5\6\4\7,/
t trunc1
s/[^:]*:\([^,]*\)[^~]*/\1/
b normal

:number
s/\(.*|?\)\(_\{0,1\}[0-9A-F]*\.\{0,1\}[0-9A-F]*\)/\2~\1~/
s/^_/-/
/^[^A-F~]*~.*|I10|/b normal
/^[-0.]*~/b normal
s:\([^.~]*\)\.*\([^~]*\):[Ilb^lbk/,\1\2~0A1B2C3D4E5F1=11223344556677889900;.\2:
:digit
    s/^\([^,]*\),\(-*\)\([0-F]\)\([^;]*\(.\)\3[^1;]*\(1*\)\)/I*+\1\2\6\5~,\2\4/
t digit
s:...\([^/]*.\)\([^,]*\)[^.]*\(.*|?.\):\2\3KSb[99]k\1]SaSaXSbLalb0<aLakLbktLbk:
b next

:string
/|?[^]]*$/N
s/\(|?[^]]*\)\[\([^]]*\)]/\1|{\2|}/
/|?\[/b string
s/\(.*|?\)|{\(.*\)|}/\2~\1[/
s/|{/[/g
s/|}/]/g
b next

:binop
/^[^~|]*~[^|]/ !i\
stack empty
//!b next
/^-\{0,1\}[0-9]*\.\{0,1\}[0-9]\{1,\}~/ !s/[^~]*\(.*|?!*[^!=<>]\)/0\1/
/^[^~]*~-\{0,1\}[0-9]*\.\{0,1\}[0-9]\{1,\}~/ !s/~[^~]*\(.*|?!*[^!=<>]\)/~0\1/
h
/|?\*/b mul
/|?\//b div
/|?%/b rem
/|?^/b exp

/|?[+-]/ s/^\(-*\)\([^~]*~\)\(-*\)\([^~]*~\).*|?\(-\{0,1\}\).*/\2\4s\3o\1\3\5/
s/\([^.~]*\)\([^~]*~[^.~]*\)\(.*\)/<\1,\2,\3|=-~.0,123456789<></
/^<\([^,]*,[^~]*\)\.*0*~\1\.*0*~/ s/</=/
:cmp1
	s/^\(<[^,]*\)\([0-9]\),\([^,]*\)\([0-9]\),/\1,\2\3,\4/
t cmp1
/^<\([^~]*\)\([^~]\)[^~]*~\1\(.\).*|=.*\3.*\2/ s/</>/
/|?/{
	s/^\([<>]\)\(-[^~]*~-.*\1\)\(.\)/\3\2/
	s/^\(.\)\(.*|?!*\)\1/\2!\1/
	s/|?![^!]\(.\)/&l\1x/
	s/[^~]*~[^~]*~\(.*|?\)!*.\(.*\)|=.*/\1\2/
	b next
}
s/\(-*\)\1|=.*/;9876543210;9876543210/
/o-/ s/;9876543210/;0123456789/
s/^>\([^~]*~\)\([^~]*~\)s\(-*\)\(-*o\3\(-*\)\)/>\2\1s\5\4/

s/,\([0-9]*\)\.*\([^,]*\),\([0-9]*\)\.*\([0-9]*\)/\1,\2\3.,\4;0/
:right1
	s/,\([0-9]\)\([^,]*\),;*\([0-9]\)\([0-9]*\);*0*/\1,\2\3,\4;0/
t right1
s/.\([^,]*\),~\(.*\);0~s\(-*\)o-*/\1~\30\2~/

:addsub1
	s/\(.\{0,1\}\)\(~[^,]*\)\([0-9]\)\(\.*\),\([^;]*\)\(;\([^;]*\(\3[^;]*\)\).*X*\1\(.*\)\)/\2,\4\5\9\8\7\6/
	s/,\([^~]*~\).\{10\}\(.\)[^;]\{0,9\}\([^;]\{0,1\}\)[^;]*/,\2\1\3/
#	  could be done in one s/// if we could have >9 back-refs...
/^~.*~;/!b addsub1

:endbin
s/.\([^,]*\),\([0-9.]*\).*/\1\2/
G
s/\n[^~]*~[^~]*//

:normal
s/^\(-*\)0*\([0-9.]*[0-9]\)[^~]*/\1\2/
s/^[^1-9~]*~/0~/
b next

:mul
s/\(-*\)\([0-9]*\)\.*\([0-9]*\)~\(-*\)\([0-9]*\)\.*\([0-9]*\).*|K\([^|]*\).*/\1\4\2\5.!\3\6,|\2<\3~\5>\6:\7;9876543210009909/

:mul1
    s/![0-9]\([^<]*\)<\([0-9]\{0,1\}\)\([^>]*\)>\([0-9]\{0,1\}\)/0!\1\2<\3\4>/
    /![0-9]/ s/\(:[^;]*\)\([1-9]\)\(0*\)\([^0]*\2\(.\).*X*\3\(9*\)\)/\1\5\6\4/
/<~[^>]*>:0*;/!t mul1

s/\(-*\)\1\([^>]*\).*/;\2^>:9876543210aaaaaaaaa/

:mul2
    s/\([0-9]~*\)^/^\1/
    s/<\([0-9]*\)\(.*[~^]\)\([0-9]*\)>/\1<\2>\3/

    :mul3
	s/>\([0-9]\)\(.*\1.\{9\}\(a*\)\)/\1>\2;9\38\37\36\35\34\33\32\31\30/
	s/\(;[^<]*\)\([0-9]\)<\([^;]*\).*\2[0-9]*\(.*\)/\4\1<\2\3/
	s/a[0-9]/a/g
	s/a\{10\}/b/g
	s/b\{10\}/c/g
    /|0*[1-9][^>]*>0*[1-9]/b mul3

    s/;/a9876543210;/
    s/a.\{9\}\(.\)[^;]*\([^,]*\)[0-9]\([.!]*\),/\2,\1\3/
    y/cb/ba/
/|<^/!b mul2
b endbin

:div
#  CDDET
/^[-.0]*[1-9]/ !i\
divide by 0
//!b pop
s/\(-*\)\([0-9]*\)\.*\([^~]*~-*\)\([0-9]*\)\.*\([^~]*\)/\2.\3\1;0\4.\5;0/
:div1
	s/^\.0\([^.]*\)\.;*\([0-9]\)\([0-9]*\);*0*/.\1\2.\3;0/
	s/^\([^.]*\)\([0-9]\)\.\([^;]*;\)0*\([0-9]*\)\([0-9]\)\./\1.\2\30\4.\5/
t div1
s/~\(-*\)\1\(-*\);0*\([^;]*[0-9]\)[^~]*/~123456789743222111~\2\3/
s/\(.\(.\)[^~]*\)[^9]*\2.\{8\}\(.\)[^~]*/\3~\1/
s,|?.,&SaSadSaKdlaZ+LaX-1+[sb1]Sbd1>bkLatsbLa[dSa2lbla*-*dLa!=a]dSaxsakLasbLb*t,
b next

:rem
s,|?%,&Sadla/LaKSa[999]k*Lak-,
b next

:exp
#  This decimal method is just a little faster than the binary method done
#  totally in dc:  1LaKLb [kdSb*LbK]Sb [[.5]*d0ktdSa<bkd*KLad1<a]Sa d1<a kk*
/^[^~]*\./i\
fraction in exponent ignored
s,[^-0-9].*,;9d**dd*8*d*d7dd**d*6d**d5d*d*4*d3d*2lbd**1lb*0,
:exp1
	s/\([0-9]\);\(.*\1\([d*]*\)[^l]*\([^*]*\)\(\**\)\)/;dd*d**d*\4\3\5\2/
t exp1
G
s,-*.\{9\}\([^9]*\)[^0]*0.\(.*|?.\),\2~saSaKdsaLb0kLbkK*+k1\1LaktsbkLax,
s,|?.,&SadSbdXSaZla-SbKLaLadSb[0Lb-d1lb-*d+K+0kkSb[1Lb/]q]Sa0>a[dk]sadK<a[Lb],
b next

:sqrt
#  first square root using sed:  8k2v at 1:30am Dec 17, 1996
/^-/i\
square root of negative number
/^[-0]/b next
s/~.*//
/^\./ s/0\([0-9]\)/\1/g
/^\./ !s/[0-9][0-9]/7/g
G
s/\n/~/
s,|?.,&K1+k KSbSb[dk]SadXdK<asadlb/lb+[.5]*[sbdlb/lb+[.5]*dlb>a]dsaxsasaLbsaLatLbk K1-kt,
b next

#  END OF GSU dc.sed


const func integer: gcd (in var integer: a, in var integer: b) is func
  result
    var integer: gcd is 0;
  local
    var integer: help is 0;
  begin
    while a <> 0 do
      help := b rem a;
      b := a;
      a := help;
    end while;
    gcd := b;
  end func;


gcd(a, b) :=
		a when b = 0
	else
		gcd(b, a mod b);


a := 33; b := 77;
print(" the gcd of",a," and ",b," is ",gcd(a,b));

c := 49865; d := 69811;
print(" the gcd of",c," and ",d," is ",gcd(c,d));

proc gcd (u, v);
  return if v = 0 then abs u else gcd (v, u mod v) end;
end;


BEGIN
    INTEGER PROCEDURE GCD(a, b); INTEGER a, b;
    BEGIN
        IF a = 0 THEN a := b
        ELSE
            WHILE 0 < b DO BEGIN INTEGER i;
                i := MOD(a, b); a := b; b := i;
            END;
        GCD := a
    END;

    INTEGER a, b;
    !outint(SYSOUT.IMAGE.MAIN.LENGTH, 0);!OUTIMAGE;!OUTIMAGE;
    !SYSOUT.IMAGE :- BLANKS(132);  ! this may or may not work;
    FOR b := 1 STEP 5 UNTIL 37 DO BEGIN
        FOR a := 0 STEP 2 UNTIL 21 DO BEGIN
            OUTTEXT("  ("); OUTINT(a, 0);
            OUTCHAR(','); OUTINT(b, 2);
            OUTCHAR(')'); OUTINT(GCD(a, b), 3);
        END;
        OUTIMAGE
    END
END


	define('gcd(i,j)')	:(gcd_end)
gcd	?eq(i,0)	:s(freturn)
	?eq(j,0)	:s(freturn)

loop	gcd = remdr(i,j)
	gcd = ?eq(gcd,0) j	:s(return)
	i = j
	j = gcd			:(loop)
gcd_end

	output = gcd(1071,1029)
end


function factors(n) {
	var f = {};

	for var i = 2; n > 1; i++ {
		while n % i == 0 {
			n /= i;
			f[i] = f[i] != nil ? f[i] + 1 : 1;
		}
	}

	return f;
}

function GCD(n, k) {
	let f1 = factors(n);
	let f2 = factors(k);

	let fs = map(f1, function(factor, multiplicity) {
		let m = f2[factor];
		return m == nil ? 0 : min(m, multiplicity);
	});

	let rfs = {};
	foreach(fs, function(k, v) {
		rfs[sizeof rfs] = pow(k, v);
	});

	return reduce(rfs, 1, function(x, y) { return x * y; });
}

function LCM(n, k) {
	return n * k / GCD(n, k);
}


DROP TABLE tbl;
CREATE TABLE tbl
(
        u       NUMBER,
        v       NUMBER
);

INSERT INTO tbl ( u, v ) VALUES ( 20, 50 );
INSERT INTO tbl ( u, v ) VALUES ( 21, 50 );
INSERT INTO tbl ( u, v ) VALUES ( 21, 51 );
INSERT INTO tbl ( u, v ) VALUES ( 22, 50 );
INSERT INTO tbl ( u, v ) VALUES ( 22, 55 );

commit;

WITH
        FUNCTION gcd ( ui IN NUMBER, vi IN NUMBER )
        RETURN NUMBER
        IS
                u NUMBER := ui;
                v NUMBER := vi;
                t NUMBER;
        BEGIN
                while v > 0
                loop
                        t := u;
                        u := v;
                        v:= MOD(t, v );
                END loop;
                RETURN abs(u);
        END gcd;
        SELECT u, v, gcd ( u, v )
        FROM tbl
/


(* Euclid’s algorithm. *)

fun gcd (u, v) =
    let
        fun loop (u, v) =
            if v = 0 then
                u
            else
                loop (v, u mod v)
    in
        loop (abs u, abs v)
    end

(* Using the Rosetta Code example for assertions in Standard ML. *)
fun assert cond =
    if cond then () else raise Fail "assert"

val () = assert (gcd (0, 0) = 0)
val () = assert (gcd (0, 10) = 10)
val () = assert (gcd (~10, 0) = 10)
val () = assert (gcd (9, 6) = 3)
val () = assert (gcd (~6, ~9) = 3)
val () = assert (gcd (40902, 24140) = 34)
val () = assert (gcd (40902, ~24140) = 34)
val () = assert (gcd (~40902, 24140) = 34)
val () = assert (gcd (~40902, ~24140) = 34)
val () = assert (gcd (24140, 40902) = 34)
val () = assert (gcd (~24140, 40902) = 34)
val () = assert (gcd (24140, ~40902) = 34)
val () = assert (gcd (~24140, ~40902) = 34)


function gcd(a_,b_) {
	a = abs(a_)
	b = abs(b_)
	while (b>0) {
		a = mod(a,b)
		swap(a,b)
	}
	return(a)
}


// Iterative

func gcd(var a: Int, var b: Int) -> Int {

    a = abs(a); b = abs(b)

    if (b > a) { swap(&a, &b) }

    while (b > 0) { (a, b) = (b, a % b) }

    return a
}

// Recursive

func gcdr (var a: Int, var b: Int) -> Int {

    a = abs(a); b = abs(b)

    if (b > a) { swap(&a, &b) }

    return gcd_rec(a,b)
}

private func gcd_rec(a: Int, b: Int) -> Int {

    return b == 0 ? a : gcd_rec(b, a % b)
}

for (a,b) in [(1,1), (100, -10), (10, -100), (-36, -17), (27, 18), (30, -42)] {

    println("Iterative: GCD of \(a) and \(b) is \(gcd(a, b))")
    println("Recursive: GCD of \(a) and \(b) is \(gcdr(a, b))")
}


package require Tcl 8.5
namespace path {::tcl::mathop ::tcl::mathfunc}
proc gcd_iter {p q} {
    while {$q != 0} {
        lassign [list $q [% $p $q]] p q
    }
    abs $p
}


10 PRINT "First number"
20 INPUT A
30 PRINT "Second number"
40 INPUT B
50 IF A<0 THEN LET A=-A
60 IF B<0 THEN LET B=-B
70 IF A>B THEN GOTO 130
80 LET B = B - A
90 IF A=0 THEN GOTO 110
100 GOTO 50
110 PRINT B
120 END
130 LET C=A
140 LET A=B
150 LET B=C
160 GOTO 70


CREATE OR ALTER FUNCTION [dbo].[PGCD]
    (    @a BigInt
    ,    @b BigInt
    )
RETURNS BigInt
WITH RETURNS NULL ON NULL INPUT
-- Calculates the Greatest Common Denominator of two numbers (1 if they are coprime).
BEGIN
DECLARE @PGCD BigInt;

WITH    Vars(A, B)
As  (   SELECT  Max(V.N) As A
            ,   Min(V.N) As B
        FROM (  VALUES  ( Abs(@a) , Abs(@b)) ) Params(A, B)
        -- First, get absolute value
        Cross APPLY (   VALUES (Params.A) , (Params.B) ) V(N)
        -- Then, order parameters without Greatest/Least functions
        WHERE Params.A > 0
            And Params.B > 0 -- If 0 passed in, NULL shall be the output
    )
    ,   Calc(A, B)
As  (   SELECT  A
            ,   B
        FROM    Vars

        UNION ALL

        SELECT  B As A
            ,   A % B As B -- Self-ordering
        FROM    Calc
        WHERE   Calc.A > 0
            And Calc.B > 0
    )
SELECT  @PGCD = Min(A)
FROM    Calc
WHERE   Calc.B = 0
;

RETURN @PGCD;

END


REM Solución iterativa
FUNCTION gcdI(x, y)
    DO WHILE y > 0
       LET t = y
       LET y = remainder(x, y)
       LET x = t
    LOOP
    LET gcdI = x
END FUNCTION

LET a = 111111111111111
LET b = 11111

PRINT
PRINT "GCD(";a;", ";b;") = "; gcdI(a, b)
PRINT
PRINT "GCD(";a;", 111) = "; gcdI(a, 111)
END


// library: math: get: greatest: common: divisor <description>greatest common divisor whole numbers. Euclid's algorithm. Recursive version</description> <version control></version control> <version>1.0.0.0.3</version> <version control></version control> (filenamemacro=getmacdi.s) [<Program>] [<Research>] [kn, ri, su, 20-01-2013 14:22:41]
INTEGER PROC FNMathGetGreatestCommonDivisorI( INTEGER x1I, INTEGER x2I )
 //
 IF ( x2I == 0 )
  //
  RETURN( x1I )
  //
 ENDIF
 //
 RETURN( FNMathGetGreatestCommonDivisorI( x2I, x1I MOD x2I ) )
 //
END

PROC Main()
 STRING s1[255] = "353"
 STRING s2[255] = "46"
 REPEAT
  IF ( NOT ( Ask( " = ", s1, _EDIT_HISTORY_ ) ) AND ( Length( s1 ) > 0 ) ) RETURN() ENDIF
  IF ( NOT ( Ask( " = ", s2, _EDIT_HISTORY_ ) ) AND ( Length( s2 ) > 0 ) ) RETURN() ENDIF
  Warn( FNMathGetGreatestCommonDivisorI( Val( s1 ), Val( s2 ) ) ) // gives e.g. 1
 UNTIL FALSE
END


function gcd(a: number, b: number) {
  a = Math.abs(a);
  b = Math.abs(b);

  if (b > a) {
    let temp = a;
    a = b;
    b = temp;
  }

  while (true) {
    a %= b;
    if (a === 0) { return b; }
    b %= a;
    if (b === 0) { return a; }
  }
}


Print "GCD of 18 : 12 = "; FUNC(_GCD_Iterative_Euclid(18,12))
Print "GCD of 1071 : 1029 = "; FUNC(_GCD_Iterative_Euclid(1071,1029))
Print "GCD of 3528 : 3780 = "; FUNC(_GCD_Iterative_Euclid(3528,3780))

End

_GCD_Iterative_Euclid Param(2)
  Local (1)
  Do While [email protected]
    [email protected] = [email protected]
    [email protected] = [email protected]
    [email protected] = [email protected] % [email protected]
  Loop
Return (Abs([email protected]))


gcd() {
	# Calculate $1 % $2 until $2 becomes zero.
	until test 0 -eq "$2"; do
		# Parallel assignment: set -- 1 2
		set -- "$2" "`expr "$1" % "$2"`"
	done

	# Echo absolute value of $1.
	test 0 -gt "$1" && set -- "`expr 0 - "$1"`"
	echo "$1"
}

gcd -47376 87843
# => 987


import "math"
out (gcd 40902 24140) endl console


#import nat

gcd = ~&B?\~&Y ~&alh^?\~&arh2faltPrXPRNfabt2RCQ @a ~&ar^?\~&al ^|R/~& ^/~&r remainder


[gcd
   [0 >] [dup rollup %]
   while
   pop
].


Function gcd(u As Long, v As Long) As Long
    Dim t As Long
    Do While v
        t = u
        u = v
        v = t Mod v
    Loop
    gcd = u
End Function


Function GCD(a,b)
	Do
		If a Mod b > 0 Then
			c = a Mod b
			a = b
			b = c
		Else
			GCD = b
			Exit Do
		End If
	Loop
End Function

WScript.Echo "The GCD of 48 and 18 is " & GCD(48,18) & "."
WScript.Echo "The GCD of 1280 and 240 is " & GCD(1280,240) & "."
WScript.Echo "The GCD of 1280 and 240 is " & GCD(3475689,23566319) & "."
WScript.Echo "The GCD of 1280 and 240 is " & GCD(123456789,234736437) & "."


module gcd
  (
  input reset_l,
  input clk,

  input [31:0] initial_u,
  input [31:0] initial_v,
  input load,

  output reg [31:0] result,
  output reg busy
  );

reg [31:0] u, v;

always @(posedge clk or negedge reset_l)
  if (!reset_l)
    begin
      busy <= 0;
      u <= 0;
      v <= 0;
    end
  else
    begin

      result <= u + v; // Result (one of them will be zero)

      busy <= u && v; // We're still busy...

      // Repeatedly subtract smaller number from larger one
      if (v <= u)
        u <= u - v;
      else if (u < v)
        v <= v - u;

      if (load) // Load new problem when high
        begin
          u <= initial_u;
          v <= initial_v;
          busy <= 1;
        end

    end

endmodule


Function GCD(ByVal a As Long, ByVal b As Long) As Long
Dim h As Long

    If a Then
        If b Then
            Do
                h = a Mod b
                a = b
                b = h
            Loop While b
        End If
        GCD = Abs(a)
    Else
        GCD = Abs(b)
    End If

End Function

Sub Main()
' testing the above function

  Debug.Assert GCD(12, 18) = 6
  Debug.Assert GCD(1280, 240) = 80
  Debug.Assert GCD(240, 1280) = 80
  Debug.Assert GCD(-240, 1280) = 80
  Debug.Assert GCD(240, -1280) = 80
  Debug.Assert GCD(0, 0) = 0
  Debug.Assert GCD(0, 1) = 1
  Debug.Assert GCD(1, 0) = 1
  Debug.Assert GCD(3475689, 23566319) = 7
  Debug.Assert GCD(123456789, 234736437) = 3
  Debug.Assert GCD(3780, 3528) = 252

End Sub


fn gcd(xx int, yy int) int {
    mut x, mut y := xx, yy
    for y != 0 {
        x, y = y, x%y
    }
    return x
}

fn main() {
    println(gcd(33, 77))
    println(gcd(49865, 69811))
}


var gcd = Fn.new { |x, y|
    while (y != 0) {
        var t = y
        y = x % y
        x = t
    }
    return x.abs
}

System.print("gcd(33, 77) = %(gcd.call(33, 77))")
System.print("gcd(49865, 69811) = %(gcd.call(49865, 69811))")


.text
.global pgcd

pgcd:
        push    %ebp
        mov     %esp, %ebp

        mov     8(%ebp), %eax
        mov     12(%ebp), %ecx
        push    %edx

.loop:
        cmp     $0, %ecx
        je      .end
        xor     %edx, %edx
        div     %ecx
        mov     %ecx, %eax
        mov     %edx, %ecx
        jmp     .loop

.end:
        pop     %edx
        leave
        ret


' Greatest common divisor
PROGRAM "gcddemo"
VERSION "0.001"

DECLARE FUNCTION Entry()
DECLARE FUNCTION GcdRecursive(u&, v&)
DECLARE FUNCTION GcdIterative(u&, v&)
DECLARE FUNCTION GcdBinary(u&, v&)

FUNCTION Entry()
  m& = 49865
  n& = 69811
  PRINT "GCD("; LTRIM$(STR$(m&)); ","; n&; "):"; GcdIterative(m&, n&); " (iterative)"
  PRINT "GCD("; LTRIM$(STR$(m&)); ","; n&; "):"; GcdRecursive(m&, n&); " (recursive)"
  PRINT "GCD("; LTRIM$(STR$(m&)); ","; n&; "):"; GcdBinary (m&, n&); " (binary)"
END FUNCTION

FUNCTION GcdRecursive(u&, v&)
  IF u& MOD v& <> 0 THEN
    RETURN GcdRecursive(v&, u& MOD v&)
  ELSE
    RETURN v&
  END IF
END FUNCTION

FUNCTION GcdIterative(u&, v&)
  DO WHILE v& <> 0
    t& = u&
    u& = v&
    v& = t& MOD v&
  LOOP
  RETURN ABS(u&)
END FUNCTION

FUNCTION GcdBinary(u&, v&)
  u& = ABS(u&)
  v& = ABS(v&)
  IF u& < v& THEN
    t& = u&
    u& = v&
    v& = t&
  END IF
  IF v& = 0 THEN
    RETURN u&
  ELSE
    k& = 1
    DO WHILE (u& MOD 2 = 0) && (v& MOD 2 = 0)
      u& = u& >> 1
      v& = v& >> 1
      k& = k& << 1
    LOOP
    IF u& MOD 2 = 0 THEN
      t& = u&
    ELSE
      t& = -v&
    END IF
    DO WHILE t& <> 0
      DO WHILE t& MOD 2 = 0
        t& = t& \ 2
      LOOP
      IF t& > 0 THEN
        u& = t&
      ELSE
        v& = -t&
      END IF
      t& = u& - v&
    LOOP
    RETURN u& * k&
  END IF
END FUNCTION

END PROGRAM


(defun greatest-common-divisor (x y)
	(if (= y 0)
		x
		(greatest-common-divisor y (mod x y)) ) )


include c:\cxpl\codes;

func GCD(U, V); \Return the greatest common divisor of U and V
int  U, V;
int  T;
[while V do     \Euclid's method
    [T:= U;  U:= V;  V:= rem(T/V)];
return abs(U);
];

\Display the GCD of two integers entered on command line
IntOut(0, GCD(IntIn(8), IntIn(8)))


sub gcd(u, v)
    local t

    u = int(abs(u))
    v = int(abs(v))
    while(v)
        t = u
        u = v
        v = mod(t, v)
    wend
    return u
end sub

print "Greatest common divisor: ", gcd(12345, 9876)


; Inputs: a, b
; Outputs: a = gcd(a, b)
; Destroys: c
; Assumes: a and b are positive one-byte integers
gcd:
    cp b
    ret z                   ; while a != b

    jr c, else              ; if a > b

    sub b                   ; a = a - b

    jr gcd

else:
    ld c, a                 ; Save a
    ld a, b                 ; Swap b into a so we can do the subtraction
    sub c                   ; b = b - a
    ld b, a                 ; Put a and b back where they belong
    ld a, c

    jr gcd


10 FOR n=1 TO 3
20 READ a,b
30 PRINT "GCD of ";a;" and ";b;" = ";
40 GO SUB 70
50 NEXT n
60 STOP
70 IF b=0 THEN PRINT ABS (a): RETURN
80 LET c=a: LET a=b: LET b=FN m(c,b): GO TO 70
90 DEF FN m(a,b)=a-INT (a/b)*b
100 DATA 12,16,22,33,45,67


JSR $FFED
;returns screen width in X and screen height in Y
dex     ;subtract 1. This is more useful for comparisons.
dey     ;subtract 1. This is more useful for comparisons.
stx $20 ;store in zero page ram
sty $21 ;store in zero page ram


doRNG:
	;run this during vblank for best results.
	JSR SYS_READ_CALENDAR
	;gets the calendar.
	;MAME uses your computer's time for this.
	MOVE.L BIOS_HOUR,D0		;D0 = HHMMSS00
	LSR.L #8,D0                     ;shift out the zeroes.
	MOVE.L frame_timer,D1           ;this value is incremented by 1 every vBlank (i.e. just before this procedure is run)
	NOT.L D1                        ;flip all the bits of D1
	MULS D1,D0
	MULU D1,D0
	MOVE.L JOYPAD1,D1               ;get the most recent button presses.
	CloneByte D1                    ;copy this byte to all 4 bytes of D1
	EOR.L D1,D0
	MOVE.L RNGout_32,D2	        ;look at last time's results.
	AND.B #1,D2                     ;check if it's odd or even
	BNE	SwapRNGifEven
		SWAP D0                 ;if even, swap the low and high words of D0
SwapRNGifEven:
	MOVE.L D0,RNGout_32
	rts


with Ada.Text_IO;            use Ada.Text_IO;
with Ada.Characters.Latin_1; use Ada.Characters.Latin_1;
with GNAT.Expect;            use GNAT.Expect;
with GNAT.OS_Lib;            use GNAT.OS_Lib;
with GNAT.String_Split;      use GNAT.String_Split;

procedure System_Command is
   Command    : String          := "ls -l";
   Args       : Argument_List_Access;
   Status     : aliased Integer;
   Separators : constant String := LF & CR;
   Reply_List : Slice_Set;

begin
   Args := Argument_String_To_List (Command);
   -- execute the system command and get the output in a single string
   declare
      Response : String :=
        Get_Command_Output
          (Command   => Args (Args'First).all,
           Arguments => Args (Args'First + 1 .. Args'Last),
           Input     => "",
           Status    => Status'Access);
   begin
      Free (Args);
      -- split the output in a slice for easier manipulation
      if Status = 0 then
         Create (S          => Reply_List,
                 From       => Response,
                 Separators => Separators,
                 Mode       => Multiple);
      end if;
   end;
   -- do something with the system output. Just print it out
   for I in 1 .. Slice_Count (Reply_List) loop
      Put_Line (Slice (Reply_List, I));
   end loop;

end System_Command;


/* JAMBO language - a flavour of Hopper */
#include <jambo.h>
Main
  sys = `cat jm/sys1.jambo`
  Set( sys ) Prnl
End


BEGIN {

         # For Windows
         out = system2var("dir")
         print out

         # Non-Windows
         out = getline2var("ls -l")
         print out
}

# For a Windows environment using system() method
function system2var(command    ,tempfile, cmd, out, rec, data, i) {
         tempfile = "C:\\TEMP\\TMP.TMP"
         cmd = command " > " tempfile
         system(cmd)
         close(cmd)
         while (getline rec < tempfile > 0) {
             if ( ++i == 1 )
                 data = rec
             else
                 data = data "\n" rec
         }
         return(data)
}

# If command returns an ERRNO function returns null string
function getline2var(command        ,fish, scale, ship) {
         command = command " 2>/dev/null"
         while ( (command | getline fish) > 0 ) {
             if ( ++scale == 1 )
                 ship = fish
             else
                 ship = ship "\n" fish
         }
         close(command)
         return ship
}


' Get system command
result$ = EXEC$("fortune")
PRINT CHOP$(result$)
PRINT "First word: " & TOKEN$(result$, 1)


@echo off
setlocal enabledelayedexpansion

:: Without storing the output of the command, it can be viewed by inputting the command
dir

:: Storing the output of 'dir' as "line[]" containing the respective lines of output (starting at line[1])
:: Note: This method removes any empty lines from the output
set tempcount=0
for /f "tokens=*" %%i in ('dir') do (
  set /a tempcount+=1
  set "line!tempcount!=%%i"
)
:: The array would be viewed like this
for /l %%i in (1,1,%tempcount%) do echo !line%%i!

:: Storing the output of 'dir' in a file, then outputting the contents of the file to the screen
:: NOTE: rewrites any file named "out.temp" in the current directory
dir>out.temp
type out.temp
del out.temp

pause>nul


(system=
.sys$(str$(!arg " > temp"))&get$(temp,STR)
);


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

int main(int argc, char **argv)
{
    if (argc < 2) return 1;

    FILE *fd;
    fd = popen(argv[1], "r");
    if (!fd) return 1;

    char   buffer[256];
    size_t chread;
    /* String to store entire command contents in */
    size_t comalloc = 256;
    size_t comlen   = 0;
    char  *comout   = malloc(comalloc);

    /* Use fread so binary data is dealt with correctly */
    while ((chread = fread(buffer, 1, sizeof(buffer), fd)) != 0) {
        if (comlen + chread >= comalloc) {
            comalloc *= 2;
            comout = realloc(comout, comalloc);
        }
        memmove(comout + comlen, buffer, chread);
        comlen += chread;
    }

    /* We can now work with the output as we please. Just print
     * out to confirm output is as expected */
    fwrite(comout, 1, comlen, stdout);
    free(comout);
    pclose(fd);
    return 0;
}


using System;

namespace GetSystemCommandOutput {
    class Program {
        static void Main(string[] args) {
            System.Diagnostics.Process process = new System.Diagnostics.Process();
            System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
            startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
            startInfo.FileName = "cmd.exe";
            startInfo.Arguments = "/c echo Hello World";
            startInfo.RedirectStandardOutput = true;
            startInfo.UseShellExecute = false;
            process.StartInfo = startInfo;
            process.Start();

            string output = process.StandardOutput.ReadToEnd();
            Console.WriteLine("Output is {0}", output);
        }
    }
}


#include <fstream>
#include <iostream>

std::string execute(const std::string& command) {
    system((command + " > temp.txt").c_str());

    std::ifstream ifs("temp.txt");
    std::string ret{ std::istreambuf_iterator<char>(ifs), std::istreambuf_iterator<char>() };
    ifs.close(); // must close the inout stream so the file can be cleaned up
    if (std::remove("temp.txt") != 0) {
        perror("Error deleting temporary file");
    }
    return ret;
}

int main() {
    std::cout << execute("whoami") << '\n';
}


(use '[clojure.java.shell :only [sh]])
(sh "echo" "Hello")


import std.process;
import std.stdio;

void main() {
    auto cmd = executeShell("echo hello");

    if (cmd.status == 0) {
        writeln("Output: ", cmd.output);
    } else {
        writeln("Failed to execute command, status=", cmd.status);
    }
}