/*REXX program  expresses numbers  from  intersecting number wheels  (or wheel sets).   */
@.=                                              /*initialize array to hold the wheels. */
parse arg lim @.1                                /*obtain optional arguments from the CL*/
if lim='' | lim=","  then lim= 20                /*Not specified?  Then use the default.*/
if @.1='' | @.1=","  then do;  @.1= ' A:  1 2 3 '
                               @.2= ' A:  1 B 2,    B:  3 4 '
                               @.3= ' A:  1 D D,    D:  6 7 8 '
                               @.4= ' A:  1 B C,    B:  3 4,    C:  5 B '
                          end
       do i=1  while @.i\='';  call run          /*construct wheel set and "execute" it.*/
       end   /*i*/
exit 0                                           /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
error: procedure; say;  say;    say '***error***'   arg(1);          say;   say;   exit 12
isLet: procedure; parse arg y;  return datatype(y, 'M') & length(y)==1   /*is a letter? */
isNum: procedure; parse arg y;  return datatype(y, 'N')                  /*is a number? */
/*──────────────────────────────────────────────────────────────────────────────────────*/
run: @wn= 'wheel name';     first=;      @noColon= "wheel name not followed by a colon:"
     @gn= 'gear name' ;     gear.=;      say copies("═", 79)
     say 'building wheel group for: '    @.i;    wheels= space(@.i);        upper wheels
        do #=1  while wheels\='';  parse var wheels  w gears "," wheels;    L= length(w)
        if L==2  then do;  !.#= left(w, 1)       /*obtain the one─character gear name.  */
                           if right(w, 1)\==':'  then call error @noColon  w
                           if \isLet(!.#)        then call error @wn "not a letter:"  w
                      end
                 else call error "first token isn't a"   @wn':'     w
        if #==1  then first= !.1                 /*Is this is the 1st wheel set?  Use it*/
        if first==''  then call error "no wheel name was specified."
        n= !.#                                   /*obtain the name of the 1st wheel set.*/
        gear.n.0= 1                              /*initialize default 1st gear position.*/
        say '   setting gear.name:'     n     "    gears=" gears
           do g=1  for words(gears);         _= word(gears, g)
           if isNum(_)  |  isLet(_)  then do;  gear.n.g= _;  iterate;  end
           call error  @gn  "isn't a number or a gear name:"  _
           end   /*g*/
        end      /*#*/
    say;                  say center(' running the wheel named '  first" ", 79, '─');   $=
        do dummy=0  by 0  until words($)==lim;           n= first
        z= gear.n.0;               x= gear.n.z;          z= z + 1
        gear.n.0= z;      if gear.n.z==''  then gear.n.0= 1
        if isNum(x)  then do;     $= $ x;    iterate;    end   /*found a number, use it.*/
        xx= x                                    /*different gear, keep switching 'til X*/
           do forever;            nn= xx
           if gear.nn.0==''  then call error "a gear is using an unknown gear name:"  x
           zz= gear.nn.0;         xx= gear.nn.zz
           zz= zz + 1;   gear.nn.0= zz;   if gear.nn.zz==''  then gear.nn.0= 1
           if isNum(xx)  then do;  $= $ xx;  iterate dummy;  end
           end   /*forever*/                     /* [↑]  found a number,  now use FIRST.*/
        end      /*dummy*/                       /*"DUMMY"  is needed for the  ITERATE. */
     say '('lim "results): "  strip($);      say;          say;          return


package main

import (
    "debug/elf"
    "debug/gosym"
    "fmt"
    "log"
    "math"
    "os"
    "runtime"
)

var bloop = -3.4

func main() {
    fmt.Println("task 1: verify version")
    fmt.Println("   program compiled with", runtime.Version())

    fmt.Println("task 2: check for presence of variable and function")
    // inspect ELF symbol table
    f, err := elf.Open(os.Args[0])
    if err != nil {
        log.Fatal(err)
    }
    defer f.Close()
    symSection := f.Section(".gosymtab")
    lineSection := f.Section(".gopclntab")
    textSection := f.Section(".text")
    if symSection == nil || lineSection == nil || textSection == nil {
        log.Fatal("symbolic information not found")
    }
    symData, err := symSection.Data()
    if err != nil {
        log.Fatal(err)
    }
    lineData, err := lineSection.Data()
    if err != nil {
        log.Fatal(err)
    }
    table, err := gosym.NewTable(symData,
        gosym.NewLineTable(lineData, textSection.Addr))
    if err != nil {
        log.Fatal("  ", err)
    }
    var foundBloop, foundFabs bool
    for _, s := range table.Syms {
        if s.Name == "main.bloop" {
            foundBloop = true
            fmt.Println("   bloop symbol table entry:", s)
        } else if s.Name == "math.Abs" {
            foundFabs = true
            fmt.Println("   abs symbol table entry:", s)
        }
    }
    if foundBloop && foundFabs {
        fmt.Println("   bloop:     ", bloop)
        fmt.Println("   abs(bloop): ", math.Abs(bloop))
    }
}


import Data.Version
import Control.Monad
import System.Info

minGHCVersion = Version [6, 8] []

main = when (compilerName == "ghc" && compilerVersion < minGHCVersion) $
    fail "Compiler too old."


;; screen copy of the REPL
;; note that the &i variables remember expression evaluation, and may be used in other expressions

EchoLisp - 2.16.2
📗 local-db: db.version: 3
(define ( f s1 s2 s3) (string-append s1 s3 s3 s2))
[0]→ f
(f "Rosetta" "Code" ":")
[1]→ "Rosetta::Code"
(+ 4 8)
[2]→ 12
(* 4 8)
[3]→ 32
(* &2 &3)
[4]→ 384
(f &1 &1 ":")
[5]→ "Rosetta::Code::Rosetta::Code"

;; etc.


c:\Alex\ELENA\bin>elt
ELENA command line VM terminal 5.1.13 (C)2011-2020 by Alexei Rakov
ELENA VM 5.1.17 (C)2005-2020 by Alex Rakov
Initializing...
Done...

>f(s1,s2,sep){^ s1 + sep + sep + s2 };

>f("Rosetta","Code",":")
Rosetta::Code
>


iex(1)> f = fn str1,str2,sep -> [str1,"",str2] |> Enum.join(sep) end # Join list on separator
iex(2)> g = fn str1,str2,sep -> str1 <> sep <> sep <> str2 end       # Or concatenate strings

iex(3)> defmodule JoinStrings do
...(3)>   def f(str1,str2,sep), do: [str1,"",str2] |> Enum.join(sep)
...(3)>   def g(str1,str2,sep), do: str1 <> sep <> sep <> str2
...(3)> end


(defun my-join (str1 str2 sep)
  (concat str1 sep sep str2))
my-join
(my-join "Rosetta" "Code" ":")
"Rosetta::Code"


groups = [{A: [1, 2, 3]},
          {A: [1, :B, 2], B: [3, 4]},
          {A: [1, :D, :D], D: [6, 7, 8]},
          {A: [1, :B, :C], B: [3, 4], C: [5, :B]} ]

groups.each do |group|
  p group
  wheels = group.transform_values(&:cycle)
  res = 20.times.map do
    el = wheels[:A].next
    el = wheels[el].next until el.is_a?(Integer)
    el
  end
  puts res.join(" "),""
end


Imports System.Runtime.CompilerServices

Module Module1

    <Extension()>
    Iterator Function Loopy(Of T)(seq As IEnumerable(Of T)) As IEnumerable(Of T)
        While True
            For Each element In seq
                Yield element
            Next
        End While
    End Function

    Iterator Function TurnWheels(ParamArray wheels As (name As Char, values As String)()) As IEnumerable(Of Char)
        Dim data = wheels.ToDictionary(Function(wheel) wheel.name, Function(wheel) wheel.values.Loopy.GetEnumerator)
        Dim primary = data(wheels(0).name)

        Dim Turn As Func(Of IEnumerator(Of Char), Char) = Function(sequence As IEnumerator(Of Char))
                                                              sequence.MoveNext()
                                                              Dim c = sequence.Current
                                                              Return If(Char.IsDigit(c), c, Turn(data(c)))
                                                          End Function

        While True
            Yield Turn(primary)
        End While
    End Function

    <Extension()>
    Sub Print(sequence As IEnumerable(Of Char))
        Console.WriteLine(String.Join(" ", sequence))
    End Sub

    Sub Main()
        TurnWheels(("A", "123")).Take(20).Print()
        TurnWheels(("A", "1B2"), ("B", "34")).Take(20).Print()
        TurnWheels(("A", "1DD"), ("D", "678")).Take(20).Print()
        TurnWheels(("A", "1BC"), ("B", "34"), ("C", "5B")).Take(20).Print()
    End Sub

End Module


global bloop

procedure main(A)
    if older(11,7) then stop("Must have version >= 11.7!")
    bloop := -5         # global variable
    floop := -11.3      # local variable
    write(proc("abs")(variable("bloop")))
    write(proc("abs")(variable("floop")))
end

procedure older(maj,min)
    &version ? {
        (tab(find("Version ")),move(*"Version "))
        major := 1(tab(upto('.')),move(1))
        minor := tab(upto('.'))
        return (major < maj) | ((major = maj) & (minor < min))
        }
end


Home is a room.

When play begins:
	let V be the current runtime version;
	if V is less than the required runtime version:
		say "Version [required runtime version] required, but [V] found.";
	otherwise:
		say "Your interpreter claims version [V].";
	end the story.

A version is a kind of value.

Section - Checking the version (for Glulx only)

1.255.255 specifies a version with parts major, minor (without leading zeros), and subminor (without leading zeros).

To decide which version is current runtime version: (- (0-->1) -).
To decide which version is required runtime version: decide on 3.1.2.

Section - Checking the version (for Z-machine only)

1.255 specifies a version with parts major and minor (without leading zeros).

To decide which version is current runtime version: (- ($32-->0) -).
To decide which version is required runtime version: decide on 1.1.


if(System version < 20080000, exit)

if(hasSlot("bloop") and bloop hasSlot("abs"), bloop abs)


$erl
1> F = fun(X,Y,Z) -> string:concat(string:concat(X,Z),string:concat(Z,Y)) end.
#Fun<erl_eval.18.105910772>
2> F("Rosetta", "Code", ":").
"Rosetta::Code"


 r$="Rosetta"
 Ok   <--- from interpreter
 c$="Code"
 Ok   <--- from interpreter
 s$="-"
 Ok   <--- from interpreter
 PRINT r$+s$+c$
 Rosetta-Code
 Ok   <--- from interpreter


Microsoft F# Interactive, (c) Microsoft Corporation, All Rights Reserved
F# Version 1.9.6.2, compiling for .NET Framework Version v2.0.50727

Please send bug reports to [email protected]com
For help type #help;;

> let f a b sep = String.concat sep [a; ""; b] ;;

val f : string -> string -> string -> string

> f "Rosetta" "Code" ":" ;;
val it : string = "Rosetta::Code"


$ fansh
Fantom Shell v1.0.57 ('?' for help)
fansh> f := |Str a, Str b, Str c -> Str| {"$a$c$c$b"}
|sys::Str,sys::Str,sys::Str->sys::Str|
fansh> f("Rosetta", "Code", ":")
Rosetta::Code


import "/dynamic" for Struct
import "/sort" for Sort
import "/fmt" for Fmt

var Wheel = Struct.create("Wheel", ["next", "values"])

var generate = Fn.new { |wheels, start, maxCount|
    var count = 0
    var w = wheels[start]
    while (true) {
        var s = w.values[w.next]
        var v = Num.fromString(s)
        w.next = (w.next + 1) % w.values.count
        wheels[start] = w
        if (v) {
            System.write("%(v) ")
            count = count + 1
            if (count == maxCount) {
                System.print("...\n")
                return
            }
        } else {
            while (true) {
                var w2 = wheels[s]
                var ss = s
                s = w2.values[w2.next]
                w2.next = (w2.next + 1) % w2.values.count
                wheels[ss] = w2
                v = Num.fromString(s)
                if (v) {
                    System.write("%(v) ")
                    count = count + 1
                    if (count == maxCount) {
                        System.print("...\n")
                        return
                    }
                    break
                }
            }
        }
    }
}

var printWheels = Fn.new { |wheels|
    var names = []
    for (name in wheels.keys) names.add(name)
    Sort.quick(names)
    System.print("Intersecting Number Wheel group:")
    for (name in names) {
        Fmt.print("  $s: $n", name, wheels[name].values)
    }
    System.write("  Generates:\n    ")
}

var wheelMaps = [
    {
        "A": Wheel.new(0, ["1", "2", "3"])
    },
    {
        "A": Wheel.new(0, ["1", "B", "2"]),
        "B": Wheel.new(0, ["3", "4"])
    },
    {
        "A": Wheel.new(0, ["1", "D", "D"]),
        "D": Wheel.new(0, ["6", "7", "8"])
    },
    {
        "A": Wheel.new(0, ["1", "B", "C"]),
        "B": Wheel.new(0, ["3", "4"]),
        "C": Wheel.new(0, ["5", "B"])
    }
]
for (wheels in wheelMaps) {
    printWheels.call(wheels)
    generate.call(wheels, "A", 20)
}


100 IF VERNUM<2.1 THEN PRINT "Version is too old.":STOP
110 WHEN EXCEPTION USE ERROR
120   PRINT ABS(BLOOP)
130 END WHEN
140 HANDLER ERROR
150   PRINT EXSTRING$(EXTYPE)
160   CONTINUE
170 END HANDLER


public class VersCheck {
	public static void main(String[] args) {
		String vers = System.getProperty("java.version");
		vers = vers.substring(0,vers.indexOf('.')) + "." +  //some String fiddling to get the version number into a usable form
			vers.substring(vers.indexOf('.')+1,vers.lastIndexOf('.'));
		if(Double.parseDouble(vers) >= 1.5){
			System.out.println("YAY!");
		}else{
			System.err.println("Must use Java >=1.5");
		}
	}
}


$ gforth
Gforth 0.7.0, Copyright (C) 1995-2008 Free Software Foundation, Inc.
Gforth comes with ABSOLUTELY NO WARRANTY; for details type `license'
Type `bye' to exit
  ok
: f ( separator suffix prefix -- )  compiled
   pad place  2swap 2dup   compiled
   pad +place    compiled
   pad +place    compiled
   pad +place  compiled
   pad count ;  ok
  ok
 s" :" s" Code" s" Rosetta" f cr type
Rosetta::Code ok


' FB 1.05.0 Win64

Dim As String s1, s2, sep
Input "First string  "; s1
Input "Second string "; s2
Input "Separator     "; sep
Print : Print  s1 + sep + sep + s2
Sleep


$ java -cp frink.jar frink.parser.Frink

f[a,b,s] := "$a$s$s$b"
f["Rosetta", "Code", ":"]


package main

import "fmt"

func f(s1, s2, sep string) string {
	return s1 + sep + sep + s2
}

func main() {
	fmt.Println(f("Rosetta", "Code", ":"))
}


fcn intersectingNumberWheelsW(wheels){ // ("A":(a,b,"C"), "C":(d,e) ...)
   ws:=wheels.pump(Dictionary(),fcn([(k,v)]){ return(k,Walker.cycle(v)) });  // new Dictionary
   Walker.zero().tweak(fcn(w,wheels){
      while(1){
	 w=wheels[w].next();	// increment wheel w
	 if(Int.isType(w)) return(w);
      }
   }.fp("A",ws))	// assume wheel A exists and is always first
}


if (typeof bloop !== "undefined") { ... }


jq --arg version $(jq --version) '$version'


/* Introspection, in jsish */
if (Info.version() < Util.verConvert('2.8.6')) {
    puts("need at least version 2.8.6 of jsish for this application");
    exit(1);
}

/* Check for "abs()" as function and "bloop" as defined value, call if both check true */
if ((bloop != undefined) && (typeof Math.abs == 'function')) {
    puts(Math.abs(bloop));
}

/* ECMAScript, this will sum all numeric values, not just strict integers */
var nums = 0, sums = 0, v;
for (v of Info.vars(this)) {
    if (isFinite(this[v])) {
        nums++;
        sums += this[v];
    }
}
printf("%d numerics with sum of: %d\n", nums, sums);


$ ghci
   ___         ___ _
  / _ \ /\  /\/ __(_)
 / /_\// /_/ / /  | |      GHC Interactive, version 6.4.2, for Haskell 98.
/ /_\\/ __  / /___| |      http://www.haskell.org/ghc/
\____/\/ /_/\____/|_|      Type :? for help.

Loading package base-1.0 ... linking ... done.
Prelude> let f as bs sep = as ++ sep ++ sep ++ bs
Prelude> f "Rosetta" "Code" ":"
"Rosetta::Code"


CHARACTER A*40, B*40, C*40

READ(Text=$CMD_LINE, Format="'','','',") A, B, C
WRITE(ClipBoard, Name) A, B, C               ! A=Rosetta; B=Code; C=:;

WRITE(ClipBoard) TRIM(A) // ':' // TRIM(C) // TRIM(B)  ! Rosetta::Code


$ io
Io 20110905
Io> f := method(str1,str2,sep,
... str1 .. sep .. sep .. str2)
==> method(str1, str2, sep,
    str1 .. sep .. sep .. str2
)
Io> f("Rosetta","Code",":")
==> Rosetta::Code
Io> writeln("I am going to exit now")
I am going to exit now
==> nil
Io> exit
$


@show VERSION
VERSION < v"0.4" && exit(1)

if isdefined(Base, :bloop) && !isempty(methods(abs))
    @show abs(bloop)
end

a, b, c = 1, 2, 3
vars = filter(x -> eval(x) isa Integer, names(Main))
println("Integer variables: ", join(vars, ", "), ".")
println("Sum of integers in the global scope: ", sum(eval.(vars)), ".")


// version 1.0.6 (intro.kt)

import java.lang.reflect.Method

val bloop = -3
val i = 4
val j = 5
val k = 6

fun main(args: Array<String>) {
    // get version of JVM
    val version = System.getProperty("java.version")
    if (version >= "1.6") println("The current JVM version is $version")
    else println("Must use version 1.6 or later")

    // check that 'bloop' and 'Math.abs' are available
    // note that the class created by the Kotlin compiler for top level declarations will be called 'IntroKt'
    val topLevel = Class.forName("IntroKt")
    val math = Class.forName("java.lang.Math")
    val abs = math.getDeclaredMethod("abs", Int::class.java)
    val methods = topLevel.getDeclaredMethods()
    for (method in methods) {
        // note that the read-only Kotlin property 'bloop' is converted to the static method 'getBloop' in Java
        if (method.name == "getBloop" && method.returnType == Int::class.java) {
            println("\nabs(bloop) = ${abs.invoke(null, method.invoke(null))}")
            break
        }
    }

    // now get the number of global integer variables and their sum
    var count = 0
    var sum = 0
    for (method in methods) {
        if (method.returnType == Int::class.java) {
            count++
            sum += method.invoke(null) as Int
        }
    }
    println("\nThere are $count global integer variables and their sum is $sum")
}


var(bloob = -26)

decimal(lasso_version(-lassoversion)) < 9.2 ? abort

var_defined('bloob') and $bloob -> isa(::integer) and lasso_tagexists('math_abs') ? math_abs($bloob)


   f=: [: ; 0 2 2 1&{
   f 'Rosetta';'Code';':'
Rosetta::Code


public static void main(String[] args) {
    System.out.println(concat("Rosetta", "Code", ":"));
}

public static String concat(String a, String b, String c) {
   return a + c + c + b;
}

Rosetta::Code


$ java -cp js.jar org.mozilla.javascript.tools.shell.Main
Rhino 1.7 release 2 2009 03 22
js> function f(a,b,s) {return a + s + s + b;}
js> f('Rosetta', 'Code', ':')
Rosetta::Code
js> quit()
$


prompt$ jsish
Jsish interactive: see 'help [cmd]'
# function f(a:string, b:string, s:string):string { return a+s+s+b; }
# f('Rosetta', 'Code', 1)
warn: type mismatch for argument arg 3 's': expected "string" but got "number", in call to 'f' <1>.    (at or near "Code")

"Rosetta11Code"
# f('Rosetta', 'Code', ':')
"Rosetta::Code"


[email protected]:~/rosetta/julia$ julia
               _
   _       _ _(_)_     |  A fresh approach to technical computing
  (_)     | (_) (_)    |  Documentation: http://docs.julialang.org
   _ _   _| |_  __ _   |  Type "help()" for help.
  | | | | | | |/ _` |  |
  | | |_| | | | (_| |  |  Version 0.3.7 (2015-03-23 21:36 UTC)
 _/ |\__'_|_|_|\__'_|  |  Official http://julialang.org release
|__/                   |  x86_64-linux-gnu

julia> function strcat(a::String, b::String, sep::String)
                  a*(sep^2)*b
       end
strcat (generic function with 1 method)

julia> strcat("rosetta", "code", "_")
"rosetta__code"

julia>


put _player.productVersion
-- "11.5.9"

_player.itemDelimiter="."
if integer(_player.productVersion.item[1])<11 then _player.quit()


org &4000   ; program start address

push bc
push de
push hl
push af
ld bc,&df00 ; select BASIC ROM
out (c),c   ;   (ROM 0)

ld bc,&7f86 ; make ROM accessible at &c000
out (c),c             ;   (RAM block 3)

ld hl,&c001 ; copy ROM version number to RAM
ld de,&4040
ld bc,3
ldir

ld bc,&7f8e ; turn off ROM
out (c),c
pop af
pop hl
pop de
pop bc
ret


show logoversion   ; 5.6
if logoversion < 6.0 [print [too old!]]

if and [name? "a] [number? :a] [
  print ifelse procedure? "abs [abs :a] [ifelse :a < 0 [minus :a] [:a]]
]


:- object(my_application).

    :- initialization((
        check_logtalk_version,
        compute_predicate_if_available
    )).

    check_logtalk_version :-
        % version data is available by consulting the "version_data" flag
        current_logtalk_flag(version_data, logtalk(Major,Minor,Patch,_)),
        (   (Major,Minor,Patch) @< (3,0,0) ->
            write('Logtalk version is too old! Please upgrade to version 3.0.0 or later'), nl,
            halt
        ;   true
        ).

    % Logtalk is not a functional language and thus doesn't support user-defined functions; we
    % use instead a predicate, abs/2, with a return argument to implement the abs/1 function
    compute_predicate_if_available :-
        (   % check that the variable "bloop" is defined within this object
            current_predicate(bloop/1),
            % assume that the abs/2 predicate, if available, comes from a "utilities" object
            utilities::current_predicate(abs/2) ->
            bloop(Value),
            utilities::abs(Value, Result),
            write('Function value: '), write(Result), nl
        ;   write('Could not compute function!'), nl
        ).

    % our "bloop" variable value as per task description
    bloop(-1).

:- end_object.


$ rlwrap k
K Console - Enter \ for help
  f:{x,z,z,y}
  f["Rosetta";"Code";":"]
"Rosetta::Code"


c:\kotlin-compiler-1.0.6>kotlinc
Welcome to Kotlin version 1.0.6-release-127 (JRE 1.8.0_31-b13)
Type :help for help, :quit for quit
>>> fun f(s1: String, s2: String, sep: String) = s1 + sep + sep + s2
>>> f("Rosetta", "Code", ":")
Rosetta::Code
>>> :quit


#!/usr/bin/lasso9

// filename: interactive_demo

define concatenate_with_delimiter(
	string1::string,
	string2::string,
	delimiter::string

) => #string1 + (#delimiter*2) + #string2

define read_input(prompt::string) => {

	local(string)

	// display prompt
	stdout(#prompt)
	// the following bits wait until the terminal gives you back a line of input
	while(not #string or #string -> size == 0) => {
		#string = file_stdin -> readsomebytes(1024, 1000)
	}
	#string -> replace(bytes('\n'), bytes(''))

	return #string -> asstring
}

local(
	string1,
	string2,
	delimiter
)

// get first string
#string1 = read_input('Enter the first string: ')

// get second string
#string2 = read_input('Enter the second string: ')

// get delimiter
#delimiter = read_input('Enter the delimiter: ')

// deliver the result
stdoutnl(concatenate_with_delimiter(#string1, #string2, #delimiter))


{def F {lambda {:a :b :s} :a:s:s:b}}
-> F

{F Rosetta Code :}
-> Rosetta::Code


> m=new(#script)
> m.scripttext="on conc(a,b,c)"&RETURN&"return a&c&c&b"&RETURN&"end"
> put conc("Rosetta", "Code", ":")
-- "Rosetta::Code"


$ logo
Welcome to Berkeley Logo version 5.6
? to f :prefix :suffix :separator
> output (word :prefix :separator :separator :suffix)
> end
f defined
? show f "Rosetta "Code ":
Rosetta::Code
?


if _VERSION:sub(5) + 0 < 5.1 then print"too old" end --_VERSION is "Lua <version>".

if bloop and math.abs then print(math.abs(bloop)) end


> kernelopts( 'version' );
                 Maple 16.00, SUN SPARC SOLARIS, Mar 3 2012, Build ID 732982


If[$VersionNumber  < 8,  Quit[]]
If[NameQ["bloop"] && NameQ["Abs"],
 Print[Abs[bloop]]]


   % convert version into numerical value
   v = version;
   v(v=='.')=' ';
   v = str2num(v);
   if v(2)>10; v(2) = v(2)/10; end;
   ver = v(1)+v(2)/10;
   if exist('OCTAVE_VERSION','builtin')
      if ver < 3.0,
         exit
      end;
   else
      if ver < 7.0,
         exit
      end;
   end

   % test variable bloob, and test whether function abs is defined as m-function, mex-function or builtin-function
   if exist('bloob','var') && any(exist('abs')==[2,3,5])
	printf('abs(bloob) is %f\n',abs(bloob));
	return;
   end;


$ lua
Lua 5.1.2  Copyright (C) 1994-2007 Lua.org, PUC-Rio
> function conc(a, b, c)
>> return a..c..c..b
>> end
> print(conc("Rosetta", "Code", ":"))
Rosetta::Code
>


>> f = @(str1, str2, delim) [str1, delim, delim, str2];


(%i1) f(a, b, c) := sconcat(a, c, c, b)$
(%i2) f("Rosetta", "Code", ":");
(%o2) "Rosetta::Code"


/* Get version information */
build_info();
/* build_info("5.27.0", "2012-05-08 11:27:57", "i686-pc-mingw32", "GNU Common Lisp (GCL)", "GCL 2.6.8") */

%@lisp_version;
/* "GCL 2.6.8" */

/* One can only check for user-defined objects: functions, variables, macros, ...
   Hence we won't check for 'abs, which is built-in, but for 'weekday, defined elsewhere on RosettaCode.
   Here year, month and day are 2012, 05, 29. */

if    subsetp({'year, 'month, 'day}, setify(values))
and   member('weekday, map(op, functions))
then  weekday(year, month, day)
else  'bad\ luck;

/* Sum of integer variables */
lreduce("+", sublist(map(ev, values), integerp));


fn computeAbsBloop bloop =
(
    versionNumber = maxVersion()

    if versionNumber[1] < 9000 then
    (
        print "Max version 9 required"
        return false
    )

    if bloop == undefined then
    (
        print "Bloop is undefined"
        return false
    )

    try
    (
        abs bloop
    )
    catch
    (
        print "No function abs"
        false
    )
)

computeAbsBloop -17


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

runSample(arg)
return

-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method runSample(arg) private static
  parse arg minVersion .
  if minVersion = '' then minVersion = 2.0
  parse version lang ver bdate
  if ver < minVersion then do
    say -
      lang 'version' ver -
      '[Build date:' bdate']' -
      'is less than' minVersion.format(null, 2)'; exiting...'
    exit
    end
  else do
    say -
      lang 'version' ver -
      '[Build date:' bdate']' -
      'meets minimum requirements of' minVersion.format(null, 2)
    end
  return


when NimVersion < "1.2":
  error "This compiler is too old"                       # Error at compile time.

assert NimVersion >= "1.4", "This compiler is too old."  # Assertion defect at runtime.

var bloop = -12

when compiles abs(bloop):
  echo abs(bloop)


# Sys.ocaml_version;;
- : string = "3.10.2"


$ (dup suffix swap suffix suffix) :glue
$ "Rosetta" "Code" ":" glue puts!
Rosetta::Code
$


MCSKIP MT,<>
MCINS %.
MCDEF F WITHS (,,)
AS <%WA1.%WA3.%WA2.%WA2.>


>nq
[no file | rec1 col1] % def f(a, b, sep)
                        ...     return a + sep + sep + b
                        ... end
[no file | rec1 col1] % println f("Rosetta", "Code", ":")
Rosetta::Code


proc f(x, y, z: string) = echo x, z, z, y
f("Rosetta", "Code", ":")


$ ocaml
        Objective Caml version 3.12.1

# let f s1 s2 sep = String.concat sep [s1; ""; s2];;
val f : string -> string -> string -> string = <fun>
# f "Rosetta" "Code" ":";;
- : string = "Rosetta::Code"
#


$ octave
GNU Octave, version 3.0.2
Copyright (C) 2008 John W. Eaton and others.
This is free software; see the source code for copying conditions.
There is ABSOLUTELY NO WARRANTY; not even for MERCHANTIBILITY or
FITNESS FOR A PARTICULAR PURPOSE.  For details, type `warranty'.

Octave was configured for "i586-mandriva-linux-gnu".

Additional information about Octave is available at http://www.octave.org.

Please contribute if you find this software useful.
For more information, visit http://www.octave.org/help-wanted.html

Report bugs to <bug@octave.org> (but first, please read
http://www.octave.org/bugs.html to learn how to write a helpful report).

For information about changes from previous versions, type `news'.

octave:1> function concat(a,b,c)
> disp(strcat(a,c,c,b));
> endfunction
octave:2> concat("Rosetta","Code",":");
Rosetta::Code
octave:3>


: bloopAbs
| bl m |
   System.VERSION println

   Word find("bloop") ->bl
   bl isA(Constant) ifFalse: [ "bloop constant does not exist" println return ]

   "abs" asMethod ->m
   m ifNull: [ "abs method does not exist" println return ]

   System.Out "bloop value is : " << bl value << cr
   System.Out "bloop abs   is : " << bl value m perform << cr ;


$ rtlversion "0.4.0"
'
#if not match(rtlversion,o2version)
   #error "This RTL version mismatches o2 version "+o2version
#else
  print o2version
#endif

float bloop=-1618

#ifdef bloop
  #ifdef abs
    print abs(bloop)
  #endif
#endif


declare
  Version = {Property.get 'oz.version'}
  %% Version is an atom like '1.4.0'. So we can not compare it directly.
  %% Extract the version components:
  [Major Minor Release] = {Map {String.tokens {Atom.toString Version} &.} String.toInt}
in
  if Major >= 1 andthen  Minor >= 4 then
     %% check whether module Number exports a value 'abs':
     if {HasFeature Number abs} then
        {Show {Number.abs ~42}}
     end
  else
     {System.showInfo "Your Mozart version is too old."}
  end


if(lex(version(), [2,4,3]) < 0, quit()); \\ Compare the version to 2.4.3 lexicographically

if(bloop!='bloop && type(abs) == "t_CLOSURE", abs(bloop))


$ ol
Welcome to Otus Lisp 2.1-2282-27a9b6c
type ',help' to help, ',quit' to end session.
> (define (f head tail mid)
     (string-append head mid mid tail))
;; Defined f
> (f "Rosetta" "Code" ":")
"Rosetta::Code"
> ,quit
bye-bye :/


D:\>rexx rexxtry ?
 This procedure lets you interactively try REXX statements.
 If you run it with no parameter, or with a question mark
 as a parameter, it will briefly describe itself.
 You may also enter a REXX statement directly on the command line
 for immediate execution and exit.  Example:  rexxtry call show

 Enter 'call show' to see user variables provided by REXXTRY.
 Enter '=' to repeat your previous statement.
 Enter '?' to invoke system-provided online help for REXX.
 The subroutine named 'sub' can be CALLed or invoked as 'sub()'.
 REXXTRY can be run recursively with CALL.

 Except for the signal instructions after a syntax error, this
 procedure is an example of structured programming.

D:\>rexx rexxtry
REXX-ooRexx_4.2.0(MT)_64-bit 6.04 22 Feb 2014
  rexxtry.rex lets you interactively try REXX statements.
    Each string is executed when you hit Enter.
    Enter 'call tell' for a description of the features.
  Go on - try a few...            Enter 'exit' to end.
x=3
  ........................................... rexxtry.rex on WindowsNT
y=x**2
  ........................................... rexxtry.rex on WindowsNT
say x y
3 9
  ........................................... rexxtry.rex on WindowsNT

  rexxtry.rex:  Enter 'exit' to end.       Or '?' for online REXX help.
say sigl
160
  ........................................... rexxtry.rex on WindowsNT
say sourceline(12)
/* Redistribution and use in source and binary forms, with or                 */
  ........................................... rexxtry.rex on WindowsNT
exit

D:\>


declare fun {F As Bs Sep} {Append As Sep|Sep|Bs} end


$ perl -de1

Loading DB routines from perl5db.pl version 1.3
Editor support available.

Enter h or `h h' for help, or `man perldebug' for more help.

main::(-e:1):   1
  DB<1> sub f {my ($s1, $s2, $sep) = @_; $s1 . $sep . $sep . $s2}

  DB<2> p f('Rosetta', 'Code', ':')
Rosetta::Code
  DB<3> q


require v5.6.1;    # run time version check
require 5.6.1;     # ditto
require 5.006_001; # ditto; preferred for backwards compatibility


requires("0.8.2")           -- crashes on 0.8.1 and earlier
requires(WINDOWS)           -- crashes on Linux
requires(64)                -- crashes on 32-bit


_version 1.0 < if "Interpreter version is old" else "Last version" endif print


<?php

if (version_compare(PHP_VERSION, '5.3.0', '<' ))
{
	echo("You are using PHP Version " . PHP_VERSION . ". Please upgrade to Version 5.3.0\n");
	exit();
}
$bloop = -3;
if (isset($bloop) && function_exists('abs'))
{
	echo(abs($bloop));
}
echo(count($GLOBALS) . " variables in global scope.\n");
echo(array_sum($GLOBALS) . " is the total of variables in global scope.\n");

?>


C:\Program Files (x86)\Phix>p -repl
Warning: the repl is brand new, experimental, incomplete, and liable to crash!
Enter a statement such as "?remainder(floor(250/8),8)" or "puts(1,"Hi")"

>function f(string a,b,c) return a&c&c&b end function

>?f("Rosetta","Code",":")
"Rosetta::Code"

>quit
C:\Program Files (x86)\Phix>


Picat> cl
f(X,Y,Sep) = X ++ [Sep,Sep] ++ Y.
<Ctrl-D>
Picat> print(f("Rosetta","Code",':'))
Rosetta::Code
yes


$ pike
Pike v7.8 release 352 running Hilfe v3.5 (Incremental Pike Frontend)
> string f(string first, string second, string sep){
>>   return(first + sep + sep + second);
>> }
> f("Rosetta","Code",":");
(1) Result: "Rosetta::Code"
>


Windows PowerShell
Copyright (C) 2009 Microsoft Corporation. All rights reserved.

PS Home:\> function f ([string] $string1, [string] $string2, [string] $separator) {
>>     $string1 + $separator * 2 + $string2
>> }
>>
PS Home:\> f 'Rosetta' 'Code' ':'
Rosetta::Code
PS Home:\>


% library(win_menu) compiled into win_menu 0.00 sec, 12,872 bytes
% library(swi_hooks) compiled into pce_swi_hooks 0.00 sec, 2,404 bytes
% The graphical front-end will be used for subsequent tracing
% c:/users/joel-seven/appdata/roaming/swi-prolog/pl.ini compiled 0.13 sec, 876,172 bytes
XPCE 6.6.66, July 2009 for Win32: NT,2000,XP
Copyright (C) 1993-2009 University of Amsterdam.
XPCE comes with ABSOLUTELY NO WARRANTY. This is free software,
and you are welcome to redistribute it under certain conditions.
The host-language is SWI-Prolog version 5.10.0

For HELP on prolog, please type help. or apropos(topic).
         on xpce, please type manpce.

1 ?- assert((f(A, B,C) :- format('~w~w~w~w~n', [A, C, C, B]))).
true.

2 ?- f('Rosetta', 'Code', ':').
Rosetta::Code
true.

3 ?-


(unless (>= (version T) (3 0 1))       # Check version (only in the 64-bit version)
   (bye) )

# (setq bloop -7)                      # Uncomment this to get the output '7'

(and
   (num? bloop)                        # When 'bloop' is bound to a number
   (getd 'abs)                         # and 'abs' defined as a function
   (println (abs bloop)) )             # then print the absolute value


   S = SYSVERSION();
   if substr(S, 6, 6) < '050000' then
      do; put skip list ('Version of compiler is too old'); stop; end;


;;; Exit if version below 15.00
if pop_internal_version < 150000 then
    sysexit()
endif;


#COMPILER PBWIN 9
#COMPILER PBWIN, PBCC 5


# version is found in $PSVersionTable
if ($PSVersionTable['PSVersion'] -lt '2.0') {
    exit
}

if ((Test-Path Variable:bloop) -and ([Math]::Abs)) {
    [Math]::Abs($bloop)
}

# find integer variables and their sum
Get-Variable -Scope global `
    | Where-Object { $_.Value -is [int] } `
    | Measure-Object -Sum Value `
    | Select-Object Count,Sum


python
Python 2.6.1 (r261:67517, Dec  4 2008, 16:51:00) [MSC v.1500 32 bit (Intel)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> def f(string1, string2, separator):
	return separator.join([string1, '', string2])

>>> f('Rosetta', 'Code', ':')
'Rosetta::Code'
>>>


 > quackery

Welcome to Quackery.

Enter "leave" to leave the shell.

/O> say " now entering a nested shell..."
... shell
...
 now entering a nested shell...
/O> say " now leaving the nested shell"
... leave
...
 now leaving the nested shell
Auf wiedersehen.

Stack empty.

/O> say " now leaving the shell invoked at the command line"
... leave
...
 now leaving the shell invoked at the command line
Goodbye.

 > echo " back at the command line"
 back at the command line
 >


$ R

R version 2.7.2 (2008-08-25)
Copyright (C) 2008 The R Foundation for Statistical Computing
ISBN 3-900051-07-0

R is free software and comes with ABSOLUTELY NO WARRANTY.
You are welcome to redistribute it under certain conditions.
Type 'license()' or 'licence()' for distribution details.

  Natural language support but running in an English locale

R is a collaborative project with many contributors.
Type 'contributors()' for more information and
'citation()' on how to cite R or R packages in publications.

Type 'demo()' for some demos, 'help()' for on-line help, or
'help.start()' for an HTML browser interface to help.
Type 'q()' to quit R.

> f <- function(a, b, s) paste(a, "", b, sep=s)
> f("Rosetta", "Code", ":")
[1] "Rosetta::Code"
> q()
Save workspace image? [y/n/c]: n


oiseau:/tmp> racket
Welcome to Racket v5.3.3.5.
> (define (f string-1 string-2 separator)
    (string-append string-1 separator separator string-2))
> (f "Rosetta" "Code" ":")
"Rosetta::Code"
> ^D
oiseau:/tmp>


$ rakudo/perl6
> sub f($str1,$str2,$sep) { $str1~$sep x 2~$str2 };
f
> f("Rosetta","Code",":");
Rosetta::Code
>


$ rebol -q
>> f: func [a b s] [print rejoin [a s s b]]
>> f "Rosetta" "Code" ":"
Rosetta::Code
>> q


CompilerIf #PB_Compiler_Version<441
  CompilerError "You failed the version check!"
CompilerEndIf

CompilerIf   Defined(bloop,#PB_Variable)
  CompilerIf Defined(Abs(),#PB_Function)
    Abs(bloop)
  CompilerEndIf
CompilerEndIf


# Checking for system version
 import sys
 major, minor, bugfix = sys.version_info[:3]
 if major < 2:
     sys.exit('Python 2 is required')

 def defined(name): # LBYL (Look Before You Leap)
     return name in globals() or name in locals() or name in vars(__builtins__)

 def defined2(name): # EAFP (Easier to Ask Forgiveness than Permission)
     try:
          eval(name)
          return True
     except NameError:
          return False

 if defined('bloop') and defined('abs') and callable(abs):
     print abs(bloop)

 if defined2('bloop') and defined2('abs') and callable(abs):
     print abs(bloop)


if(getRversion() < "2.14.1")
{
   warning("Your version of R is older than 2.14.1")
   q()  # exit R, with the option to cancel
}


#lang racket
(unless (string<=? "5.3" (version)) (error "ancient version"))


:f (sss-s) [ s:prepend ] sip s:prepend s:append ;
'Rosetta 'Code ': f


/*REXX*/  parse arg a b c
say f(a,b,c)
exit
f:return arg(1)arg(3)arg(3)arg(2)


r = "Rosetta"
c = "Code"
s = ":"
see r+s+s+c


$ irb
irb(main):001:0> def f(string1, string2, separator)
irb(main):002:1>     [string1, '', string2].join(separator)
irb(main):003:1> end
=> :f
irb(main):004:0> f('Rosetta', 'Code', ':')
=> "Rosetta::Code"
irb(main):005:0> exit
$


name: myapp
version: "1.0"
author: A Rust Developer <[email protected]>
about: Does awesome things
args:
  - STRING1:
      about: First string to use
      required: true
      index: 1
  - STRING2:
      about: Second string to use
      required: true
      index: 2
  - SEPARATOR:
      about: Separtor to use
      required: true
      index: 3


my $bloop = -123;

if MY::{'$bloop'}.defined and CORE::{'&abs'}.defined { say abs $bloop }

my @ints = ($_ when Int for PROCESS::.values);
say "Number of PROCESS vars of type Int: ", +@ints;
say "PROCESS vars of type Int add up to ", [+] @ints;


VERSION 0 prefer 20071104 <
if  'version >= 20071104 required' print bye

'bloop' GLOBAL keys in && 'abs' CORE keys in
if  bloop abs print


                                /*output from parse version (almost all REXX versions)  */
                                /*      theREXXinterpreterName level mm Mon yyyy        */
parse version . level .
if level<4  then exit


C:\>scala
Welcome to Scala version 2.8.0.r21356-b20100407020120 (Java HotSpot(TM) Client V
M, Java 1.6.0_05).
Type in expressions to have them evaluated.
Type :help for more information.

scala> "rosetta"
res0: java.lang.String = rosetta


> scheme
Scheme Microcode Version 14.9
MIT Scheme running under FreeBSD
Type `^C' (control-C) followed by `H' to obtain information about interrupts.
Scheme saved on Monday June 17, 2002 at 10:03:44 PM
  Release 7.7.1
  Microcode 14.9
  Runtime 15.1

1 ]=> (define (f string-1 string-2 separator)
        (string-append string-1 separator separator string-2))

;Value: f

1 ]=> (f "Rosetta" "Code" ":")

;Value 1: "Rosetta::Code"

1 ]=> ^D
End of input stream reached
Happy Happy Joy Joy.
>


$ sidef -i
>>> func f(s1, s2, sep) { s1 + sep*2 + s2 };
f
>>> f('Rosetta', 'Code', ':')
"Rosetta::Code"
>>>


slate[1]> [email protected](String traits) rosettaWith: [email protected](String traits) and: [email protected](String traits) [s ; s3 ; s3 ; s2].
[rosettaWith:and:]
slate[2]> 'Rosetta' rosettaWith: 'Code' and: ':'.
'Rosetta::Code'


$ gst
GNU Smalltalk ready

st> |concat|
st> concat := [ :a :b :c | (a,c,c,b) displayNl ].
a BlockClosure
st> concat value: 'Rosetta' value: 'Code' value: ':'.
Rosetta::Code
'Rosetta::Code'
st>


>spitbol code
SPITBOL-386   Release 3.7(ver 1.30.20)   Serial xxxxx
...
Enter SPITBOL statements:
? define('f(a,b,s)'):(z);f f = a s s b:(return);z
Success
?= f('Rosetta','Code',':')
Rosetta::Code
Success
?end
>


$ sml
Standard ML of New Jersey v110.67 [built: Fri Jul  4 09:00:58 2008]
- fun f (s1, s2, sep) = String.concatWith sep [s1, "", s2];
[autoloading]
[library $SMLNJ-BASIS/basis.cm is stable]
[autoloading done]
val f = fn : string * string * string -> string
- f ("Rosetta", "Code", ":");
val it = "Rosetta::Code" : string
-


# Project: Introspection

if version() < 1.8
   see "Version is too old" + " (" + version() + ")" + nl
else
   see "Version is uptodate" + " (" + version() + ")" + nl
ok
bloop = 5
if isglobal("bloop") = 1
   see "Variable " + "'bloop'" + " exists" + nl
else
   see "Variable " + "'bloop'" + " doesn't exist" + nl
ok
if isglobal("bleep") = 1
   see "Variable " + "'bleep'" + " exists" + nl
else
   see "Variable " + "'bleep'" + " doesn't exist" + nl
ok
if isfunction("abs") = 1
   see "Function " + "'abs'" + " is defined" + nl
else
   see "Function " + "'abs'" + " is not defined" + nl
ok
if isfunction("abc") = 1
   see "Function " + "'abc'" + " is defined" + nl
else
   see "Function " + "'abc'" + " is not defined" + nl
ok

func abs(bloop)
        return fabs(bloop)


exit if RUBY_VERSION < '1.8.6'
puts bloop.abs if defined?(bloop) and bloop.respond_to?(:abs)


object VersCheck extends App {
  val minimalVersion = 1.7

  val vers = System.getProperty("java.specification.version");
  println(if (vers.toDouble >= minimalVersion) "YAY!" else s"Must use Java >= $minimalVersion");

  val bloop = Option(-42)
  if (bloop.isDefined) bloop.get.abs
}


Platform run: StartupArguments first ; ' --version'.


| s v t sum hm |
"uncomment the following to see what happens if bloop exists"
"Smalltalk at: #bloop put: -10."
s := Smalltalk version.
(s =~ '(\d+)\.(\d+)\.(\d+)')
  ifMatched: [:match |
       v := (( (match at: 1) asInteger ) * 100) +
            (( (match at: 2) asInteger ) * 10) +
            ( (match at: 3) asInteger )
  ].
( v < 300 )
  ifTrue: [
     Transcript show: 'I need version 3.0.0 or later' ; cr ]
  ifFalse: [
     Transcript show: 'Ok! I can run!' ; cr .
     "does bloop exists as global var?"
     t := Smalltalk at: #bloop
            ifAbsent: [
                 Transcript show: 'bloop var does not exist as global!' ; cr .
                 ^nil
            ].
     (t respondsTo: #abs)
          ifTrue:
             [ Transcript show: 'Absolute value of bloop: ' ;
                     show: (t abs) printString ; cr ].
  ] .

"how many 'numbers' in global scope, and compute their sums"
hm := 0.
sum := 0.
(Smalltalk keys) do: [ :els |
        ( (Smalltalk at: els) isKindOf: Number )
          ifTrue: [ hm := hm + 1.
                    sum := sum + (Smalltalk at: els).
                    "Transcript show: (els asString) ; cr" ]
    ] .
Transcript show: 'Num of global numeric vars: '; show: (hm printString); cr ;
           show: 'Sum of global numeric vars: '; show: (sum printString) ; cr.


$ tclsh
% proc f {s1 s2 sep} {
    append result $s1 $sep $sep $s2
}
% f Rosetta Code :
Rosetta::Code
% exit


■ x & s & s & y → f(x,y,s)
                                  Done
■ f("Rosetta", "Code", ":")
                       "Rosetta::Code"


package require Tcl 8.4 ; # throws an error if older
if {[info exists bloop] && [llength [info functions abs]]} {
    puts [expr abs($bloop)]
}


()
Prgm
  Local l, i, vers
  getConfg() → l
  For i,1,dim(l),2
    If l[i] = "OS Version" or l[i] = "Version" Then
      l[i + 1] → vers
      Disp "Version: " & vers
      If expr(right(vers, 4)) < 2005 Then  © Lousy parsing strategy
        Disp vers & " is too old"
        Stop
      EndIf
    EndIf
  EndFor

  If isVar(bloop) Then        © Dynamic name check can be done with isVar(#aString)
    © Builtin functions cannot be tested for.
    Disp abs(bloop)
  Else
    Disp "No bloop"
  EndIf

  © There is no way to get a list of global variables.
EndPrgm


case ${.sh.version} in
    *93[[:alpha:]]+*) :;; #this appears to be ksh93, we're OK
    *)  echo "version appears to be too old"
        exit              # otherwise, bail out
        ;;
esac

if [[ -z ${bloop+bloop has a value} ]]; then
    print "no bloop variable"
elsif (( abs(1) )); then
    print -- $(( abs(bloop) ))
fi

typeset -a int_vars
set | while IFS='=' read -r var value; do
    if [[ $value == +([[:digit:]]) ]]; then
        int_vars[n++]=$var
        let sum += $value
    fi
done
print "${int_vars[*]}"
print -- $sum


$ sh
sh-3.2$ concat() { echo "$1$3$3$2"; }
sh-3.2$ concat Rosetta Code :
Rosetta::Code
sh-3.2$


$ java -jar ursa.jar
cygnus/x ursa v0.76 (default, release 1)
[Oracle Corporation JVM 1.8.0_91 on Linux 3.16.0-4-686-pae i386]
> def f (string s1, string s2, string sep)
..	return (+ s1 sep sep s2)
..end
> out (f "Rosetta" "Code" ":") endl console
Rosetta::Code
> _


XLISP 3.3, September 6, 2002 Copyright (c) 1984-2002, by David Betz
[1] (defun f (a b sep)
        (string-append a sep sep b))

F
[2] (f "Rosetta" "Code" ":")

"Rosetta::Code"
[3]


$ ./wren
\\/"-
 \_/   wren v0.2.0
> var f = Fn.new { |s1, s2, sep| s1 + sep + sep + s2 }
> f.call("Rosetta", "Code", ":")
Rosetta::Code
>
^C
$


$ zkl
zkl 1.12.8, released 2014-04-01
zkl: fcn f(a,b,c){String(a,c,c,b)}
Void
zkl: f("Rosetta", "Code", ":")
Rosetta::Code
zkl:


#import std
#import flo
#import lag

maybe_abs = math.|fabs (%QI flo)-:~&! 'abs'

#preprocess version==-[0.10.2]-?\<'wrong version'>!% *^0 ||~& -&
   -&~&vitB,~&d.lexeme=='=',~&vhd.lexeme=='bloop',~&vthd.lexeme=='(evaluated)'&-,
   &vthd.semantics:= !+ !+ maybe_abs+ ~&vthd.semantics.&iNHiNH&-

#cast %e

bloop = -1.


If Application.Version < 15 Then Exit Sub


import "os" for Platform, Process
import "io" for File
import "meta" for Meta
import "/pattern" for Pattern
import "/math" for Nums

var a = 4    /* 1st integer variable */
var b = 0xA  /* 2nd integer variable */
var c = -8   /* 3rd integer variable */

var bloop = -17.3

var checkVersion = Fn.new {
    var version = Process.version
    var components = version.split(".")
    if (Num.fromString(components[1]) < 3) {
        Fiber.abort("Wren version (%(version)) is too old.")
    }
}

var globalIntVars = Fn.new {
    var sep = Platform.isWindows ? "\r\n" : "\n"
    var lines = File.read(Process.allArguments[1]).split(sep)
    var p = Pattern.new("var+1/s[+1/x]+1/s/=+1/s[0x+1/h|~-+1/d]+0/s", Pattern.whole)
    var q = Pattern.new("[////|//*]+0/z", Pattern.end)
    var vars = []
    var vals = []
    for (line in lines) {
        line = q.replaceAll(line, "") // get rid of any comments
        var m = p.find(line)
        if (m) {
            vars.add(m.capsText[0])
            vals.add(Num.fromString(m.capsText[1]))
        }
    }
    return [vars, vals]
}

checkVersion.call()
var res = globalIntVars.call()
var d
Meta.eval("d = bloop.abs") // this won't compile if either 'bloop' or 'abs' not available
System.print("bloop.abs = %(d)")
var vars = res[0]
var vals = res[1]
System.print("The sum of the %(vars.count) integer variables, %(vars), is %(Nums.sum(vals))"


if peek("version") < 2.63 error "Interpreter version is too old!"


Language.version //-->L(1,12,8,"2014-04-01")
if (Language.version[1] < 10) System.exit("Too old");
var bloop=-123;
if ((1).resolve("abs",1) and resolve("bloop",8)) bloop.abs().println()


10 LET totram=PEEK 23732 + 256 * PEEK 23733: REM Check that we have a 48k machine
20 IF totram < 65535 THEN PRINT "Your 16k Spectrum is too old": STOP
30 REM variables must exist before they are used, otherwise we get an error
40 REM we can poke a new error handler and check for variable not found.
50 REM I haven't implemented this, because I have forgotten the handler address
60 LET bloob = -4: REM make sure bloob exists, by creating it.
70 PRINT ABS(bloob): REM function will be present, ZX Spectrum Basic is standardized.


F commatize(number, step = 3, sep = ‘,’)
   V s = reversed(String(number))
   String r = s[0]
   L(i) 1 .< s.len
      I i % step == 0
         r ‘’= sep
      r ‘’= s[i]
   R reversed(r)

F isqrt(BigInt x)
   assert(x >= 0)

   V q = BigInt(1)
   L q <= x
      q *= 4

   V z = x
   V r = BigInt(0)
   L q > 1
      q I/= 4
      V t = z - r - q
      r I/= 2
      I t >= 0
         z = t
         r += q

   R r

print(‘The integer square root of integers from 0 to 65 are:’)
L(i) 66
   print(isqrt(BigInt(i)), end' ‘ ’)
print()

print(‘The integer square roots of powers of 7 from 7^1 up to 7^73 are:’)
print(‘power                                    7 ^ power                                                 integer square root’)
print(‘----- --------------------------------------------------------------------------------- -----------------------------------------’)
V pow7 = BigInt(7)
V bi49 = BigInt(49)
L(i) (1..73).step(2)
   print(‘#2 #84 #41’.format(i, commatize(pow7), commatize(isqrt(pow7))))
   pow7 *= bi49


with Ada.Text_Io;
with Ada.Numerics.Big_Numbers.Big_Integers;
with Ada.Strings.Fixed;

procedure Integer_Square_Root is

   use Ada.Numerics.Big_Numbers.Big_Integers;
   use Ada.Text_Io;

   function Isqrt (X : Big_Integer) return Big_Integer is
      Q       : Big_Integer := 1;
      Z, T, R : Big_Integer;
   begin
      while Q <= X loop
         Q := Q * 4;
      end loop;
      Z := X;
      R := 0;
      while Q > 1 loop
         Q := Q / 4;
         T := Z - R - Q;
         R := R / 2;
         if T >= 0 then
            Z := T;
            R := R + Q;
         end if;
      end loop;
      return R;
   end Isqrt;

   function Commatize (N : Big_Integer; Width : Positive) return String is
      S     : constant String := To_String (N, Width);
      Image : String (1 .. Width + Width / 3) := (others => ' ');
      Pos   : Natural := Image'Last;
   begin
      for I in S'Range loop
         Image (Pos) := S (S'Last - I + S'First);
         exit when Image (Pos) = ' ';
         Pos := Pos - 1;
         if I mod 3 = 0 and S (S'Last - I + S'First - 1) /= ' ' then
            Image (Pos) := ''';
            Pos := Pos - 1;
         end if;
      end loop;
      return Image;
   end Commatize;

   type Mode_Kind is (Tens, Ones, Spacer, Result);
begin
   Put_Line ("Integer square roots of integers 0 .. 65:");
   for Mode in Mode_Kind loop
      for N in 0 .. 65 loop
         case Mode is
            when Tens   =>  Put ((if N / 10 = 0
                                  then "  "
                                  else Natural'Image (N / 10)));
            when Ones   =>  Put (Natural'Image (N mod 10));
            when Spacer =>  Put ("--");
            when Result =>  Put (To_String (Isqrt (To_Big_Integer (N))));
         end case;
      end loop;
      New_Line;
   end loop;
   New_Line;

   declare
      package Integer_Io is new Ada.Text_Io.Integer_Io (Natural);
      use Ada.Strings.Fixed;
      N    : Integer    := 1;
      P, R : Big_Integer;
   begin
      Put_Line ("|  N|" & 80 * " " & "7**N|" & 30 * " " & "isqrt (7**N)|");
      Put_Line (133 * "=");
      loop
         P := 7**N;
         R := Isqrt (P);
         Put ("|");  Integer_Io.Put (N, Width => 3);
         Put ("|");  Put (Commatize (P, Width => 63));
         Put ("|");  Put (Commatize (R, Width => 32));
         Put ("|");  New_Line;
         exit when N >= 73;
         N := N + 2;
      end loop;
      Put_Line (133 * "=");
   end;

end Integer_Square_Root;


BEGIN # Integer square roots #
    PR precision 200 PR
    # returns the integer square root of x; x must be >= 0                   #
    PROC isqrt = ( LONG LONG INT x )LONG LONG INT:
         IF   x < 0 THEN print( ( "Negative number in isqrt", newline ) );stop
         ELIF x < 2 THEN x
         ELSE
            # x is greater than 1                                            #
            # find a power of 4 that's greater than x                        #
            LONG LONG INT q := 1;
            WHILE q <= x DO q *:= 4 OD;
            # find the root                                                  #
            LONG LONG INT z := x;
            LONG LONG INT r := 0;
            WHILE q > 1 DO
                q OVERAB 4;
                LONG LONG INT t = z - r - q;
                r OVERAB 2;
                IF t >= 0 THEN
                    z  := t;
                    r +:= q
                FI
            OD;
            r
         FI; # isqrt #
    # returns a string representation of n with commas                       #
    PROC commatise = ( LONG LONG INT n )STRING:
         BEGIN
            STRING result      := "";
            STRING unformatted  = whole( n, 0 );
            INT    ch count    := 0;
            FOR c FROM UPB unformatted BY -1 TO LWB unformatted DO
                IF   ch count <= 2 THEN ch count +:= 1
                ELSE                    ch count  := 1; "," +=: result
                FI;
                unformatted[ c ] +=: result
            OD;
            result
         END; # commatise #
    # left-pads a string to at least n characters                            #
    PROC pad left = ( STRING s, INT n )STRING:
         BEGIN
             STRING result := s;
             WHILE ( UPB result - LWB result ) + 1 < n DO " " +=: result OD;
             result
         END; # pad left #
    # task test cases #
    print( ( "Integer square roots of 0..65", newline ) );
    FOR i FROM 0 TO 65 DO print( ( " ", whole( isqrt( i ), 0 ) ) ) OD;
    print( ( newline ) );
    # integer square roots of odd powers of 7                                #
    print( ( "Integer square roots of 7^n", newline ) );
    print( ( " n|", pad left( "7^n", 82 ), "|", pad left( "isqrt(7^n)", 42 ), newline ) );
    LONG LONG INT p7 := 7;
    FOR p BY 2 TO 73 DO
        print( ( whole( p, -2 )
               , "|"
               , pad left( commatise(        p7   ), 82 )
               , "|"
               , pad left( commatise( isqrt( p7 ) ), 42 )
               , newline
               )
             );
        p7 *:= 49
    OD
END


BEGIN

% RETURN INTEGER SQUARE ROOT OF N %
INTEGER FUNCTION ISQRT(N);
INTEGER N;
BEGIN
    INTEGER R1, R2;
    R1 := N;
    R2 := 1;
    WHILE R1 > R2 DO
        BEGIN
            R1 := (R1+R2) / 2;
            R2 := N / R1;
        END;
    ISQRT := R1;
END;

COMMENT - LET'S EXERCISE THE FUNCTION;

INTEGER I, COL;
WRITE("INTEGER SQUARE ROOT OF FIRST 65 NUMBERS:");
WRITE("");
COL := 1;
FOR I := 1 STEP 1 UNTIL 65 DO
    BEGIN
        WRITEON(ISQRT(I));
        COL := COL + 1;
        IF COL > 10 THEN
            BEGIN
                WRITE("");
                COL := 1;
            END;
    END;

WRITE("");
WRITE("     N    7^N  ISQRT");
WRITE("--------------------");
COMMENT - ODD POWERS OF 7 GREATER THAN 3 WILL CAUSE OVERFLOW;
FOR I := 1 STEP 2 UNTIL 3 DO
    BEGIN
        INTEGER POW7;
        POW7 := 7**I;
        WRITE(I, POW7, ISQRT(POW7));
    END;
WRITE("THAT'S ALL. GOODBYE.");

END


on isqrt(x)
    set q to 1
    repeat until (q > x)
        set q to q * 4
    end repeat
    set z to x
    set r to 0
    repeat while (q > 1)
        set q to q div 4
        set t to z - r - q
        set r to r div 2
        if (t > -1) then
            set z to t
            set r to r + q
        end if
    end repeat

    return r
end isqrt

-- Task code
on intToText(n, separator)
    set output to ""
    repeat until (n < 1000)
        set output to separator & (text 2 thru 4 of ((1000 + (n mod 1000) as integer) as text)) & output
        set n to n div 1000
    end repeat

    return (n as integer as text) & output
end intToText

on doTask()
    -- Get the integer and power results.
    set {integerResults, powerResults} to {{}, {}}
    repeat with x from 0 to 65
        set end of integerResults to isqrt(x)
    end repeat
    repeat with p from 1 to 73 by 2
        set x to 7 ^ p
        if (x > 1.0E+15) then exit repeat -- Beyond the precision of AppleScript reals.
        set end of powerResults to "7^" & p & tab & "(" & intToText(x, ",") & "):" & (tab & tab & intToText(isqrt(x), ","))
    end repeat
    -- Format and output.
    set astid to AppleScript's text item delimiters
    set AppleScript's text item delimiters to space
    set output to {"Isqrts of integers from 0 to 65:", space & integerResults, ¬
        "Isqrts of odd powers of 7 from 1 to " & (p - 2) & ":", powerResults}
    set AppleScript's text item delimiters to linefeed
    set output to output as text
    set AppleScript's text item delimiters to astid

    return output
end doTask

doTask()


 i←{x←⍵
    q←(×∘4)⍣{⍺>x}⊢1
    ⊃{  r z q←⍵
        q←⌊q÷4
        t←(z-r)-q
        r←⌊r÷2
        z←z t[1+t≥0]
        r←r+q×t≥0
        r z q
    }⍣{ r z q←⍺
        q≤1
    }⊢0 x q
 }


commatize: function [x][
    reverse join.with:"," map split.every: 3 split reverse to :string x => join
]

isqrt: function [x][
    num: new x
    q: new 1
    r: new 0

    while [q =< num]-> shl.safe 'q 2
    while [q > 1][
        shr 'q 2
        t: (num-r)-q
        shr 'r 1
        if t >= 0 [
            num: t
            r: new r+q
        ]
    ]
    return r
]

print map 0..65 => isqrt

loop range 1 .step: 2 72 'n ->
    print [n "\t" commatize isqrt 7^n]


(*

Compile with "myatscc isqrt.dats", thus obtaining an executable called
"isqrt".

##myatsccdef=\
patscc -O2 \
  -I"${PATSHOME}/contrib/atscntrb" \
  -IATS "${PATSHOME}/contrib/atscntrb" \
  -D_GNU_SOURCE -DATS_MEMALLOC_LIBC \
  -o $fname($1) $1 -lgmp

*)

#include "share/atspre_staload.hats"

(* An interface to GNU Multiple Precision. The type system will help
   ensure that you do "mpz_clear" on whatever you allocate. *)
staload "atscntrb-hx-libgmp/SATS/gmp.sats"

(* As of this writing, gmp.dats is empty, but it does no harm to
   staload it. *)
staload _ = "atscntrb-hx-libgmp/DATS/gmp.dats"

fn
find_a_power_of_4_greater_than_x
          (x : &mpz,            (* Input. *)
           q : &mpz? >> mpz)    (* Output. *)
    : void =
  let
    fun
    loop (x : &mpz, q : &mpz) : void =
      if 0 <= mpz_cmp (x, q) then
        begin
          mpz_mul (q, 4u);
          loop (x, q)
        end
  in
    mpz_init_set (q, 1u);
    loop (x, q)
  end

fn
isqrt_and_remainder
          (x : &mpz,            (* Input. *)
           r : &mpz? >> mpz,    (* Output: square root. *)
           z : &mpz? >> mpz)    (* Output: remainder. *)
    : void =
  let
    fun
    loop (q : &mpz, z : &mpz, r : &mpz, t : &mpz) : void =
      if 0 < mpz_cmp (q, 1u) then
        begin
          mpz_tdiv_q (q, 4u);
          mpz_set_mpz (t, z);
          mpz_sub (t, r);
          mpz_sub (t, q);
          mpz_tdiv_q (r, 2u);
          if 0 <= mpz_cmp (t, 0u) then
            begin
              mpz_set_mpz (z, t);
              mpz_add (r, q);
            end;
          loop (q, z, r, t);
        end

    var q : mpz
    var t : mpz
  in
    find_a_power_of_4_greater_than_x (x, q);
    mpz_init_set (z, x);
    mpz_init_set (r, 0u);
    mpz_init (t);

    loop (q, z, r, t);

    mpz_clear (q);
    mpz_clear (t);
  end

fn
isqrt (x : &mpz,                (* Input. *)
       r : &mpz? >> mpz)        (* Output: square root. *)
    : void =
  let
    var z : mpz
  in
    isqrt_and_remainder (x, r, z);
    mpz_clear (z);
  end

fn
print_n_spaces (n : uint) : void =
  let
    var i : [i : nat] uint i
  in
    for (i := 0u; i < n; i := succ i)
      print! (" ")
  end

fn
print_with_commas (n           : &mpz,
                   num_columns : uint) : void =
  let
    fun
    make_list (q   : &mpz,
               r   : &mpz,
               lst : List0_vt char,
               i   : uint) : List_vt char =
      if mpz_cmp (q, 0u) = 0 then
        lst
      else
        let
          val _ = mpz_tdiv_qr (q, r, 10u)
          val ones_place = mpz_get_int (r)
          val digit = int2char0 (ones_place + char2i '0')
        in
          if i = 3u then
            let
              val lst = list_vt_cons (',', lst)
              val lst = list_vt_cons (digit, lst)
            in
              make_list (q, r, lst, 1u)
            end
          else
            let
              val lst = list_vt_cons (digit, lst)
            in
              make_list (q, r, lst, succ i)
            end
        end

    var q : mpz
    var r : mpz

    val _ = mpz_init_set (q, n)
    val _ = mpz_init (r)
    val char_lst = make_list (q, r, list_vt_nil (), 0u)
    val _ = mpz_clear (q)
    val _ = mpz_clear (r)

    fun
    print_and_consume_lst (char_lst : List0_vt char) : void =
      case+ char_lst of
      | ~ list_vt_nil () => ()
      | ~ list_vt_cons (head, tail) =>
        begin
          print! (head);
          print_and_consume_lst (tail);
        end

    prval _ = lemma_list_vt_param (char_lst)
    val len = i2u (list_vt_length (char_lst))
  in
    assertloc (len <= num_columns);
    print_n_spaces (num_columns - len);
    print_and_consume_lst (char_lst)
  end

fn
do_the_roots_of_0_to_65 () : void =
  let
    var i : mpz
  in
    mpz_init_set (i, 0u);
    while (mpz_cmp (i, 65u) <= 0)
      let
        var r : mpz
      in
        isqrt (i, r);
        fprint (stdout_ref, r);
        print! (" ");
        mpz_add (i, 1u);
        mpz_clear (r);
      end;
    mpz_clear (i);
  end

fn
do_the_roots_of_odd_powers_of_7 () : void =
  let
    var seven : mpz
    var seven_raised_i : mpz
    var i_mpz : mpz
    var i : [i : pos] uint i
  in
    mpz_init_set (seven, 7u);
    mpz_init (seven_raised_i);
    mpz_init (i_mpz);
    for (i := 1u; i <= 73u; i := succ (succ i))
      let
        var r : mpz
      in
        mpz_pow_uint (seven_raised_i, seven, i);
        isqrt (seven_raised_i, r);
        mpz_set_uint (i_mpz, i);
        print_with_commas (i_mpz, 2u);
        print! (" ");
        print_with_commas (seven_raised_i, 84u);
        print! (" ");
        print_with_commas (r, 43u);
        print! ("\n");
        mpz_clear (r);
      end;
    mpz_clear (seven);
    mpz_clear (seven_raised_i);
    mpz_clear (i_mpz);
  end

implement
main0 () =
  begin
    print! ("isqrt(i) for 0 <= i <= 65:\n\n");
    do_the_roots_of_0_to_65 ();
    print! ("\n\n\n");
    print! ("isqrt(7**i) for 1 <= i <= 73, i odd:\n\n");
    print! (" i                                                                                7**i                                  sqrt(7**i)\n");
    print! ("-----------------------------------------------------------------------------------------------------------------------------------\n");
    do_the_roots_of_odd_powers_of_7 ();
  end


print "Integer square root of first 65 numbers:"
for n = 1 to 65
    print ljust(isqrt(n),3);
next n
print : print
print "Integer square root of odd powers of 7"
print "  n                 7^n       isqrt"
print "-"*36
for n = 1 to 21 step 2
    pow7 = int(7 ^ n)
    print rjust(n,3);rjust(pow7,20);rjust(isqrt(pow7),12)
next n
end

function isqrt(x)
    q = 1
    while q <= x
        q *= 4
    end while
    r = 0
    while q > 1
        q /= 4
        t = x - r - q
        r /= 2
        if t >= 0 then
            x = t
            r += q
        end if
    end while
    return int(r)
end function


#include <stdint.h>
#include <stdio.h>

int64_t isqrt(int64_t x) {
    int64_t q = 1, r = 0;
    while (q <= x) {
        q <<= 2;
    }
    while (q > 1) {
        int64_t t;
        q >>= 2;
        t = x - r - q;
        r >>= 1;
        if (t >= 0) {
            x = t;
            r += q;
        }
    }
    return r;
}

int main() {
    int64_t p;
    int n;

    printf("Integer square root for numbers 0 to 65:\n");
    for (n = 0; n <= 65; n++) {
        printf("%lld ", isqrt(n));
    }
    printf("\n\n");

    printf("Integer square roots of odd powers of 7 from 1 to 21:\n");
    printf(" n |              7 ^ n | isqrt(7 ^ n)\n");
    p = 7;
    for (n = 1; n <= 21; n += 2, p *= 49) {
        printf("%2d | %18lld | %12lld\n", n, p, isqrt(p));
    }
}


#include <iomanip>
#include <iostream>
#include <sstream>
#include <boost/multiprecision/cpp_int.hpp>

using big_int = boost::multiprecision::cpp_int;

template <typename integer>
integer isqrt(integer x) {
    integer q = 1;
    while (q <= x)
        q <<= 2;
    integer r = 0;
    while (q > 1) {
        q >>= 2;
        integer t = x - r - q;
        r >>= 1;
        if (t >= 0) {
            x = t;
            r += q;
        }
    }
    return r;
}

std::string commatize(const big_int& n) {
    std::ostringstream out;
    out << n;
    std::string str(out.str());
    std::string result;
    size_t digits = str.size();
    result.reserve(4 * digits/3);
    for (size_t i = 0; i < digits; ++i) {
        if (i > 0 && i % 3 == digits % 3)
            result += ',';
        result += str[i];
    }
    return result;
}

int main() {
    std::cout << "Integer square root for numbers 0 to 65:\n";
    for (int n = 0; n <= 65; ++n)
        std::cout << isqrt(n) << ' ';
    std::cout << "\n\n";

    std::cout << "Integer square roots of odd powers of 7 from 1 to 73:\n";
    const int power_width = 83, isqrt_width = 42;
    std::cout << " n |"
        << std::setw(power_width) << "7 ^ n" << " |"
        << std::setw(isqrt_width) << "isqrt(7 ^ n)"
        << '\n';
    std::cout << std::string(6 + power_width + isqrt_width, '-') << '\n';
    big_int p = 7;
    for (int n = 1; n <= 73; n += 2, p *= 49) {
        std::cout << std::setw(2) << n << " |"
            << std::setw(power_width) << commatize(p) << " |"
            << std::setw(isqrt_width) << commatize(isqrt(p))
            << '\n';
    }
    return 0;
}


using System;
using static System.Console;
using BI = System.Numerics.BigInteger;

class Program {

    static BI isqrt(BI x) { BI q = 1, r = 0, t; while (q <= x) q <<= 2; while (q > 1) {
        q >>= 2; t = x - r - q; r >>= 1; if (t >= 0) { x = t; r += q; } } return r; }

    static void Main() { const int max = 73, smax = 65;
        int power_width = ((BI.Pow(7, max).ToString().Length / 3) << 2) + 3,
            isqrt_width = (power_width + 1) >> 1;
        WriteLine("Integer square root for numbers 0 to {0}:", smax);
        for (int n = 0; n <= smax; ++n) Write("{0} ",
            (n / 10).ToString().Replace("0", " ")); WriteLine();
        for (int n = 0; n <= smax; ++n) Write("{0} ", n % 10); WriteLine();
        WriteLine(new String('-', (smax << 1) + 1));
        for (int n = 0; n <= smax; ++n) Write("{0} ", isqrt(n));
        WriteLine("\n\nInteger square roots of odd powers of 7 from 1 to {0}:", max);
        string s = string.Format("[0,2] |[1,{0}:n0] |[2,{1}:n0]",
            power_width, isqrt_width).Replace("[", "{").Replace("]", "}");
        WriteLine(s, "n", "7 ^ n", "isqrt(7 ^ n)");
        WriteLine(new String('-', power_width + isqrt_width + 6));
        BI p = 7; for (int n = 1; n <= max; n += 2, p *= 49)
            WriteLine (s, n, p, isqrt(p)); }
}


% This program uses the 'bigint' cluster from PCLU's 'misc.lib'

% Integer square root of a bigint
isqrt = proc (x: bigint) returns (bigint)
    % Initialize a couple of bigints we will reuse
    own zero: bigint := bigint$i2bi(0)
    own one: bigint := bigint$i2bi(1)
    own two: bigint := bigint$i2bi(2)
    own four: bigint := bigint$i2bi(4)

    q: bigint := one
    while q <= x do q := q * four end

    t: bigint
    z: bigint := x
    r: bigint := zero
    while q>one do
        q := q / four
        t := z - r - q
        r := r / two
        if t >= zero then
            z := t
            r := r + q
        end
    end
    return(r)
end isqrt

% Format a bigint using commas
fmt = proc (x: bigint) returns (string)
    own zero: bigint := bigint$i2bi(0)
    own ten: bigint := bigint$i2bi(10)

    if x=zero then return("0") end
    out: array[char] := array[char]$[]
    ds: int := 0
    while x>zero do
        array[char]$addl(out, char$i2c(bigint$bi2i(x // ten) + 48))
        x := x / ten
        ds := ds + 1
        if x~=zero cand ds//3=0 then
            array[char]$addl(out, ',')
        end
    end
    return(string$ac2s(out))
end fmt

start_up = proc ()
    po: stream := stream$primary_output()

    % print square roots from 0..65
    stream$putl(po, "isqrt of 0..65:")
    for i: int in int$from_to(0, 65) do
        stream$puts(po, fmt(isqrt(bigint$i2bi(i))) || " ")
    end

    % print square roots of odd powers
    stream$putl(po, "\n\nisqrt of odd powers of 7:")
    seven: bigint := bigint$i2bi(7)
    for p: int in int$from_to_by(1, 73, 2) do
        stream$puts(po, "isqrt(7^")
        stream$putright(po, int$unparse(p), 2)
        stream$puts(po, ") = ")
        stream$putright(po, fmt(isqrt(seven ** bigint$i2bi(p))), 41)
        stream$putl(po, "")
    end
end start_up


#!/bin/sh
#|-*- mode:lisp -*-|#
#|
exec ros -Q -- $0 "[email protected]"
|#
(progn ;;init forms
  (ros:ensure-asdf)
  #+quicklisp(ql:quickload '() :silent t)
  )

(defpackage :ros.script.isqrt.3860764029
  (:use :cl))
(in-package :ros.script.isqrt.3860764029)

;;
;; The Rosetta Code integer square root task, in Common Lisp.
;;
;; I translate the tail recursions of the Scheme as regular loops in
;; Common Lisp, although CL compilers most often can optimize tail
;; recursions of the kind. They are not required to, however.
;;
;; As a result, the CL is actually closer to the task's pseudocode
;; than is the Scheme.
;;
;; (The Scheme, by the way, could have been written much as follows,
;; using "set!" where the CL has "setf", and with other such
;; "linguistic" changes.)
;;

(defun find-a-power-of-4-greater-than-x (x)
  (let ((q 1))
    (loop until (< x q)
          do (setf q (* 4 q)))
    q))

(defun isqrt+remainder (x)
  (let ((q (find-a-power-of-4-greater-than-x x))
        (z x)
        (r 0))
    (loop until (= q 1)
          do (progn (setf q (/ q 4))
                    (let ((z1 (- z r q)))
                      (setf r (/ r 2))
                      (when (<= 0 z1)
                        (setf z z1)
                        (setf r (+ r q))))))
    (values r z)))

(defun rosetta_code_isqrt (x)
  (nth-value 0 (isqrt+remainder x)))

(defun main (&rest argv)
  (declare (ignorable argv))
  (format t "isqrt(i) for ~D <= i <= ~D:~2%" 0 65)
  (loop for i from 0 to 64
        do (format t "~D " (isqrt i)))
  (format t "~D~3%" (isqrt 65))
  (format t "isqrt(7**i) for ~D <= i <= ~D, i odd:~2%" 1 73)
  (format t "[email protected] [email protected] [email protected]~%" "i" "7**i" "sqrt(7**i)")
  (format t "~A~%" (make-string 131 :initial-element #\-))
  (loop for i from 1 to 73 by 2
        for 7**i = (expt 7 i)
        for root = (rosetta_code_isqrt 7**i)
        do (format t "~2D ~84:D ~43:D~%" i 7**i root)))

;;; vim: set ft=lisp lisp:


include "cowgol.coh";

# Integer square root
sub isqrt(x: uint32): (x0: uint32) is
    x0 := x >> 1;
    if x0 == 0 then
        x0 := x;
        return;
    end if;
    loop
        var x1 := (x0 + x/x0) >> 1;
        if x1 >= x0 then
            break;
        end if;
        x0 := x1;
    end loop;
end sub;

# Power
sub pow(x: uint32, n: uint8): (r: uint32) is
    r := 1;
    while n > 0 loop
        r := r * x;
        n := n - 1;
    end loop;
end sub;

# Print integer square roots of 0..65
var n: uint32 := 0;
var col: uint8 := 11;
while n <= 65 loop
    print_i32(isqrt(n));
    col := col - 1;
    if col == 0 then
        print_nl();
        col := 11;
    else
        print_char(' ');
    end if;
    n := n + 1;
end loop;

# Cowgol only supports 32-bit integers out of the box, so only powers of 7
# up to 7^11 are printed
var x: uint8 := 0;
while x <= 11 loop
    print("isqrt(7^");
    print_i8(x);
    print(") = ");
    print_i32(isqrt(pow(7, x)));
    print_nl();
    x := x + 1;
end loop;


import std.bigint;
import std.conv;
import std.exception;
import std.range;
import std.regex;
import std.stdio;

//Taken from the task http://rosettacode.org/wiki/Commatizing_numbers#D
auto commatize(in char[] txt, in uint start=0, in uint step=3, in string ins=",") @safe
in {
    assert(step > 0);
} body {
    if (start > txt.length || step > txt.length)    {
        return txt;
    }

    // First number may begin with digit or decimal point. Exponents ignored.
    enum decFloField = ctRegex!("[0-9]*\\.[0-9]+|[0-9]+");

    auto matchDec = matchFirst(txt[start .. $], decFloField);
    if (!matchDec) {
        return txt;
    }

    // Within a decimal float field:
    // A decimal integer field to commatize is positive and not after a point.
    enum decIntField = ctRegex!("(?<=\\.)|[1-9][0-9]*");
    // A decimal fractional field is preceded by a point, and is only digits.
    enum decFracField = ctRegex!("(?<=\\.)[0-9]+");

    return txt[0 .. start] ~ matchDec.pre ~ matchDec.hit
        .replace!(m => m.hit.retro.chunks(step).join(ins).retro)(decIntField)
        .replace!(m => m.hit.chunks(step).join(ins))(decFracField)
        ~ matchDec.post;
}

auto commatize(BigInt v) {
    return commatize(v.to!string);
}

BigInt sqrt(BigInt x) {
    enforce(x >= 0);

    auto q = BigInt(1);
    while (q <= x) {
        q <<= 2;
    }
    auto z = x;
    auto r = BigInt(0);
    while (q > 1) {
        q >>= 2;
        auto t = z;
        t -= r;
        t -= q;
        r >>= 1;
        if (t >= 0) {
            z = t;
            r += q;
        }
    }
    return r;
}

void main() {
    writeln("The integer square root of integers from 0 to 65 are:");
    foreach (i; 0..66) {
        write(sqrt(BigInt(i)), ' ');
    }
    writeln;

    writeln("The integer square roots of powers of 7 from 7^1 up to 7^73 are:");
    writeln("power                                    7 ^ power                                                 integer square root");
    writeln("----- --------------------------------------------------------------------------------- -----------------------------------------");
    auto pow7 = BigInt(7);
    immutable bi49 = BigInt(49);
    for (int i = 1; i <= 73; i += 2) {
        writefln("%2d %84s %41s", i, pow7.commatize, sqrt(pow7).commatize);
        pow7 *= bi49;
    }
}


/* Integer square root using quadratic residue method */
proc nonrec isqrt(ulong x) ulong:
    ulong q, z, r;
    long t;

    q := 1;
    while q <= x do q := q << 2 od;

    z := x;
    r := 0;
    while q > 1 do
        q := q >> 2;
        t := z - r - q;
        r := r >> 1;
        if t >= 0 then
            z := t;
            r := r + q
        fi
    od;

    r
corp

proc nonrec main() void:
    byte x;
    ulong pow7;

    /* print isqrt(0) ... isqrt(65) */
    for x from 0 upto 65 do
        write(isqrt(x):2);
        if x % 11 = 10 then writeln() fi
    od;

    /* print isqrt(7^0) thru isqrt(7^10) */
    pow7 := 1;
    for x from 0 upto 10 do
        writeln("isqrt(7^", x:2, ") = ", isqrt(pow7):5);
        pow7 := pow7 * 7
    od
corp


// Find Integer Floor sqrt of a Large Integer. Nigel Galloway: July 17th., 2020
let Isqrt n=let rec fN i g l=match(l>0I,i-g-l) with
                              (true,e) when e>=0I->fN e (g/2I+l) (l/4I)
                             |(true,_)           ->fN i (g/2I)   (l/4I)
                             |_                  ->g
            fN n 0I (let rec fG g=if g>n then g/4I else fG (g*4I) in fG 1I)
[0I..65I]|>Seq.iter(Isqrt>>string>>printf "%s "); printfn "\n"
let fN n=7I**n in [1..2..73]|>Seq.iter(fN>>Isqrt>>printfn "%a" (fun n g -> n.Write("{0:#,#}", g)))


USING: formatting io kernel locals math math.functions
math.ranges prettyprint sequences tools.memory.private ;

:: isqrt ( x -- n )
    1 :> q!
    [ q x > ] [ q 4 * q! ] until
    x 0 :> ( z! r! )
    [ q 1 > ] [
        q 4 /i q!
        z r - q - :> t
        r -1 shift r!
        t 0 >= [
            t z!
            r q + r!
        ] when
    ] while
    r ;

"Integer square root for numbers 0 to 65 (inclusive):" print
66 <iota> [ bl ] [ isqrt pprint ] interleave nl nl

: align ( str str str -- ) "%2s%85s%44s\n" printf ;
: show ( n -- ) dup 7 swap ^ dup isqrt [ commas ] [email protected] align ;

"x" "7^x" "isqrt(7^x)" align
"-" "---" "----------" align
1 73 2 <range> [ show ] each


: d., ( n -- ) \ write double precision int, commatized.
    tuck dabs
    <# begin  2dup 1.000 d>  while  # # # [char] , hold  repeat #s rot sign #>
    type space ;

: .,  ( n -- ) \ write integer commatized.
    s>d d., ;

: 4*  s" 2 lshift" evaluate ; immediate
: 4/  s" 2 rshift" evaluate ; immediate

: isqrt-mod ( n -- z r )  \ n = r^2 + z
    1 begin 2dup >= while 4* repeat
    0 locals| r q z |
    begin q 1 > while
        q 4/ to q
        z r - q - \ t
        r 2/ to r
        dup 0>= if
            to z
            r q + to r
        else
            drop
        then
    repeat z r ;

: isqrt  isqrt-mod nip ;

: task1
    ." Integer square roots from 0 to 65:" cr
    66 0 do  i isqrt .  loop cr ;

: task2
    ." Integer square roots of 7^n" cr
    7 11 0 do
        i 2* 1+ 2 .r 3 spaces
        dup isqrt ., cr
        49 *
    loop ;

task1 cr task2 bye


MODULE INTEGER_SQUARE_ROOT
    IMPLICIT NONE

    CONTAINS

    ! Convert string representation number to string with comma digit separation
    FUNCTION COMMATIZE(NUM) RESULT(OUT_STR)
         INTEGER(16), INTENT(IN) :: NUM
         INTEGER(16) I
         CHARACTER(83) :: TEMP, OUT_STR

         WRITE(TEMP, '(I0)') NUM

         OUT_STR = ""

         DO I=0, LEN_TRIM(TEMP)-1
             IF (MOD(I, 3) .EQ. 0 .AND. I .GT. 0 .AND. I .LT. LEN_TRIM(TEMP)) THEN
                  OUT_STR = "," // TRIM(OUT_STR)
             END IF
             OUT_STR = TEMP(LEN_TRIM(TEMP)-I:LEN_TRIM(TEMP)-I) // TRIM(OUT_STR)
         END DO
    END FUNCTION COMMATIZE

    ! Calculate the integer square root for a given integer
    FUNCTION ISQRT(NUM)
        INTEGER(16), INTENT(IN) :: NUM
        INTEGER(16) :: ISQRT
        INTEGER(16) :: Q, Z, R, T

        Q = 1
        Z = NUM
        R = 0
        T = 0

        DO WHILE (Q .LT. NUM)
            Q = Q * 4
        END DO

        DO WHILE (Q .GT. 1)
            Q = Q / 4
            T = Z - R - Q
            R = R / 2

            IF (T .GE. 0) THEN
                Z = T
                R = R + Q
            END IF
        END DO

        ISQRT = R
    END FUNCTION ISQRT

END MODULE INTEGER_SQUARE_ROOT

! Demonstration of integer square root for numbers 0-65 followed by odd powers of 7
! from 1-73. Currently this demo takes significant time for numbers above 43
PROGRAM ISQRT_DEMO
    USE INTEGER_SQUARE_ROOT
    IMPLICIT NONE

    INTEGER(16), PARAMETER :: MIN_NUM_HZ = 0
    INTEGER(16), PARAMETER :: MAX_NUM_HZ = 65
    INTEGER(16), PARAMETER :: POWER_BASE = 7
    INTEGER(16), PARAMETER :: POWER_MIN = 1
    INTEGER(16), PARAMETER :: POWER_MAX = 73
    INTEGER(16), DIMENSION(MAX_NUM_HZ-MIN_NUM_HZ+1) :: VALUES
    CHARACTER(2) :: HEADER_1
    CHARACTER(83) :: HEADER_2
    CHARACTER(83) :: HEADER_3

    INTEGER(16) :: I

    HEADER_1 = " n"
    HEADER_2 = "7^n"
    HEADER_3 = "isqrt(7^n)"

    WRITE(*,'(A, I0, A, I0)') "Integer square root for numbers ", MIN_NUM_HZ, " to ", MAX_NUM_HZ

    DO I=1, SIZE(VALUES)
        VALUES(I) = ISQRT(MIN_NUM_HZ+I)
    END DO

    WRITE(*,'(100I2)') VALUES
    WRITE(*,*) NEW_LINE('A')

    WRITE(*,'(A,A,A,A,A)') HEADER_1, " | ", HEADER_2, " | ", HEADER_3
    WRITE(*,*) REPEAT("-", 8+83*2)

    DO I=POWER_MIN,POWER_MAX, 2
        WRITE(*,'(I2, A, A, A, A)') I, " | " // COMMATIZE(7**I), " | ", COMMATIZE(ISQRT(7**I))
    END DO

 END PROGRAM ISQRT_DEMO


function isqrt( byval x as ulongint ) as ulongint
    dim as ulongint q = 1, r
    dim as longint t
    while q <= x
        q = q shl 2
    wend
    while q > 1
        q = q shr 2
        t = x - r - q
        r = r shr 1
        if t >= 0  then
            x  = t
            r += q
        end if
    wend
    return r
end function

function commatize( byval N as string ) as string
    dim as string bloat = ""
    dim as uinteger c = 0
    while N<>""
        bloat = right(N,1) + bloat
        N = left(N, len(N)-1)
        c += 1
        if c mod 3 = 0 and N<>"" then bloat = "," + bloat
    wend
    return bloat
end function

for i as ulongint = 0 to 65
    print isqrt(i);" ";
next i
print

dim as string ns
for i as uinteger = 1 to 22 step 2
    ns = str(isqrt(7^i))
    print i, commatize(ns)
next i


package main

import (
    "fmt"
    "log"
    "math/big"
)

var zero = big.NewInt(0)
var one = big.NewInt(1)

func isqrt(x *big.Int) *big.Int {
    if x.Cmp(zero) < 0 {
        log.Fatal("Argument cannot be negative.")
    }
    q := big.NewInt(1)
    for q.Cmp(x) <= 0 {
        q.Lsh(q, 2)
    }
    z := new(big.Int).Set(x)
    r := big.NewInt(0)
    for q.Cmp(one) > 0 {
        q.Rsh(q, 2)
        t := new(big.Int)
        t.Add(t, z)
        t.Sub(t, r)
        t.Sub(t, q)
        r.Rsh(r, 1)
        if t.Cmp(zero) >= 0 {
            z.Set(t)
            r.Add(r, q)
        }
    }
    return r
}

func commatize(s string) string {
    le := len(s)
    for i := le - 3; i >= 1; i -= 3 {
        s = s[0:i] + "," + s[i:]
    }
    return s
}

func main() {
    fmt.Println("The integer square roots of integers from 0 to 65 are:")
    for i := int64(0); i <= 65; i++ {
        fmt.Printf("%d ", isqrt(big.NewInt(i)))
    }
    fmt.Println()
    fmt.Println("\nThe integer square roots of powers of 7 from 7^1 up to 7^73 are:\n")
    fmt.Println("power                                    7 ^ power                                                 integer square root")
    fmt.Println("----- --------------------------------------------------------------------------------- -----------------------------------------")
    pow7 := big.NewInt(7)
    bi49 := big.NewInt(49)
    for i := 1; i <= 73; i += 2 {
        fmt.Printf("%2d %84s %41s\n", i, commatize(pow7.String()), commatize(isqrt(pow7).String()))
        pow7.Mul(pow7, bi49)
    }
}


import Data.Bits

isqrt :: Integer -> Integer
isqrt n = go n 0 (q `shiftR` 2)
 where
   q = head $ dropWhile (< n) $ iterate (`shiftL` 2) 1
   go z r 0 = r
   go z r q = let t = z - r - q
              in if t >= 0
                 then go t (r `shiftR` 1 + q) (q `shiftR` 2)
                 else go z (r `shiftR` 1) (q `shiftR` 2)

main = do
  print $ isqrt <$> [1..65]
  mapM_ print $ zip [1,3..73] (isqrt <$> iterate (49 *) 7)


link numbers                    # For the "commas" procedure.
link printf

procedure main ()
  write ("isqrt(i) for 0 <= i <= 65:")
  write ()
  roots_of_0_to_65()
  write ()
  write ()
  write ("isqrt(7**i) for 1 <= i <= 73, i odd:")
  write ()
  printf ("%2s %84s %43s\n", "i", "7**i", "sqrt(7**i)")
  write (repl("-", 131))
  roots_of_odd_powers_of_7()
end

procedure roots_of_0_to_65 ()
  local i

  every i := 0 to 64 do writes (isqrt(i), " ")
  write (isqrt(65))
end

procedure roots_of_odd_powers_of_7 ()
  local i, power_of_7, root

  every i := 1 to 73 by 2 do {
    power_of_7 := 7^i
    root := isqrt(power_of_7)
    printf ("%2d %84s %43s\n", i, commas(power_of_7), commas(root))
  }
end

procedure isqrt (x)
  local q, z, r, t

  q := find_a_power_of_4_greater_than_x (x)
  z := x
  r := 0
  while 1 < q do {
    q := ishift(q, -2)
    t := z - r - q
    r := ishift(r, -1)
    if 0 <= t then {
      z := t
      r +:= q
    }
  }
  return r
end

procedure find_a_power_of_4_greater_than_x (x)
  local q

  q := 1
  while q <= x do q := ishift(q, 2)
  return q
end


isqrt_float=: <[email protected]:%:
isqrt_newton=: 9&$: :(x:@:<[email protected]:-:@:(] + x:@:<[email protected]:%)^:_&>~&:x:)

align=: (|.~ i.&' ')"1
comma=: (' ' -.~ [: }: [: , [: (|.) _3 (',' ,~ |.)\ |.)@":&>
While=: {{ u^:(0[email protected]:-:v)^:_ }}

isqrt=: 3 :0&>
 y =. x: y
 NB. q is a power of 4 that's greater than y.  Append 0 0 under binary representation
 q =. y (,&0 0x&.:#:@:])While>: 1x
 z =. y               NB. set  z  to the value of y.
 r =. 0x              NB. initialize  r  to zero.
 while. 1 < q do.     NB. perform while  q > unity.
  q =. _2&}.&.:#: q   NB. integer divide by 4 (-2 drop under binary representation)
  t =. (z - r) - q    NB. compute value of  t.
  r =. }:&.:#: r      NB. integer divide by  two. (curtail under binary representation)
  if. 0 <: t do.
   z =. t             NB. set  z  to value of t
   r =. r + q         NB. compute new value of r
  end.
 end.
 NB. r  is now the  isqrt(y). (most recent value computed)
 NB. Sidenote: Also, Z is now the remainder after square root
 NB. ie. r^2 + z = y, so if z = 0 then x is a perfect square
 NB. r , z
)


import java.math.BigInteger;

public class Isqrt {
    private static BigInteger isqrt(BigInteger x) {
        if (x.compareTo(BigInteger.ZERO) < 0) {
            throw new IllegalArgumentException("Argument cannot be negative");
        }
        var q = BigInteger.ONE;
        while (q.compareTo(x) <= 0) {
            q = q.shiftLeft(2);
        }
        var z = x;
        var r = BigInteger.ZERO;
        while (q.compareTo(BigInteger.ONE) > 0) {
            q = q.shiftRight(2);
            var t = z;
            t = t.subtract(r);
            t = t.subtract(q);
            r = r.shiftRight(1);
            if (t.compareTo(BigInteger.ZERO) >= 0) {
                z = t;
                r = r.add(q);
            }
        }
        return r;
    }

    public static void main(String[] args) {
        System.out.println("The integer square root of integers from 0 to 65 are:");
        for (int i = 0; i <= 65; i++) {
            System.out.printf("%s ", isqrt(BigInteger.valueOf(i)));
        }
        System.out.println();

        System.out.println("The integer square roots of powers of 7 from 7^1 up to 7^73 are:");
        System.out.println("power                                    7 ^ power                                                 integer square root");
        System.out.println("----- --------------------------------------------------------------------------------- -----------------------------------------");
        var pow7 = BigInteger.valueOf(7);
        var bi49 = BigInteger.valueOf(49);
        for (int i = 1; i < 74; i += 2) {
            System.out.printf("%2d %,84d %,41d\n", i, pow7, isqrt(pow7));
            pow7 = pow7.multiply(bi49);
        }
    }
}


# For gojq
def idivide($j):
  . as $i
  | ($i % $j) as $mod
  | ($i - $mod) / $j ;

# input should be non-negative
def isqrt:
  . as $x
  | 1 | until(. > $x; . * 4) as $q
  | {$q, $x, r: 0}
  | until( .q <= 1;
           .q |= idivide(4)
           | .t = .x - .r - .q
           | .r |= idivide(2)
           | if .t >= 0
             then .x = .t
	     | .r += .q
             else . end).r ;

def power($n):
  . as $in
  | reduce range(0;$n) as $i (1; . * $in);

def lpad($len): tostring | ($len - length) as $l | (" " * $l)[:$l] + .;

## The task:

"The integer square roots of integers from 0 to 65 are:",
[range(0;66) | isqrt],
"",
"The integer square roots of odd powers of 7 from 7^1 up to 7^73 are:",
("power" + " "*16 + "7 ^ power" + " "*70 + "integer square root"),

(range( 1;74;2) as $i
  | (7 | power($i)) as $p
  | "\($i|lpad(2)) \($p|lpad(84)) \($p | isqrt | lpad(43))" )


using Formatting

function integer_sqrt(x)
    @assert(x >= 0)
    q = one(x)
    while q <= x
        q <<= 2
    end
    z, r = x, zero(x)
    while q > 1
        q >>= 2
        t = z - r - q
        r >>= 1
        if t >= 0
            z = t
            r += q
        end
    end
    return r
end

println("The integer square roots of integers from 0 to 65 are:")
println(integer_sqrt.(collect(0:65)))

println("\nThe integer square roots of odd powers of 7 from 7^1 up to 7^73 are:\n")
println("power", " "^36, "7 ^ power", " "^60, "integer square root")
println("----- ", "-"^80, " ------------------------------------------")
pow7 = big"7"
for i in 1:2:73
    println(lpad(i, 2), lpad(format(pow7^i, commas=true), 84),
        lpad(format(integer_sqrt(pow7^i), commas=true), 43))
end


import java.math.BigInteger

fun isqrt(x: BigInteger): BigInteger {
    if (x < BigInteger.ZERO) {
        throw IllegalArgumentException("Argument cannot be negative")
    }
    var q = BigInteger.ONE
    while (q <= x) {
        q = q.shiftLeft(2)
    }
    var z = x
    var r = BigInteger.ZERO
    while (q > BigInteger.ONE) {
        q = q.shiftRight(2)
        var t = z
        t -= r
        t -= q
        r = r.shiftRight(1)
        if (t >= BigInteger.ZERO) {
            z = t
            r += q
        }
    }
    return r
}

fun main() {
    println("The integer square root of integers from 0 to 65 are:")
    for (i in 0..65) {
        print("${isqrt(BigInteger.valueOf(i.toLong()))} ")
    }
    println()

    println("The integer square roots of powers of 7 from 7^1 up to 7^73 are:")
    println("power                                    7 ^ power                                                 integer square root")
    println("----- --------------------------------------------------------------------------------- -----------------------------------------")
    var pow7 = BigInteger.valueOf(7)
    val bi49 = BigInteger.valueOf(49)
    for (i in (1..73).step(2)) {
        println("%2d %,84d %,41d".format(i, pow7, isqrt(pow7)))
        pow7 *= bi49
    }
}


function isqrt(x)
    local q = 1
    local r = 0
    while q <= x do
        q = q << 2
    end
    while q > 1 do
        q = q >> 2
        local t = x - r - q
        r = r >> 1
        if t >= 0 then
            x = t
            r = r + q
        end
    end
    return r
end

print("Integer square root for numbers 0 to 65:")
for n=0,65 do
    io.write(isqrt(n) .. ' ')
end
print()
print()

print("Integer square roots of oddd powers of 7 from 1 to 21:")
print(" n |              7 ^ n | isqrt(7 ^ n)")
local p = 7
local n = 1
while n <= 21 do
    print(string.format("%2d | %18d | %12d", n, p, isqrt(p)))
    ----------------------
    n = n + 2
    p = p * 49
end


            NORMAL MODE IS INTEGER

          R  INTEGER SQUARE ROOT OF X

            INTERNAL FUNCTION(X)
            ENTRY TO ISQRT.
            Q = 1
FNDPW4      WHENEVER Q.LE.X
                Q = Q * 4
                TRANSFER TO FNDPW4
            END OF CONDITIONAL
            Z = X
            R = 0
FNDRT       WHENEVER Q.G.1
                Q = Q / 4
                T = Z - R - Q
                R = R / 2
                WHENEVER T.GE.0
                    Z = T
                    R = R + Q
                END OF CONDITIONAL
                TRANSFER TO FNDRT
            END OF CONDITIONAL
            FUNCTION RETURN R
            END OF FUNCTION

          R  PRINT INTEGER SQUARE ROOTS OF 0..65

            THROUGH SQ65, FOR N=0, 11, N.G.65
SQ65        PRINT FORMAT N11, ISQRT.(N), ISQRT.(N+1), ISQRT.(N+2),
          0    ISQRT.(N+3), ISQRT.(N+4), ISQRT.(N+5), ISQRT.(N+6),
          1    ISQRT.(N+7), ISQRT.(N+8), ISQRT.(N+9), ISQRT.(N+10)
            VECTOR VALUES N11 = $11(I1,S1)*$

          R  MACHINE WORD SIZE ON IBM 704 IS 36 BITS
          R  PRINT UP TO AND INCLUDING ISQRT(7^12)

            POW7 = 1
            THROUGH SQ7P12, FOR I=0, 1, I.G.12
            PRINT FORMAT SQ7, I, ISQRT.(POW7)
SQ7P12      POW7 = POW7 * 7
            VECTOR VALUES SQ7 = $9HISQRT.(7^,I2,4H) = ,I6*$

            END OF PROGRAM


ClearAll[ISqrt]
ISqrt[x_Integer?NonNegative] := Module[{q = 1, z, r, t},
  While[q <= x,
   q *= 4
   ];
  z = x;
  r = 0;
  While[q > 1,
   q = Quotient[q, 4];
   t = z - r - q;
   r /= 2;
   If[t >= 0,
    z = t;
    r += q
    ];
   ];
  r
  ]
ISqrt /@ Range[65]
Column[ISqrt /@ (7^Range[1, 73])]


/* -*- Maxima -*- */

/*

The Rosetta Code integer square root task, in Maxima.

I have not tried to make the output conform quite to the task
description, because Maxima is not a general purpose programming
language. Perhaps someone else will care to do it.

I *do* check that the Rosetta Code routine gives the same results as
the built-in function.

*/

/* pow4gtx -- find a power of 4 greater than x. */
pow4gtx (x) := block (
  [q],
  q : 1, while q <= x do q : bit_lsh (q, 2),
  q
  ) $

/* rosetta_code_isqrt -- find the integer square root. */
rosetta_code_isqrt (x) := block (
  [q, z, r, t],
  q : pow4gtx (x),
  z : x,
  r : 0,
  while 1 < q do (
    q : bit_rsh (q, 2),
    t : z - r - q,
    r : bit_rsh (r, 1),
    if 0 <= t then (
      z : t,
      r : r + q
      )
    ),
  r
  ) $

for i : 0 thru 65 do (
  display (rosetta_code_isqrt (i),
    is (equal (rosetta_code_isqrt (i), isqrt (i))))
  ) $
for i : 1 thru 73 step 2 do (
  display (7**i, rosetta_code_isqrt (7**i),
    is (equal (rosetta_code_isqrt (7**i), isqrt (7**i))))
  ) $


:- module isqrt_in_mercury.

:- interface.
:- import_module io.
:- pred main(io, io).
:- mode main(di, uo) is det.

:- implementation.
:- import_module char.
:- import_module exception.
:- import_module int.
:- import_module integer.       % Integers of arbitrary size.
:- import_module list.
:- import_module string.

:- func four = integer.
four = integer(4).

:- func seven = integer.
seven = integer(7).

%% Find a power of 4 greater than X.
:- func pow4gtx(integer) = integer.
pow4gtx(X) = Q :- pow4gtx_(X, one, Q).

%% The tail recursion for pow4gtx.
:- pred pow4gtx_(integer, integer, integer).
:- mode pow4gtx_(in, in, out) is det.
pow4gtx_(X, A, Q) :- if (X < A) then (Q = A)
                     else (A1 = A * four,
                           pow4gtx_(X, A1, Q)).

%% Integer square root function.
:- func isqrt(integer) = integer.
isqrt(X) = Root :- isqrt(X, Root, _).

%% Integer square root and remainder.
:- pred isqrt(integer, integer, integer).
:- mode isqrt(in, out, out) is det.
isqrt(X, Root, Remainder) :-
  Q = pow4gtx(X),
  isqrt_(X, Q, zero, X, Root, Remainder).

%% The tail recursion for isqrt.
:- pred isqrt_(integer, integer, integer, integer, integer, integer).
:- mode isqrt_(in, in, in, in, out, out) is det.
isqrt_(X, Q, R0, Z0, R, Z) :-
  if (X < zero) then throw("isqrt of a negative integer")
  else if (Q = one) then (R = R0, Z = Z0)
  else (Q1 = Q // four,
        T = Z0 - R0 - Q1,
        (if (T >= zero)
         then (R1 = (R0 // two) + Q1,
               isqrt_(X, Q1, R1, T, R, Z))
         else (R1 is R0 // two,
               isqrt_(X, Q1, R1, Z0, R, Z)))).

%% Insert a character, every three digits, into (what presumably is)
%% an integer numeral. (The name "commas" is not very good.)
:- func commas(string, char) = string.
commas(S, Comma) = T :-
  RCL = to_rev_char_list(S),
  commas_(RCL, Comma, 0, [], CL),
  T = from_char_list(CL).

%% The tail recursion for commas.
:- pred commas_(list(char), char, int, list(char), list(char)).
:- mode commas_(in, in, in, in, out) is det.
commas_([], _, _, L, CL) :- L = CL.
commas_([C | Tail], Comma, I, L, CL) :-
  if (I = 3) then commas_([C | Tail], Comma, 0, [Comma | L], CL)
  else (I1 = I + 1,
        commas_(Tail, Comma, I1, [C | L], CL)).

:- pred roots_m_to_n(integer, integer, io, io).
:- mode roots_m_to_n(in, in, di, uo) is det.
roots_m_to_n(M, N, !IO) :-
  if (N < M) then true
  else (write_string(to_string(isqrt(M)), !IO),
        (if (M \= N) then write_string(" ", !IO)
         else true),
        M1 = M + one,
        roots_m_to_n(M1, N, !IO)).

:- pred roots_of_odd_powers_of_7(integer, integer, io, io).
:- mode roots_of_odd_powers_of_7(in, in, di, uo) is det.
roots_of_odd_powers_of_7(M, N, !IO) :-
  if (N < M) then true
  else (Pow7 = pow(seven, M),
        Isqrt = isqrt(Pow7),
        format("%2s %84s %43s",
               [s(commas(to_string(M), (','))),
                s(commas(to_string(Pow7), (','))),
                s(commas(to_string(Isqrt), (',')))],
               !IO),
        nl(!IO),
        M1 = M + two,
        roots_of_odd_powers_of_7(M1, N, !IO)).

main(!IO) :-
  write_string("isqrt(i) for 0 <= i <= 65:", !IO),
  nl(!IO), nl(!IO),
  roots_m_to_n(zero, integer(65), !IO),
  nl(!IO), nl(!IO), nl(!IO),
  write_string("isqrt(7**i) for 1 <= i <= 73, i odd:", !IO),
  nl(!IO), nl(!IO),
  format("%2s %84s %43s", [s("i"), s("7**i"), s("isqrt(7**i)")], !IO),
  nl(!IO),
  write_string(duplicate_char(('-'), 131), !IO),
  nl(!IO),
  roots_of_odd_powers_of_7(one, integer(73), !IO).

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% Instructions for GNU Emacs--
%%% local variables:
%%% mode: mercury
%%% prolog-indent-width: 2
%%% end:
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%


MODULE IntSqrt;

IMPORT IO;

(* Procedure to find integer square root of a 32-bit unsigned integer. *)
PROCEDURE Isqrt( X : LONGCARD) : LONGCARD;
VAR
  Xdiv4, q, r, s, z : LONGCARD;
BEGIN
  Xdiv4 := X DIV 4;
  q := 1;
  WHILE q <= Xdiv4 DO q := 4*q; END;
  z := X;
  r := 0;
  REPEAT
    s := q + r;
    r := r DIV 2;
    IF z >= s THEN
      DEC(z, s);
      INC(r, q);
    END;
    q := q DIV 4;
  UNTIL q = 0;
  RETURN r;
END Isqrt;

(* Main program *)
CONST (* constants for Part 1 of the task *)
  Max_n = 65;
  NrPerLine = 22;
VAR
  n : LONGCARD;
  arr_n, arr_i : ARRAY[0..NrPerLine - 1] OF LONGCARD; (* for display *)
  j, k : INTEGER;
BEGIN
(* Part 1 *)
  k := 0; (* index into arrays *)
  FOR n := 0 TO Max_n DO
    arr_n[k] := n;
    arr_i[k] := Isqrt(n);
    INC(k);
    IF (k = NrPerLine) OR (n = Max_n) THEN
      IO.WrStr( 'Number: ');
      FOR j := 0 TO k - 1 DO IO.WrLngCard(arr_n[j], 3); END;
      IO.WrLn();
      IO.WrStr( 'Isqrt:  ');
      FOR j := 0 TO k - 1 DO IO.WrLngCard(arr_i[j], 3); END;
      IO.WrLn();
      k := 0;
    END;
  END;
  IO.WrLn();

(* Part 2 *)
  IO.WrStr( 'Isqrt of odd powers of 7'); IO.WrLn();
  n := 7;
  FOR k := 1 TO 11 BY 2 DO
    IF k > 1 THEN n := n*49; END;
    IO.WrInt( k, 2); IO.WrStr( ' --> ');
    IO.WrLngCard( n, 10); IO.WrStr(' --> ');
    IO.WrLngCard( Isqrt(n), 5); IO.WrLn();
  END;
END IntSqrt.


import strformat, strutils
import bignum

func isqrt*[T: SomeSignedInt | Int](x: T): T =
  ## Compute integer square root for signed integers
  ## and for big integers.

  when T is Int:
    result = newInt()
    var q = newInt(1)
  else:
    result = 0
    var q = T(1)

  while q <= x:
    q = q shl 2

  var z = x
  while q > 1:
    q = q shr 2
    let t = z - result - q
    result = result shr 1
    if t >= 0:
      z = t
      result += q

when isMainModule:

  echo "Integer square root for numbers 0 to 65:"
  for n in 0..65:
    stdout.write ' ', isqrt(n)
  echo "\n"

  echo "Integer square roots of odd powers of 7 from 7^1 to 7^73:"
  echo " n" & repeat(' ', 82) & "7^n" & repeat(' ', 34) & "isqrt(7^n)"
  echo repeat("—", 131)

  var x = newInt(7)
  for n in countup(1, 73, 2):
    echo &"{n:>2}   {insertSep($x, ','):>82}   {insertSep($isqrt(x), ','):>41}"
    x *= 49


# -*- ObjectIcon -*-

import io
import ipl.numbers              # For the "commas" procedure.
import ipl.printf

procedure main ()
  write ("isqrt(i) for 0 <= i <= 65:")
  write ()
  roots_of_0_to_65()
  write ()
  write ()
  write ("isqrt(7**i) for 1 <= i <= 73, i odd:")
  write ()
  printf ("%2s %84s %43s\n", "i", "7**i", "sqrt(7**i)")
  write (repl("-", 131))
  roots_of_odd_powers_of_7()
end

procedure roots_of_0_to_65 ()
  local i

  every i := 0 to 64 do writes (isqrt(i), " ")
  write (isqrt(65))
end

procedure roots_of_odd_powers_of_7 ()
  local i, power_of_7, root

  every i := 1 to 73 by 2 do {
    power_of_7 := 7^i
    root := isqrt(power_of_7)
    printf ("%2d %84s %43s\n", i, commas(power_of_7), commas(root))
  }
end

procedure isqrt (x)
  local q, z, r, t

  q := find_a_power_of_4_greater_than_x (x)
  z := x
  r := 0
  while 1 < q do {
    q := ishift(q, -2)
    t := z - r - q
    r := ishift(r, -1)
    if 0 <= t then {
      z := t
      r +:= q
    }
  }
  return r
end

procedure find_a_power_of_4_greater_than_x (x)
  local q

  q := 1
  while q <= x do q := ishift(q, 2)
  return q
end