COMMENT text between pairs of words 'comment' in capitals are
        for the human reader's information and are ignored by the machine
COMMENT

COMMENT Define s to be the integer value 269 696              COMMENT
INT s = 269 696;

COMMENT Name a location in the machine's storage area that will be
        used to hold integer values.
        The value stored in the location will change during the
        calculations.
        Note, "*" is used to represent the multiplication operator.
              ":=" causes the location named to the left of ":=" to
                   assume the value computed by the expression to the right.
              "sqrt" computes an approximation to the square root
                     of the supplied parameter
              "MOD" is an operator that computes the modulus of its
                    left operand with respect to its right operand
              "ENTIER" is a unary operator that yields the largest
                      integer that is at most its operand.
COMMENT
INT v := ENTIER sqrt( s );

COMMENT the construct: WHILE...DO...OD repeatedly executes the
        instructions between DO and OD, the execution stops when
        the instructions between WHILE and DO yield the value FALSE.
COMMENT
WHILE ( v * v ) MOD 1 000 000 /= s DO v := v + 1 OD;

COMMENT print displays the values of its parameters
COMMENT
print( ( v, " when squared is: ", v * v, newline ) )


      ⍝ We know that 99,736 is a valid answer, so we only need to test the positive integers from 1 up to there:
      N←⍳99736
      ⍝ The SQUARE OF omega is omega times omega:
      SQUAREOF←{⍵×⍵}
      ⍝ To say that alpha ENDS IN the six-digit number omega means that alpha divided by 1,000,000 leaves remainder omega:
      ENDSIN←{(1000000|⍺)=⍵}
      ⍝ The SMALLEST number WHERE some condition is met is found by taking the first number from a list of attempts, after rearranging the list so that numbers satisfying the condition come before those that fail to satisfy it:
      SMALLESTWHERE←{1↑⍒⍵}
      ⍝ We can now ask the computer for the answer:
      SMALLESTWHERE (SQUAREOF N) ENDSIN 269696


-- BABBAGE -------------------------------------------------------------------

-- babbage :: Int -> [Int]
on babbage(intTests)

    script test
        on toSquare(x)
            (x * 1000000) + 269696
        end toSquare

        on |λ|(x)
            hasIntRoot(toSquare(x))
        end |λ|
    end script

    script toRoot
        on |λ|(x)
            ((x * 1000000) + 269696) ^ (1 / 2)
        end |λ|
    end script

    set xs to filter(test, enumFromTo(1, intTests))
    zip(map(toRoot, xs), map(test's toSquare, xs))
end babbage

-- TEST ----------------------------------------------------------------------
on run
    -- Try 1000 candidates

    unlines(map(curry(intercalate)'s |λ|("  ->  "), babbage(1000)))

    --> "2.5264E+4 -> 6.38269696E+8"
end run

-- GENERIC FUNCTIONS ---------------------------------------------------------

-- curry :: (Script|Handler) -> Script
on curry(f)
    script
        on |λ|(a)
            script
                on |λ|(b)
                    |λ|(a, b) of mReturn(f)
                end |λ|
            end script
        end |λ|
    end script
end curry

-- enumFromTo :: Int -> Int -> [Int]
on enumFromTo(m, n)
    if m > n then
        set d to -1
    else
        set d to 1
    end if
    set lst to {}
    repeat with i from m to n by d
        set end of lst to i
    end repeat
    return lst
end enumFromTo

-- filter :: (a -> Bool) -> [a] -> [a]
on filter(f, xs)
    tell mReturn(f)
        set lst to {}
        set lng to length of xs
        repeat with i from 1 to lng
            set v to item i of xs
            if |λ|(v, i, xs) then set end of lst to v
        end repeat
        return lst
    end tell
end filter

-- hasIntRoot :: Int -> Bool
on hasIntRoot(n)
    set r to n ^ 0.5
    r = (r as integer)
end hasIntRoot

-- intercalate :: Text -> [Text] -> Text
on intercalate(strText, lstText)
    set {dlm, my text item delimiters} to {my text item delimiters, strText}
    set strJoined to lstText as text
    set my text item delimiters to dlm
    return strJoined
end intercalate

-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
    tell mReturn(f)
        set lng to length of xs
        set lst to {}
        repeat with i from 1 to lng
            set end of lst to |λ|(item i of xs, i, xs)
        end repeat
        return lst
    end tell
end map

-- min :: Ord a => a -> a -> a
on min(x, y)
    if y < x then
        y
    else
        x
    end if
end min

-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: Handler -> Script
on mReturn(f)
    if class of f is script then
        f
    else
        script
            property |λ| : f
        end script
    end if
end mReturn

-- unlines :: [String] -> String
on unlines(xs)
    intercalate(linefeed, xs)
end unlines

-- zip :: [a] -> [b] -> [(a, b)]
on zip(xs, ys)
    set lng to min(length of xs, length of ys)
    set lst to {}
    repeat with i from 1 to lng
        set end of lst to {item i of xs, item i of ys}
    end repeat
    return lst
end zip


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

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

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

/*********************************/
/* UnInitialized data            */
/*********************************/
.bss
/*********************************/
/*  code section                 */
/*********************************/
.text
.global main
main:                                             @ entry of program

    ldr r4,iNbStart                               @ start number = 269696
    mov r5,#0                                     @ counter multiply
    ldr r2,iNbMult                                @ value multiply = 1 000 000
    mov r6,r4
1:
    mov r0,r6
    bl squareRoot                                 @ compute square root
    umull r1,r3,r0,r0
    cmp r3,#0                                     @ overflow ?
    bne 100f                                      @ yes -> end
    cmp r1,r6                                     @ perfect square
    bne 2f                                        @ no -> loop
    ldr r1,iAdrsMessValeur
    bl conversion10                               @ call conversion decimal
    ldr r0,iAdrsMessResult
    bl affichageMess                              @ display message
    b 100f                                        @ end
2:
    add r5,#1                                     @ increment counter
    mul r3,r5,r2                                  @ multiply by 1 000 000
    add r6,r3,r4                                  @ add start number
    b 1b

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

iAdrsMessValeur:          .int sMessValeur
iAdrszCarriageReturn:     .int szCarriageReturn
iAdrsMessResult:          .int sMessResult
iNbStart:                 .int 269696
iNbMult:                  .int 1000000
/******************************************************************/
/*     compute squareRoot                                       */
/******************************************************************/
/* r0 contains n          */
/* r0 return result or -1 */
squareRoot:
    push {r1-r5,lr}                     @ save  registers
    cmp r0,#0
    beq 100f                            @ if zero -> end
    movlt r0,#-1                        @ if negatif return - 1
    blt 100f
    cmp r0,#4                           @ if <  4 return 1
    movlt r0,#1
    blt 100f
                                        @ start
    clz r2,r0                           @ number of zeros on the left
    rsb r2,#32                          @ so many useful numbers right
    bic r2,#1                           @ to have an even number of digits
    mov r3,#0b11                        @ mask for extract 2 bits
    lsl r3,r2
    mov r1,#0                           @ init résult with 0
    mov r4,#0                           @ raz remainder area

1:                                      @ begin loop
    and r5,r0,r3                        @ extract 2 bits with mask
    add r4,r5,lsr r2                    @ shift right and addition with remainder
    lsl r5,r1,#1                        @ multiplication by 2
    lsl r5,#1                           @ shift left one bit
    orr r5,#1                           @ bit right = 1
    lsl r1,#1                           @ shift left one bit
    subs r4,r5                          @ sub remainder
    addmi r4,r4,r5                      @ if negative restaur register
    addpl r1,#1                         @ else add 1
    subs r2,#2                          @ decrement number bits
    movmi r0,r1                         @ if end return result
    bmi 100f
    lsl r4,#2                           @ no -> shift left remainder 2 bits
    lsr r3,#2                           @ and shift right mask 2 bits
    b 1b                                @ and loop

100:
    pop {r1-r5,lr}                      @ restaur registers
    bx lr                               @return
/******************************************************************/
/*     display text with size calculation                         */
/******************************************************************/
/* r0 contains the address of the message */
affichageMess:
    push {r0,r1,r2,r7,lr}                          @ save  registres
    mov r2,#0                                      @ counter length
1:                                                 @ loop length calculation
    ldrb r1,[r0,r2]                                @ read octet start position + index
    cmp r1,#0                                      @ if 0 its over
    addne r2,r2,#1                                 @ else add 1 in the length
    bne 1b                                         @ and loop
                                                   @ so here r2 contains the length of the message
    mov r1,r0                                      @ address message in r1
    mov r0,#STDOUT                                 @ code to write to the standard output Linux
    mov r7, #WRITE                                 @ code call system "write"
    svc #0                                         @ call systeme
    pop {r0,r1,r2,r7,lr}                           @ restaur des  2 registres */
    bx lr                                          @ return
/******************************************************************/
/*     Converting a register to a decimal unsigned                */
/******************************************************************/
/* r0 contains value and r1 address area   */
/* r0 return size of result (no zero final in area) */
/* area size => 11 bytes          */
.equ LGZONECAL,   10
conversion10:
    push {r1-r4,lr}                                 @ save registers
    mov r3,r1
    mov r2,#LGZONECAL
1:                                                  @ start loop
    bl divisionpar10U                               @ unsigned  r0 <- dividende. quotient ->r0 reste -> r1
    add r1,#48                                      @ digit
    strb r1,[r3,r2]                                 @ store digit on area
    cmp r0,#0                                       @ stop if quotient = 0
    subne r2,#1                                     @ else previous position
    bne 1b                                          @ and loop
                                                    @ and move digit from left of area
    mov r4,#0
2:
    ldrb r1,[r3,r2]
    strb r1,[r3,r4]
    add r2,#1
    add r4,#1
    cmp r2,#LGZONECAL
    ble 2b
                                                      @ and move spaces in end on area
    mov r0,r4                                         @ result length
    mov r1,#' '                                       @ space
3:
    strb r1,[r3,r4]                                   @ store space in area
    add r4,#1                                         @ next position
    cmp r4,#LGZONECAL
    ble 3b                                            @ loop if r4 <= area size

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

/***************************************************/
/*   division par 10   unsigned                    */
/***************************************************/
/* r0 dividende   */
/* r0 quotient    */
/* r1 remainder   */
divisionpar10U:
    push {r2,r3,r4, lr}
    mov r4,r0                                          @ save value
    ldr r3,iMagicNumber                                @ r3 <- magic_number    raspberry 1 2
    umull r1, r2, r3, r0                               @ r1<- Lower32Bits(r1*r0) r2<- Upper32Bits(r1*r0)
    mov r0, r2, LSR #3                                 @ r2 <- r2 >> shift 3
    add r2,r0,r0, lsl #2                               @ r2 <- r0 * 5
    sub r1,r4,r2, lsl #1                               @ r1 <- r4 - (r2 * 2)  = r4 - (r0 * 10)
    pop {r2,r3,r4,lr}
    bx lr                                              @ leave function
iMagicNumber:  	.int 0xCCCCCCCD


; Give n an initial value
n = 519

; Loop this action while condition is not satisfied
while (Mod(n*n, 1000000) != 269696) {
	; Increment n
	n++
}

; Display n as value
msgbox, %n%


# A comment starts with a "#" and are ignored by the machine.  They can be on a
# line by themselves or at the end of an executable line.
#
# A program consists of multiple lines or statements.  This program tests
# positive integers starting at 1 and terminates when one is found whose square
# ends in 269696.
#
# The next line shows how to run the program.
# syntax: GAWK -f BABBAGE_PROBLEM.AWK
#
BEGIN { # start of program
# this declares a variable named "n" and assigns it a value of zero
    n = 0
# do what's inside the "{}" until n times n ends in 269696
    do {
      n = n + 1 # add 1 to n
    } while (n*n !~ /269696$/)
# print the answer
    print("The smallest number whose square ends in 269696 is " n)
    print("Its square is " n*n)
# terminate program
    exit(0)
} # end of program


 100 :
 110  REM  BABBAGE PROBLEM
 120 :
 130  DEF  FN ST(A) = N - INT (A) * INT (A)
 140 N = 269696
 150 N = N + 1000000
 160 R =  SQR (N)
 170  IF FN ST(R) <  > 0 AND N < 999999999 THEN GOTO 150
 180  IF N > 999999999 THEN  GOTO 210
 190  PRINT "SMALLESt NUMBER WHOSE
      SQUARE ENDS IN"; CHR$ (13);
      "269696 IS ";R;", AND THE
      SQUARE IS"; CHR$ (13);N
 200  END
 210  PRINT "THERE IS NO SOLUTION
      FOR VALUES SMALLER"; CHR$(13);
      "THAN 999999999."


:: This line is only required to increase the readability of the output by hiding the lines of code being executed
@echo off

:: Everything between the lines keeps repeating until the answer is found
:: The code works by, starting at 1, checking to see if the last 6 digits of the current number squared is equal to 269696
::----------------------------------------------------------------------------------
:loop
:: Increment the current number being tested by 1
set /a number+=1

:: Square the current number
set /a numbersquared=%number%*%number%

:: Check if the last 6 digits of the current number squared is equal to 269696, and if so, stop looping and go to the end
if %numbersquared:~-6%==269696 goto end

goto loop
::----------------------------------------------------------------------------------

:end
echo %number% * %number% = %numbersquared%
pause>nul


    1+       ::*    "d"::** %       "V8":** -!     #v_ > > > > >
                                                    v
increment n  n*n  modulo 1000000  equal to 269696?  v  if false, loop to right
                                                    v
v"Smallest number whose square ends in 269696 is "0 <  else output n below
>:#,_$           .      55+,     @

ouput message  then n  newline  exit

numeric constants explained:

"d"  ascii value of 'd', i.e. 100
::   duplicate twice: 100,100,100
**   multiply twice: 100*100*100 = 1000000

"V8" ascii values of 'V' and '8', i.e. 86 and 56
:    duplicate the '8' (56): 86,56,56
**   multiply twice:  86*56*56 = 269696


(
  500:?number {A child knows that 269696 is larger than 500*500,
               but not by much. It is safe to start the search with 500.}
&   whl  {'whl' is shorthand for 'while'. It announces the evaluation of
                            an expression that is repeated until it fails.}
  ' ( @(!number*!number:~(? 269696))  { ~(? 269696) is a pattern. It says
                                       that it will not match numbers that do
                                       not end with the figures 269696.
                                       The question mark is there to match all
                                       the figures before 269696.}
    & !number:<99736                  { We should under no circumstance try
                                       numbers that are larger than 99736.}
    & 1+!number:?number               { If the number did not pass the test,
                                        we take the next number and repeat
                                        the test. }
    )
&   out
  $ ( str
    $ ( "The smallest number that ends with the figures 269696 when squared is "
        !number
        ", since the square of "
        !number
        " is "
        !number*!number
      )
    )
)


// This code is the implementation of Babbage Problem

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

int main() {
	int current = 0, 	//the current number
	    square;		//the square of the current number

	//the strategy of take the rest of division by 1e06 is
	//to take the a number how 6 last digits are 269696
	while (((square=current*current) % 1000000 != 269696) && (square<INT_MAX)) {
		current++;
	}

        //output
	if (square>+INT_MAX)
	    printf("Condition not satisfied before INT_MAX reached.");
	else
	    printf ("The smallest number whose square ends in 269696 is %d\n", current);

        //the end
	return 0 ;
}


namespace Babbage_Problem
{
    class iterateNumbers
    {
        public iterateNumbers()
        {
            long baseNumberSquared = 0; //the base number multiplied by itself
            long baseNumber = 0;  //the number to be squared, this one will be iterated

            do  //this sets up the loop
            {
                baseNumber += 1; //add one to the base number
                baseNumberSquared = baseNumber * baseNumber; //multiply the base number by itself and store the value as baseNumberSquared
            }
            while (Right6Digits(baseNumberSquared) != 269696); //this will continue the loop until the right 6 digits of the base number squared are 269,696

            Console.WriteLine("The smallest integer whose square ends in 269,696 is " + baseNumber);
            Console.WriteLine("The square is " + baseNumberSquared);

        }

        private long Right6Digits(long baseNumberSquared)
        {

            string numberAsString = baseNumberSquared.ToString(); //this is converts the number to a different type so it can be cut up

            if (numberAsString.Length < 6) { return baseNumberSquared; }; //if the number doesn't have 6 digits in it, just return it to try again.

            numberAsString = numberAsString.Substring(numberAsString.Length - 6);  //this extracts the last 6 digits from the number

            return long.Parse(numberAsString); //return the last 6 digits of the number

        }
    }
}}


#include <iostream>

int main( ) {
   int current = 0 ;
   while ( ( current * current ) % 1000000 != 269696 )
      current++ ;
   std::cout << "The square of " << current << " is " << (current * current) << " !\n" ;
   return 0 ;
}


BABBAGE
	; start at the integer prior to the square root of 269,696 as it has to be at least that big
	set i = ($piece($zsqr(269696),".",1,1) - 1)    ; piece 1 of . gets the integer portion

	; loop forever, incrementing by one, until we find a square ending in 269696
	for {
		set i = i + 1    ; this will start us at the integer value from the piece statement above

		; evaluate if the last 6 digits of the square equal 269696
		set square = i * i
		if ($extract(square,$length(square) - 5,$length(square)) = 269696) {
			; We match - display the integer and square value to the screen, formatting the numerics with a comma separator as needed.
			write !,"Result: "_$fnumber(i,",")_" squared is "_$fnumber(square,",")_".  This ends in 269696."
			quit    ; exit for loop
		}
	}

	quit    ; exit routine


; Defines function named babbage? that returns true if the
; square of the provided number leaves a remainder of 269,696 when divided
; by a million
(defn babbage? [n]
  (let [square (* n n)]
    (= 269696 (mod square 1000000))))

; Use the above babbage? to find the first positive integer that returns true
; (We're exploiting Clojure's laziness here; (range) with no parameters returns
; an infinite series.)
(first (filter babbage? (range)))


IDENTIFICATION DIVISION.
PROGRAM-ID. BABBAGE-PROGRAM.
* A line beginning with an asterisk is an explanatory note.
* The machine will disregard any such line.
DATA DIVISION.
WORKING-STORAGE SECTION.
* In this part of the program we reserve the storage space we shall
* be using for our variables, using a 'PICTURE' clause to specify
* how many digits the machine is to keep free.
* The prefixed number 77 indicates that these variables do not form part
* of any larger 'record' that we might want to deal with as a whole.
77  N           PICTURE 99999.
* We know that 99,736 is a valid answer.
77  N-SQUARED   PICTURE 9999999999.
77  LAST-SIX    PICTURE 999999.
PROCEDURE DIVISION.
* Here we specify the calculations that the machine is to carry out.
CONTROL-PARAGRAPH.
    PERFORM COMPUTATION-PARAGRAPH VARYING N FROM 1 BY 1
    UNTIL LAST-SIX IS EQUAL TO 269696.
    STOP RUN.
COMPUTATION-PARAGRAPH.
    MULTIPLY N BY N GIVING N-SQUARED.
    MOVE N-SQUARED TO LAST-SIX.
* Since the variable LAST-SIX can hold a maximum of six digits,
* only the final six digits of N-SQUARED will be moved into it:
* the rest will not fit and will simply be discarded.
    IF LAST-SIX IS EQUAL TO 269696 THEN DISPLAY N.


(defun babbage-test (n)
 "A generic function for any ending of a number"
  (when (> n 0)
    (do* ((i 0 (1+ i))
          (d (expt 10 (1+ (truncate (log n) (log 10))))) )
      ((= (mod (* i i) d) n) i) )))


MODULE BabbageProblem;
IMPORT StdLog;

PROCEDURE Do*;
VAR
	i: LONGINT;
BEGIN
	i := 2;
	WHILE (i * i MOD 1000000) # 269696 DO
		IF i MOD 10 = 4 THEN INC(i,2) ELSE INC(i,8) END
	END;
	StdLog.Int(i)
END Do;

END BabbageProblem.


// It's basically the same as any other version.
// What can be observed is that 269696 is even, so we have to consider only even numbers,
// because only the square of even numbers is even.

import std.math;
import std.stdio;

void main( )
{
    // get smallest number <= sqrt(269696)
    int k = cast(int)(sqrt(269696.0));

    // if root is odd -> make it even
    if (k % 2 == 1)
        k = k - 1;

    // cycle through numbers
    while ((k * k) % 1000000 != 269696)
        k = k + 2;

    // display output
    writefln("%d * %d = %d", k, k, k*k);
}


// Helper function for mask: does the actual computation.
function method mask_(v:int,m:int):int
  decreases v-m
  requires 0 <= v && 0 < m
  ensures v < mask_(v,m)
{
  if v < m then m else mask_(v,m*10)
}

// Return the smallest power of 10 greater than v.
function method mask(v:int):int
  requires 0 <= v
  ensures v < mask(v)
{
  mask_(v,10)
}

// Return true if the last digits of v == suffix.
predicate method EndWith(v:int,suffix:int)
  requires 0 <= suffix
{
  v % mask(suffix) == suffix
}

method SmallestSqEndingWith(suffix:int) returns (s:int)
  requires 0 < suffix
  ensures EndWith(s*s, suffix)
  // ensures forall i :: 0 <= i < s ==> !EndWith(i*i,suffix)
  decreases *                   // This method may not terminate.
{
  s := 0;
  // squares is the sequence of s*s. A ghost variable is only used by the
  // verification process at compile time.
  ghost var squares := [];
  while !EndWith(s*s, suffix)
    invariant s == |squares|
    invariant forall i :: 0 <= i < s ==> squares[i] == i*i && !EndWith(squares[i], suffix)
    decreases *
  {
    squares := squares + [s*s];
    s := s + 1;
  }
  // Leaving the method:
  // s*s ends with the suffix.
  assert EndWith(s*s, suffix);
  // The sequence squares contains i*i for i in [0..s]; none of the elements of
  // squares ends with the suffix.
  assert s == |squares|;
  assert forall i :: 0 <= i < s ==> i*i == squares[i] && !EndWith(squares[i], suffix);
  // That last assertion should imply the commented-out post-condition of the
  // method, but I'm not sure how to express that.
  //
  // Conclusion: s is guaranteed to be the smallest number whose square ends
  // with the suffix.
}

method Main() decreases *
{
  var suffix := 269696;
  var smallest := SmallestSqEndingWith(suffix);
  print smallest, "\n";
}


var i = 0
while i * i % 1000000 != 269696 {
	i += 1
}

print("\(i) is the smallest number that ends with 269696")


[Babbage problem from Rosetta Code website]
[EDSAC program, Initial Orders 2]

[Library subroutine M3. Pauses the loading, prints header,
  and gets overwritten when loading resumes.
Here, the last character sets the teleprinter to figures.]
 [email protected]@E8FEZPF
 @&*[email protected]&#
        ..PZ   [blank tape, needed to mark end of header text]

[Library subroutine P6. Prints strictly positive integer.
32 locations; argument at 0, working locations 1, 4, 5]
        T56K   [define load address for subroutine]
        [email protected]@[email protected]@[email protected]@
        [email protected]@[email protected]@J995FJF!F

               [Main routine. Load after subroutine P6.
                Must be at an even address because each double
                value at the start must be at an even address.]
        T88K   [define absolute load address]
        GK     [set @ (theta) for relative addresses]

               [Variables]
    [0] PF PF     [trial solution, call it n]
    [2] PF PF     [residue of n^2 modulo 1000000]
    [4] PF PF     [1st difference for n^2]

               [Constants]
    [6] P64F PF   [2nd difference for n^2, i.e. 128]
    [8] P4F  PF   [1st difference for n, i.e. 8]
        T10#Z PF T10Z  [clears sandwich digit between 10 and 11;
                        cf. Wilkes, Wheeler & Gill, 1951, pp 110, 141-2]
   [10] #1760F V2046F  [-1000000]
        T12#Z PF T12Z  [clears sandwich digit between 12 and 13]
   [12] Q1728F PD      [269696]
   [14] &F     [line feed]
   [15] @F     [carriage return]
   [16] K4096F [teleprinter null]

           [Enter with acc = 0]
   [17] T#@    [trial number n := 0]
        T2#@   [(n^2 mod 1000000) := 0]
        S6#@   [acc := -128]
        RD     [right shift]
        T4#@   [(1st difference for n^2) := -64]

           [Start of loop]
   [22] TF     [clear acc]
        A#@    [load n]
        A8#@   [add 8]
        T#@    [update n]
        A4#@   [load 1st difference of n^2]
        A6#@   [add 128]
        T4#@   [update]
        A2#@   [load residue of n^2 mod 1000000]
        A4#@   [add 1st difference]
   [31] A10#@  [subtract 1000000, by adding -1000000]
        [email protected]   [repeat until result < 0]
        S10#@  [add back 1000000]
        U2#@   [update residue]
        S12#@  [subtract target 269696]
        [email protected]   [loop back if residue < 269696]
               [if still here, acc is non-neg mult of 64]
        S8#@   [test for acc = 0 by subtracting 8]
        [email protected]   [loop back if residue > 269696]

           [Here with the solution]
        TF     [clear acc]
        A#@    [load solution n]
        TD     [store at absolute address 0 for printing]
   [42] [email protected]   [for return from subroutine]
        G56F   [call subroutine to print n]
        [email protected]   [print CR]
        [email protected]   [print LF]
        [email protected]   [print null, to flush printer buffer]
        ZF     [stop]
        E17Z   [define entry point]
        PF     [enter with acc = 0]


import extensions;
import system'math;

public program()
{
    var n := 1;

    until(n.sqr().mod:1000000 == 269696)
    {
        n += 1
    };

    console.printLine(n)
}


defmodule Babbage do
  def problem(n) when rem(n*n,1000000)==269696, do: n
  def problem(n), do: problem(n+2)
end

IO.puts Babbage.problem(0)


-module(solution1).
-export([main/0]).
babbage(N,E) when N*N rem 1000000 == 269696 ->
	io:fwrite("~p",[N]);
babbage(N,E) ->
	case E of
	4 -> babbage(N+2,6);
	6 -> babbage(N+8,4)
end.
main()->
	babbage(4,4).


! Lines like this one are comments. They are meant for humans to
! read and have no effect on the instructions carried out by the
! computer (aside from Factor's parser ignoring them).

! Comments may appear after program instructions on the same
! line.

! Each word between USING: and ; is a vocabulary. By importing
! a vocabulary in this way, its words are made available for the
! program to use. This is a way to keep the space requirements
! down for deployed programs, and a nice side effect is that it
! gives readers a clue for where to look for documentation.

USING: kernel math math.ranges prettyprint sequences ;

! Before the program begins, it's incredibly helpful to have an
! understanding of Factor's dataflow model. Don't worry; it's
! not complicated, but it's confusing to read a Factor program
! without this knowledge.

! Factor is a stack-based language. What this means is that
! there is an implicit data stack in the background, waiting
! to recieve whatever manner of thing we wish to give it. Here
! is a simple arithmetic expression to demonstrate:

! language token | data stack
! ---------------+-----------
!     2            2      ! numbers place themselves on the stack.
!     1            2 1
!     4            2 1 4
!     +            2 5    ! consume 1 and 4 and leave behind 5.
!     *            10     ! consume 2 and 5 and leave behind 10.

! Thus the phrase

! 2 1 4 + *

! in Factor is a way to calculate 2 * (4 + 1).
! We could have also written this as

! 1 4 + 2 *

! with no change in meaning or outcome.

! Because of the way the data stack works, there is no need
! to specify order of operations in the language, because you do
! so inherently by the order you place things on the data stack.

! === BEGIN PROGRAM ============================================

518 99,736 2 <range>   ! Here we place three numbers on the
                       ! stack representing a range of numbers.
                       ! The first, 518, represents the starting
                       ! point of the sequence. 99,736
                       ! represents the ending point of the
                       ! sequence. 2 represents the "step" of
                       ! the sequence, or a constant distance
                       ! between members.

                       ! <range> takes those three numbers and
                       ! creates an object representing the
                       ! described range of numbers. Computers
                       ! of today are more than capable of
                       ! storing that many numbers, but <range>
                       ! doesn't store them all; it calculates
                       ! the number that is needed at the
                       ! current time.

                       ! The rationale for the sequence is as
                       ! follows. Odd squares are always odd, so
                       ! we don't need to consider them. That's
                       ! why the sequence starts with an even
                       ! number and is incremented by 2. We
                       ! choose 518 to start because it's the
                       ! largest even square less than 269,696.
                       ! We choose 99,736 to end because we
                       ! know it's a solution.

[ sq 1,000,000 mod 269,696 = ]
                       ! the [ ... ] form is called a quotation.
                       ! Think of it like a sequence that stores
                       ! code. It's a way to place code on the
                       ! data stack without executing it. This
                       ! is so that it can be used by the find
                       ! word. You could also think of it much
                       ! like a function that hasn't been given
                       ! a name.

find
                       ! When we call the find word, there are
                       ! two objects on the stack: a sequence
                       ! and a quotation. find is a word that
                       ! takes a sequence and a quotation and
                       ! applies the quotation to one member of
                       ! the sequence after another. It does
                       ! so until the quotation returns a t
                       ! value (denoting a boolean true) and
                       ! then leaves that number, along with its
                       ! index in the sequence, on the stack.

                       ! Let's take a look at what happens
                       ! for each iteration of find. Let's look
                       ! at what happens with the first number
                       ! in the sequence.

! language token | data stack
! ---------------+-----------
! 518              518               ! 518 is placed on the stack
                                     ! from the sequence by find.
! sq               268,324           ! square it
! 1,000,000        268,324 1,000,000 ! place a million on the stack
! mod              268,324           ! take modulus of 268,324
                                     ! and 1,000,000
! 269,696          268,324 269,696   ! place 269,696 on the stack
! =                f                 ! test 268,324 and 269,696 for
                                     ! equality.

                       ! So the square of the first number in
                       ! the sequence, 518, does not end with
                       ! 269,696. We'll try each number in the
                       ! sequence until we get a t.

.    ! Consume the top member of the data stack and print it out.

drop ! find leaves both the found element from the sequence
     ! and the index at which it was found on the data stack.
     ! We don't care about the index so we will call drop to
     ! remove it from the top of the data stack. All programs
     ! must end with an emtpy data stack.

! Putting the entire program together, it looks like this:

! 518 99,736 2 <range> [ sq 1,000,000 mod 269,696 = ] find . drop


( First we set out the steps the computer will use to solve the problem )

: BABBAGE
    1 ( start from the number 1 )
    BEGIN ( commence a "loop": the computer will return to this point repeatedly )
        1+ ( add 1 to our number )
        DUP DUP ( duplicate the result twice, so we now have three copies )
        ( We need three because we are about to multiply two of them together to find the square, and the third will be used the next time we go around the loop -- unless we have found our answer, in which case we shall need to print it out )
        * ( * means "multiply", so we now have the square )
        1000000 MOD ( find the remainder after dividing it by a million )
        269696 = ( is it equal to 269,696? )
    UNTIL ( keep repeating the steps from BEGIN until the condition is satisfied )
    . ; ( when it is satisfied, print out the number that allowed us to satisfy it )

( Now we ask the machine to carry out these instructions )

BABBAGE


' version 25-10-2016
' compile with: fbc -s console

' Charles Babbage would have known that only number ending
' on a 4 or 6 could produce a square ending on a 6
' also any number below 520 would produce a square smaller than 269,696
' we can stop when we have reached 99,736
' we know it square and it ends on 269,696

Dim As ULong number = 524 ' first number to try
Dim As ULong square, count

Do
    ' square the number
    square = number * number
    ' look at the last 6 digits, if they match print the number
    If Right(Str(square), 6) = "269696" Then Exit Do
    ' increase the number with 2, number end ons a 6
    number = number +2
    ' if the number = 99736 then we haved found a smaller number, so stop
    If number = 99736 Then Exit Do
    square = number * number
    ' look at the last 6 digits, if they match print the number
    If Right(Str(square),6 ) = "269696" Then Exit Do
    ' increase the number with 8, number ends on a 4
    number = number +8
    ' go to the first line under "Do"
Loop

If number = 99736 Then
    Print "No smaller number was found"
Else
    ' we found a smaller number, print the number and its square
    Print Using "The number = #####, and its square = ##########,"; number; square
End If

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


// This is a solver for the Rosetta Code problem "Babbage problem"
// https://rosettacode.org/wiki/Babbage_problem

i = 1
while true
{
    // mod is the modulus operator.
    // The == operator is a test for equality.  A single =
    // assigns to a variable.
    if i² mod million == 269696
    {
       // This prints i and i²
       println[i + "² = " + i²]
       exit[] 	 // This terminates the program if a solution is found.
    }
    i = i + 1
}


window 1

long i

for i = 1 to 1000000
  if i ^ 2 mod 1000000 == 269696 then exit for
next

print @"The smallest number whose square ends in 269696 is ";i
print @"Its square is ";i ^ 2

HandleEvents


Public Sub Main()
Dim iNum As Long

For iNum = 1 To 100000
  If Str(iNum * iNum) Ends "269696" Then Break
Next

Print "The lowest number squared that ends in '269696' is " & Str(iNum)

End


package main

import "fmt"

func main() {
	const (
		target  = 269696
		modulus = 1000000
	)
	for n := 1; ; n++ { // Repeat with n=1, n=2, n=3, ...
		square := n * n
		ending := square % modulus
		if ending == target {
			fmt.Println("The smallest number whose square ends with",
				target, "is", n,
			)
			return
		}
	}
}


--Calculate squares, testing for the last 6 digits
findBabbageNumber :: Integer
findBabbageNumber =
  head (filter ((269696 ==) . flip mod 1000000 . (^ 2)) [1 ..])

main :: IO ()
main =
  (putStrLn . unwords)
    (zipWith
       (++)
       (show <$> ([id, (^ 2)] <*> [findBabbageNumber]))
       [" ^ 2 equals", " !"])


public class Test {

    public static void main(String[] args) {

        // let n be zero
        int n = 0;

        // repeat the following action
        do {

            // increase n by 1
            n++;

        // while the modulo of n times n is not equal to 269696
        } while (n * n % 1000_000 != 269696);

        // show the result
        System.out.println(n);
    }
}


// Every line starting with a double slash will be ignored by the processing machine,
// just like these two.
//
// Since the square root of 269,696 is approximately 519, we create a variable named "n"
// and give it this value.
  n = 519

// The while-condition is in parentheses
// * is for multiplication
// % is for modulo operation
// != is for "not equal"
  while ( ((n * n) % 1000000) != 269696 )
    n = n + 1

// n is incremented until the while-condition is met, so n should finally be the
// smallest positive integer whose square ends in the digits 269,696. To see n, we
// need to send it to the monitoring device (named console).
  console.log(n)


function babbage(x::Integer)
  i = big(0)
  d = floor(log10(x)) + 1
  while i ^ 2 % 10 ^ d != x
    i += 1
  end
  return i
end


fun main(args: Array<String>) {
    var number = 520L
    var square = 520 * 520L

    while (true) {
        val last6 = square.toString().takeLast(6)
        if (last6 == "269696") {
            println("The smallest number is $number whose square is $square")
            return
        }
        number += 2
        square = number * number
    }
}


[start]
if right$(str$(n*n),6)="269696" then
    print "n = "; using("###,###", n);
    print "   n*n = "; using("###,###,###,###", n*n)
end if
if n<100000 then n=n+1: goto [start]
print "Program complete."


implement Babbage;

include "sys.m";
	sys: Sys;
	print: import sys;
include "draw.m";
	draw: Draw;

Babbage : module
{
	init : fn(ctxt : ref Draw->Context, args : list of string);
};

init (ctxt: ref Draw->Context, args: list of string)
{
	sys = load Sys Sys->PATH;
	current := 0;
	while ((current * current) % 1000000 != 269696)
		current++;
	print("%d", current);
}


-- get smallest number <= sqrt(269696)
k = math.floor(math.sqrt(269696))

-- if root is odd -> make it even
if k % 2 == 1 then
    k = k - 1
end

-- cycle through numbers
while not ((k * k) % 1000000 == 269696) do
    k = k + 2
end

io.write(string.format("%d * %d = %d\n", k, k, k * k))


Def Long  k=1000000, T=269696, n
n=Sqrt(269696)
For n=n to k {
      If n^2 mod k = T Then Exit
}
Report format$("The smallest number whose square ends in {0} is {1}, Its square is {2}", T, n, n**2)


-- MAXScript : Babbage problem : N.H.
posInt = 1
while posInt < 1000000 do
	(
	if (matchPattern((posInt * posInt) as string) pattern: "*269696") then exit
	posInt += 1
	)
Print "The smallest number whose square ends in 269696 is " + ((posInt) as string)
Print "Its square is " + (((pow posInt 2) as integer) as string)


' Babbage problem
' The quote (') means a comment
' The equals sign (=) means assign
n = 500
' 500 is stored in variable n*n
' 500 because 500*500=250000 less than 269696

' The nitty-gritty is in the 3 lines between "While" and "EndWhile".
' So, we start with 500, n is being incremented by 1 at each round
' while its square (n*n) (* means multiplication) does not have
' a remainder (function Math.Remainder) of 269696 when divided by one million.
' This means that the loop will stop when the smallest positive integer
' whose square ends in 269696
' is found and stored in n.
' (<>)  means "not equal to"
While Math.Remainder( n*n , 1000000 ) <> 269696
    n = n + 1
EndWhile

' (TextWindow.WriteLine) displays the string to the monitor
' (+) concatenates strings or variables to be displayed
TextWindow.WriteLine("The smallest positive integer whose square ends in 269696 is " + (n) + ".")
TextWindow.WriteLine("Its square is " + (n*n) + ".")

' End of Program.


// Lines that start with "//" are "comments" that are ignored
// by the computer.  We use them to explain the code.

// Start by finding the smallest number that could possibly
// square to 269696.  sqrt() returns the square root of a
// number, and floor() truncates any fractional part.
k = floor(sqrt(269696))

// Since 269696 is even, we are only going to consider even
// roots.  We use the % (modulo) operator, which returns the
// remainder after division, to tell if k is odd; if so, we
// add 1 to make it even.
if k % 2 == 1 then k = k + 1

// Now we count up by 2 from k, until we find a number that,
// when squared, ends in 269696 (using % again).
while k^2 % 1000000 != 269696
    k = k + 2
end while

// The first such number we find is our answer.
print k + "^2 = " + k^2


MODULE BabbageProblem;
FROM FormatString IMPORT FormatString;
FROM RealMath IMPORT sqrt;
FROM Terminal IMPORT WriteString,ReadChar;

VAR
    buf : ARRAY[0..63] OF CHAR;
    k : INTEGER;
BEGIN
    (* Find the greatest integer less than the square root *)
    k := TRUNC(sqrt(269696.0));

    (* Odd numbers cannot be solutions, so decrement *)
    IF k MOD 2 = 1 THEN
        DEC(k);
    END;

    (* Find a number that meets the criteria *)
    WHILE (k*k) MOD 1000000 # 269696 DO
        INC(k,2)
    END;

    FormatString("%i * %i = %i", buf, k, k, k*k);
    WriteString(buf);

    ReadChar
END BabbageProblem.


/* NetRexx */
options replace format comments java crossref symbols nobinary utf8
numeric digits 5000 -- set up numeric precision

babbageNr = babbage() -- call a function to perform the analysis and capture the result
babbageSq = babbageNr ** 2  -- calculate the square of the result
-- display results using a library function
System.out.printf("%,10d\u00b2 == %,12d%n", [Integer(babbageNr), Integer(babbageSq)])
return

-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- A function method to answer Babbage's question:
--   "What is the smallest positive integer whose square ends in the digits 269,696?"
--     — Babbage, letter to Lord Bowden, 1837;
--       see Hollingdale and Tootill, Electronic Computers, second edition, 1970, p. 125.
--   (He thought the answer might be 99,736, whose square is 9,947,269,696; but he couldn't be certain.)

method babbage() public static binary
  n = int 104 -- (integer arithmatic)
  -- begin a processing loop to determine the value
  -- starting point: 104
  loop while ((n * n) // 1000000) \= 269696
    -- loop continues while the remainder of n squared divided by 1,000,000 is not equal to 269,696
    if n // 10 == 4 then do
      -- increment n by 2 if the remainder of n divided by 10 equals 4
      n = n + 2
      end
    if n // 10 == 6 then do
      -- increment n by 8 if the remainder of n divided by 10 equals 6
      n = n + 8
      end
    end

  return n -- end the function and return the result


;;;	Start by assigning n the integer square root of 269696
;;;	minus 1 to be even
(setq n 518)
;;;	Increment n by 2 till the last 6 digits of its square are 269696
(while (!= (% (* n n) 1000000) 269696)
	(++ n 2))
;;;	Show the result and its square
(println n "^2 = " (* n n))


var n : int = 0
while n*n mod 1_000_000 != 269_696:
  inc(n)
echo n


class Babbage  {
  function : Main(args : String[]) ~ Nil {
    cur := 0;
    do {
      cur++;
    }
    while(cur * cur % 1000000 <> 269696);

        cur_sqr := cur * cur;
    "The square of {$cur} is {$cur_sqr}!"->PrintLine();
  }
}


let rec f a=
if (a*a) mod 1000000 != 269696
then f(a+1)
else a
in
let a= f 1 in
Printf.printf "smallest positive integer whose square ends in the digits 269696 is %d\n" a


m=269696;
k=1000000;
{for(n=1,99736,
  \\ Try each number in this range, from 1 to 99736
  if(denominator((n^2-m)/k)==1, \\ Check if n squared, minus m, is divisible by k
    return(n) \\ If so, return this number and STOP.
  )
)}


program BabbageProblem;
(* Anything bracketed off like this is an explanatory comment. *)
var n : longint; (* The VARiable n can hold a 'long', ie large, INTeger. *)
begin
    n := 2; (* Start with n equal to 2. *)
    repeat
        n := n + 2 (* Increase n by 2. *)
    until (n * n) mod 1000000 = 269696;
(* 'n * n' means 'n times n'; 'mod' means 'modulo'. *)
    write(n)
end.


#!/usr/bin/perl
use strict ;
use warnings ;

my $current = 0 ;
while ( ($current ** 2 ) % 1000000  != 269696 ) {
   $current++ ;
}
print "The square of $current is " . ($current * $current) . " !\n" ;


with javascript_semantics
for i=2 to 99736 by 2 do
    if remainder(i*i,1000000)=269696 then ?i exit end if
end for


<?php

for (
    $i = 1 ;                                    // Initial positive integer to check
    ($i * $i) % 1000000 !== 269696 ;            // While i*i does not end with the digits 269,696
    $i++                                        // ... go to next integer
);

echo $i, ' * ', $i, ' = ', ($i * $i), PHP_EOL;  // Print the result


Remark:Lines identified as "remarks" are intended for the human reader, and will be ignored by the machine.
Remark:A "compute" instruction gives a value to a variable.
Remark:We begin by making the variable n equal to 2.
Compute:n = 2
Remark:Lines beginning with asterisks are labels. We can instruct the machine to "jump" to them, rather than carrying on to the next instruction as it normally would.
*CheckNextNumber
Remark:In "compute" instructions, "x * y" should be read as "x times y" and "x % y" as "x modulo y".
Compute:square = n * n
Compute:lastSix = square % 1000000
Remark:A "jump" instruction that includes an equation or an inequality in parentheses jumps to the designated label if and only if the equation or inequality is true.
Jump( lastSix = 269696 ):*FoundIt
Remark:If the last six digits are not equal to 269696, add 2 to n and jump back to "CheckNextNumber".
Compute:n = n + 2
Jump:*CheckNextNumber
*FoundIt
Remark:Type, i.e. print, the result. The symbol "#" means that what follows is one of our variables and the machine should type its value.
Type:The smallest number whose square ends in 269696 is #n. Its square is #square.
Remark:The end.
End:


To run:
Start up.
Put 1 into a number.
Loop.
Divide the number times the number by 1000000 giving a quotient and a remainder.
If the remainder is 269696, break.
Bump the number.
Repeat.
Write "The answer is " then the number on the console.
Wait for the escape key.
Shut down.


/* Babbage might have used a difference engine to compute squares.         */
/* The algorithm used here uses only additions to form successive squares. */
/* Since there is no guarantee that the final square will not exceed a     */
/* 32-bit integer word, modulus is formed to limit the magnitude of the    */
/* squares, since we are really interested only in the last six digits of  */
/* the square.                                                             */

Babbage_problem: procedure options (main);  /* R. Vowels, 19 Dec. 2021 */
   declare n fixed decimal (5);
   declare (odd, sq) fixed binary (31);

   odd = 3; sq = 4;         /* the initial square is 4 */

   do n = 3 to 99736;
      odd = odd + 2;
      sq = sq + odd;        /* form the next square */
      if sq >= 1000000 then sq = sq - 1000000; /* keep the remainder */
      if sq = 269696 then leave;
   end;
   put ('The smallest number whose square ends in 269696 is ' || trim(n) );
   put skip list ('The corresponding square is ' || trim (n*n) );
      /* Even if the number had been 99736, n*n would not have overflowed */
      /* because decimal arithmetic allows up to 15 decimal digits.       */
end Babbage_problem;


###########################################################################################
#
# Definitions:
#
#   Lines that begin with the "#" symbol are comments: they will be ignored by the machine.
#
# -----------------------------------------------------------------------------------------
#
#   While
#
#   Run a command block based on the results of a conditional test.
#
#   Syntax
#       while (condition) {command_block}
#
#   Key
#
#       condition      If this evaluates to TRUE the loop {command_block} runs.
#                      when the loop has run once the condition is evaluated again.
#
#       command_block  Commands to run each time the loop repeats.
#
#   As long as the condition remains true, PowerShell reruns the {command_block} section.
#
# -----------------------------------------------------------------------------------------
#
#   *   means 'multiplied by'
#   %   means 'modulo', or remainder after division
#   -ne means 'is not equal to'
#   ++  means 'increment variable by one'
#
###########################################################################################

# Declare a variable, $integer, with a starting value of 0.

$integer = 0

while (($integer * $integer) % 1000000 -ne 269696)
{
    $integer++
}

# Show the result.

$integer


// Lines that begin with two slashes, thus, are comments: they
// will be ignored by the machine.

// First we must declare a variable, n, suitable to store an integer:

int n;

// Each statement we address to the machine must end with a semicolon.

// To begin with, the value of n will be zero:

n = 0;

// Now we must repeatedly increase it by one, checking each time to see
// whether its square ends in 269,696.

// We shall do this by seeing whether the remainder, when n squared
// is divided by one million, is equal to 269,696.

do {
    n = n + 1;
} while (n * n % 1000000 != 269696);

// To read this formula, it is necessary to know the following
// elements of the notation:
//     * means 'multiplied by'
//     % means 'modulo', or remainder after division
//     != means 'is not equal to'

// Now that we have our result, we need to display it.

// println is short for 'print line'

println(n);


:- use_module(library(clpfd)).

babbage_(B, B, Sq) :-
	B * B #= Sq,
	number_chars(Sq, R),
	append(_, ['2','6','9','6','9','6'], R).
babbage_(B, R, Sq) :-
	N #= B + 1,
	babbage_(N, R, Sq).

babbage :-
	once(babbage_(1, Num, Square)),
	format('lowest number is ~p which squared becomes ~p~n', [Num, Square]).


EnableExplicit
Macro putresult(n)
  If OpenConsole("Babbage_problem")
    PrintN("The smallest number whose square ends in 269696 is " + Str(n))
    Input()
  EndIf
EndMacro

CompilerIf #PB_Processor_x64
  #MAXINT = 1 << 63 - 1
CompilerElseIf #PB_Processor_x86
  #MAXINT = 1 << 31 - 1
CompilerEndIf

#GOAL = 269696
#DIV  = 1000000
Define n.i, q.i = Int(Sqr(#MAXINT))

For n = 2 To q Step 2
  If (n*n) % #DIV = #GOAL : putresult(n) : Break : EndIf
Next


# Lines that start by # are a comments:
# they will be ignored by the machine

n=0 # n is a variable and its value is 0

# we will increase its value by one until
# its square ends in 269,696

while n**2 % 1000000 != 269696:

    # n**2 -> n squared
    # %    -> 'modulo' or remainer after division
    # !=   -> not equal to

    n += 1 # += -> increase by a certain number

print(n) # prints n

# short version
>>> [x for x in range(30000) if (x*x) % 1000000 == 269696] [0]
25264


(   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   )

( The computer will ignore anything between parentheses, providing there is
  a space or carriage return on either side of each parenthesis.            )

(   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   )

( A number squared is that number, multiplied by itself.

  Here, "dup" means "make a duplicate" and "*" means "multiply two numbers",
  So "dup *" means "make a duplicate of a number and multiply it by itself".
  We will tell the computer that this action is called "squared".           )

                            [ dup * ] is squared

( "squared" takes a number and returns that number, squared.                )

(   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   )

( A number n ends with the digits 269696 if n mod 1000000 = 269696,
  When expressed in postfix notation this is: 1000000 mod 269696 =
  We will tell the computer that this test is called "ends.with.269696".    )

                [ 1000000 mod 269696 = ] is ends.with.269696

( "ends.with.269696" takes a number and returns true if it ends with 269696,
  and false if it does not.                                                 )

(   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   )

( The square root of 269696 is approximately equal to 518.35, so we need not
  consider numbers less than 519.

  Starting withe 518, we will intruct the computer to repeatedly add 2 to
  the number using the command "2 +" (because the number we are looking for
  must be an even number as the square root of any even perfect square
  must be an even number), then square a duplicate of the number until a
  value is found of which its square ends with 269696.

  "until" will take the truth value returned by "ends.with.269696" and, if
  that value is "false", will cause the previous commands from the nearest
  "[" preceding "until" to be repeated.

  When the value is "true" the computer will proceed to the word "echo",
  which will take the calculated solution and display it on the screen.     )

             518 [ 2 + dup squared ends.with.269696 until ] echo

(   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   )


babbage_function=function(){
  n=0
  while (n**2%%1000000!=269696) {
    n=n+1
  }
  return(n)
}
babbage_function()[length(babbage_function())]


;; Text from a semicolon to the end of a line is ignored
;; This lets the racket engine know it is running racket
#lang racket

;; “define” defines a function in the engine
;; we can use an English name for the function
;; a number ends in 269696 when its remainder when
;; divided by 1000000 is 269696 (we omit commas in
;; numbers... they are used for another reason).
(define (ends-in-269696? x)
  (= (remainder x 1000000) 269696))

;; we now define another function square-ends-in-269696?
;; actually this is the composition of ends-in-269696? and
;; the squaring function (which is called “sqr” in racket)
(define square-ends-in-269696? (compose ends-in-269696? sqr))

;; a for loop lets us iterate (it’s a long Latin word which
;; Victorians are good at using) over a number range.
;;
;; for/first go through the range and break when it gets to
;; the first true value
;;
;; (in-range a b) produces all of the integers from a (inclusive)
;; to b (exclusive). Because we know that 99736² ends in 269696,
;; we will stop there. The add1 is to make in-range include 99736
;;
;; we define a new variable, so that we can test the verity of
;; our result
(define first-number-that-when-squared-ends-in-269696
(for/first ((i ; “i” will become the ubiquetous looping variable of the future!
             (in-range 1 (add1 99736)))
            ; when returns when only the first one that matches
            #:when (square-ends-in-269696? i))
  i))

;; display prints values out; newline writes a new line (otherwise everything
;; gets stuck together)
(display first-number-that-when-squared-ends-in-269696)
(newline)
(display (sqr first-number-that-when-squared-ends-in-269696))
(newline)
(newline)
(display (ends-in-269696? (sqr first-number-that-when-squared-ends-in-269696)))
(newline)
(display (square-ends-in-269696? first-number-that-when-squared-ends-in-269696))
(newline)
;; that all seems satisfactory


# For all positives integers from 1 to Infinity
for 1 .. Inf -> $integer {

    # calculate the square of the integer
    my $square = $integer²;

    # print the integer and square and exit if the square modulo 1000000 is equal to 269696
    print "{$integer}² equals $square" and exit if $square mod 1000000 == 269696;
}


Red []
number: 510 ;; starting number
;; repeat, until the last condition in the block is true
until [
 number: number + 2 ;; only even numbers can have even squares
 ;; The word modulo computes the non-negative remainder of the
 ;; first argument divided by the second argument.
 ;; **  =>  Returns a number raised to a given power (exponent)
  269696 = modulo (number ** 2) 1000000
]
?? number


/*REXX program finds the  lowest (positive)  integer  whose  square  ends in  269,696.  */
   do j=2  by 2  until right(j * j, 6) == 269696 /*start  J  at two,  increment by two. */
   end                                           /*◄── signifies the end of the DO loop.*/
                                                 /* [↑]     *     means multiplication. */
say "The smallest integer whose square ends in  269,696  is: "    j


n = 0
while pow(n,2) % 1000000 != 269696
        n = n + 1
end

see "The smallest number whose square ends in 269696 is : " + n + nl
see "Its square is : " + pow(n,2)


for n = 1 to  1000000
if n^2 MOD 1000000 = 269696 then exit for
next

PRINT "The smallest number whose square ends in 269696 is "; n
PRINT "Its square is "; n^2


fn main() {
    let mut current = 0;
    while (current * current) % 1_000_000 != 269_696 {
        current += 1;
    }
    println!(
        "The smallest number whose square ends in 269696 is {}",
        current
    );
}


object BabbageProblem {
    def main( args:Array[String] ): Unit = {

        var x : Int = 524        // Sqrt of 269696 = 519.something

        while( (x * x) % 1000000 != 269696 ){
            if( x % 10 == 4 ) x = x + 2
            else x = x + 8
        }

        println("The smallest positive integer whose square ends in 269696 = " + x )
    }
}


(define (digits n)
  (string->list (number->string n)))

(define (ends-with list tail)
  ;; does list end with tail?
  (starts-with (reverse list)
               (reverse tail)))

(define (starts-with list head)
  (cond ((null? head)
         #t)
        ((null? list)
         #f)
        ((equal? (car list) (car head))
         (starts-with (cdr list) (cdr head)))
        (else
         #f)))

(let loop ((i 1))
  (if (ends-with (digits (* i i)) (digits 269696))
      i
      (loop (+ i 1))))

;; 25264


n=2;
flag=%F
    while ~flag
        n = n+2;
        if pmodulo(n*n,1000000)==269696 then
            flag=%T;
        end
end
disp(n);


$ include "seed7_05.s7i";

const proc: main is func
  local
    var integer: current is 0;
  begin
    while current ** 2 rem 1000000 <> 269696 do
      incr(current);
    end while;
    writeln("The square of " <& current <& " is " <& current ** 2);
  end func;


(*
Answer Charles Babbage's question:
What is the smallest positive integer whose square ends in the digits 269,696?
*)

put 1 into int

repeat forever
	if int squared ends with "269696" then
		put "The smallest positive integer whose square ends in the digits 269696 is" && int
		exit all -- don't keep repeating forever!
	end if

	add 1 to int
end repeat


main() := babbage(0);

babbage(current) :=
        current when current * current mod 1000000 = 269696
    else
        babbage(current + 1);


(define babbage
    N -> N where (= 269696 (shen.mod (* N N) 1000000)))
    N -> (babbage (+ N 1))

(babbage 1)


BEGIN
    INTEGER PROBE, SQUARE;
    BOOLEAN DONE;

    WHILE NOT DONE DO BEGIN
        PROBE := PROBE + 1;
        SQUARE := PROBE * PROBE;
        IF MOD(SQUARE, 1000000) = 269696 THEN BEGIN

            OUTTEXT("THE SMALLEST NUMBER: ");
            OUTINT(PROBE,0);
            OUTIMAGE;

            OUTTEXT("THE SQUARE : ");
            OUTINT(SQUARE,0);
            OUTIMAGE;

            DONE := TRUE;
        END;
    END;

END


"We use one variable, called n. Let it initially be equal to 1. Then keep increasing it by 1 for only as long as the remainder after dividing by a million is not equal to 269,696; finally, show the value of n."
| n |
n := 1.
[ n squared \\ 1000000 = 269696 ] whileFalse: [ n := n + 1 ].
n


/*
This code is an implementation of Babbage Problem in SQL ORACLE 19c
p_ziel  -- the substring to search for, which can start with leading zeros
p_max   -- upper bound of the cycle
v_max   -- safe determination of the upper bound of the cycle
v_start -- safe starting point
*/
WITH
  FUNCTION babbage(p_ziel IN varchar2, p_max INTEGER) RETURN varchar2 IS
    v_max    INTEGER := greatest(p_max,to_number('1E+'||LENGTH(to_char(p_ziel))));
    v_start  NUMBER := CASE WHEN substr(p_ziel,1,1)='0' THEN CEIL(SQRT('1'||p_ziel)) ELSE CEIL(SQRT(p_ziel)) END;
    v_length NUMBER := to_number('1E+'||LENGTH(to_char(p_ziel)));
  BEGIN
    -- first check
    IF substr(p_ziel,-1) IN (2,3,7,8) THEN
      RETURN 'The exact square of an integer cannot end with '''||substr(p_ziel,-1)||''', so there is no such smallest number whose square ends in '''||p_ziel||'''';
    END IF;
    -- second check
    IF regexp_count(p_ziel,'([^0]0{1,}$)')=1 AND MOD(regexp_count(regexp_substr(p_ziel,'(0{1,}$)'),'0'),2)=1 THEN
      RETURN 'An exact square of an integer cannot end with an odd number of zeros, so there is no such smallest number whose square ends in '''||p_ziel||'''';
    END IF;
    -- main cycle
    while v_start < v_max loop
      exit WHEN MOD(v_start**2,v_length) = p_ziel;
      v_start := v_start + 1;
    END loop;
    -- output
    IF v_start = v_max THEN
      RETURN 'There is no such smallest number before '||v_max||' whose square ends in '''||p_ziel||'''';
    ELSE
      RETURN ''||v_start||' is the smallest number, whose square '||regexp_replace(to_char(v_start**2),'(\d{1,})('||p_ziel||')','\1''\2''')||' ends in '''||p_ziel||'''';
    END IF;
    --
  END;

--Test
SELECT babbage('222',100000) AS res FROM dual
UNION ALL
SELECT babbage('33',100000) AS res FROM dual
UNION ALL
SELECT babbage('17',100000) AS res FROM dual
UNION ALL
SELECT babbage('888',100000) AS res FROM dual
UNION ALL
SELECT babbage('1000',100000) AS res FROM dual
UNION ALL
SELECT babbage('000',100000) AS res FROM dual
UNION ALL
SELECT babbage('269696',100000) AS res FROM dual -- strict Babbage Problem
UNION ALL
SELECT babbage('269696',10) AS res FROM dual
UNION ALL
SELECT babbage('169696',10) AS res FROM dual
UNION ALL
SELECT babbage('19696',100000) AS res FROM dual
UNION ALL
SELECT babbage('04',100000) AS res FROM dual;


import Swift

for i in 2...Int.max {
	if i * i % 1000000 == 269696 {
		print(i, "is the smallest number that ends with 269696")
		break
	}
}


for {set i 1} {![string match *269696 [expr $i*$i]]} {incr i} {}
puts "$i squared is [expr $i*$i]"


#lang transd

MainModule : {
    rem: 269696,

    _start: (lambda
        (with n (to-Int (sqrt rem))
            (while (neq (mod (pow n 2) 1000000) rem) (+= n 1))
            (lout n)
    )   )
}


# Program to determine the smallest positive integer whose square
# has a decimal representation ending in the digits 269,696.

# Start with the smallest positive integer of them all
let trial_value=1

# Compute the remainder when the square of the current trial value is divided
# by 1,000,000.␣
while (( trial_value * trial_value % 1000000 != 269696 )); do
  # As long as this value is not yet 269,696, increment
  # our trial integer and try again.
  let trial_value=trial_value+1
done

# To get here we must have found an integer whose square meets the
# condition; display that final result
echo $trial_value


···
http://rosettacode.org/wiki/Babbage_problem
···
■ BabbageProblem
  § static
    ▶ main
    • args⦂ String[]
      for each number from √269696 up to √Integer.MAX_VALUE
          if ("⸨number × number⸩").endsWith "269696"
             System.exit number


36 35 34 33 32 31 00000008'010E0000' 0000     1 result: .ascid  "123456"                ;output buffer
                               0000  000E     2 retlen: .word   0                       ;$fao_s bytes written
         4C 55 21 00000018'010E0000' 0010     3 format: .ascid  "!UL"                   ;unsigned decimal
                                     001B     4
                               0000  001B     5 .entry  bab,0
                            55   D4  001D     6         clrl    r5                      ;result
                                     001F     7 10$:
                            55   D6  001F     8         incl    r5
             56   00   55   55   7A  0021     9         emul    r5,r5,#0,r6             ;mulr.rl, muld.rl, add.rl, prod.wq
    51   50   56   000F4240 8F   7B  0026    10         ediv    #1000000,r6,r0,r1       ;divr.rl, divd.rq, quo.wl, rem.wl
              51   00041D80 8F   D1  002F    11         cmpl    #269696,r1
                            E7   12  0036    12         bneq    10$                     ;not equal - try next
                                     0038    13
                                     0038    14         $fao_s -                        ;convert integer to text
                                     0038    15                  ctrstr = format, -
                                     0038    16                  outlen = retlen, -
                                     0038    17                  outbuf = result, -
                                     0038    18                  p1     = r5
                 B1 AF   C1 AF   B0  004A    19         movw    retlen, result          ;adjust length
                         AE AF   7F  004F    20         pushaq  result
              00000000'GF   01   FB  0052    21         calls   #1, g^lib$put_output
                                 04  0059    22         ret
                                     005A    23 .end    bab
$ run bab
25264


Sub Baggage_Problem()
Dim i As Long

    'We can start at the square root of 269696
    i = 520
    '269696 is a multiple of 4, 520 too
    'so we can increment i by 4
    Do While ((i * i) Mod 1000000) <> 269696
        i = i + 4 'Increment by 4
    Loop
    Debug.Print "The smallest positive integer whose square ends in the digits 269 696 is : " & i & vbCrLf & _
    "Its square is : " & i * i
End Sub


'Sir, this is a script that could solve your problem.

'Lines that begin with the apostrophe are comments. The machine ignores them.

'The next line declares a variable n and sets it to 0. Note that the
'equals sign "assigns", not just "relates". So in here, this is more
'of a command, rather than just a mere proposition.
n = 0

'Starting from the initial value, which is 0, n is being incremented
'by 1 while its square, n * n (* means multiplication) does not have
'a modulo of 269696 when divided by one million. This means that the
'loop will stop when the smallest positive integer whose square ends
'in 269696 is found and stored in n. Before I forget, "<>" basically
'means "not equal to".
Do While ((n * n) Mod 1000000) <> 269696
    n = n + 1 'Increment by 1.
Loop

'The function "WScript.Echo" displays the string to the monitor. The
'ampersand concatenates strings or variables to be displayed.
WScript.Echo("The smallest positive integer whose square ends in 269696 is " & n & ".")
WScript.Echo("Its square is " & n*n & ".")

'End of Program.


Module Module1

    Function Right6Digits(num As Long) As Long
        Dim asString = num.ToString()
        If asString.Length < 6 Then
            Return num
        End If

        Dim last6 = asString.Substring(asString.Length - 6)
        Return Long.Parse(last6)
    End Function

    Sub Main()
        Dim bnSq = 0    'the base number squared
        Dim bn = 0      'the number to be squared

        Do
            bn = bn + 1
            bnSq = bn * bn
        Loop While Right6Digits(bnSq) <> 269696

        Console.WriteLine("The smallest integer whose square ends in 269,696 is {0}", bn)
        Console.WriteLine("The square is {0}", bnSq)
    End Sub

End Module


const (
    target  = 269696
    modulus = 1000000
)
fn main() {
	for n := 1; ; n++ { // Repeat with n=1, n=2, n=3, ...
		square := n * n
		ending := square % modulus
		if ending == target {
			println("The smallest number whose square ends with $target is $n")
			return
		}
	}
}


/*
    The answer must be an even number and it can't be less than the square root of 269,696.
    So, if we start from that, keep on adding 2 and squaring it we'll eventually find the answer.
*/

import "/fmt" for Fmt                // this enables us to format numbers with thousand separators

var start = 269696.sqrt.ceil         // get the next integer higher than (or equal to) the square root
start = (start/2).ceil * 2           // if it's odd, use the next even integer
var i = start                        // assign it to a variable 'i' for use in the following loop
while (true) {                       // loop indefinitely till we find the answer
    var sq = i * i                   // get the square of 'i'
    var last6 = sq % 1000000         // get its last 6 digits by taking the remainder after division by a million
    if (last6 == 269696) {           // if those digits are 269696, we're done and can print the result
        Fmt.print("The lowest number whose square ends in 269,696 is $,d.", i)
        Fmt.print("Its square is $,d.", sq)
        break                        // break from the loop and end the program
    }
    i = i + 2                        // increase 'i' by 2
}


# What is the lowest number whose square ends in 269,696?

# At the very end, when we have a result and we need to print it, we shall use for the purpose a program called PRINTF, which forms part of a library of similar utility programs that are provided for us. The codes given here will be needed at that point to tell PRINTF that we are asking it to print a decimal integer (as opposed to, for instance, text):

.data
decin: .string "%d\n\0"

# This marks the beginning of our program proper:

.text
.global main

main:

# We shall test numbers from 1 upwards to see whether their squares leave a remainder of 269,696 when divided by a million.

# We shall be making use of four machine 'registers', called EAX, EBX, ECX, and EDX. Each can hold one integer.

# Move the number 1,000,000 into EBX:

        mov    $1000000, %ebx

# The numbers we are testing will be stored in ECX. We start by moving a 1 there:

        mov    $1,       %ecx

# Now we need to test whether the number satisfies our requirements. We shall want the computer to come back and repeat this sequence of instructions for each successive integer until we have found the answer, so we put a label ('next') to which we can refer.

next:

# We move (in fact copy) the number stored in ECX into EAX, where we shall be able to perform some calculations upon it without disturbing the original:

        mov    %ecx,     %eax

# Multiply the number in EAX by itself:

        mul    %eax

# Divide the number in EAX (now the square of the number in ECX) by the number in EBX (one million). The quotient -- for which we have no use -- will be placed in EAX, and the remainder in EDX:

        idiv   %ebx

# Compare the number in EDX with 269,696. If they are equal, jump ahead to the label 'done':

        cmp    $269696,  %edx
        je     done

# Otherwise, increment the number in ECX and jump back to the label 'next':

        inc    %ecx
        jmp    next

# If we get to the label 'done', it means the answer is in ECX.

done:

# Put a reference to the codes for PRINTF into EAX:

        lea    decin,    %eax

# Now copy the number in ECX, which is our answer, into an area of temporary storage where PRINTF will expect to find it:

        push   %ecx

# Do the same with EAX -- giving the code for 'decimal integer' -- and then call PRINTF to print the answer:

        push   %eax
        call   printf

# The pieces of information we provided to PRINTF are still taking up some temporary storage. They are no longer needed, so make that space available again:

        add    $8,       %esp

# Place the number 0 in EAX -- a conventional way of indicating that the program has finished correctly -- and return control to whichever program called this one:

        mov    $0,       %eax
        ret

# The end.


; The computer will evaluate expressions written in -- possibly nested -- parentheses, where the first symbol gives the operation and any subsequent symbols or numbers give the operands.

; For instance, (+ (+ 2 2) (- 7 5)) evaluates to 6.

; We define our problem as a function:

(define (try n)

; We are looking for a value of n that leaves 269,696 as the remainder when its square is divided by a million.

; The symbol * stands for multiplication.

    (if (= (remainder (* n n) 1000000) 269696)

; If this condition is met, the function should give us the value of n:

        n

; If not, it should try n+1:

        (try (+ n 1))))

; We supply our function with 1 as an initial value to test, and ask the computer to print the final result.

(print (try 1))


// Charles Babbage habría sabido que solo un número que termina en 4 o 6
// podría producir un cuadrado que termina en 6, y cualquier número por
// debajo de 520 produciría un cuadrado menor que 269696. Podemos detenernos
// cuando hayamos alcanzado 99736, sabemos que es cuadrado y termina en 269696.

number = 524 // primer numero a probar
repeat
	number = number + 2
until mod((number ^ 2), 1000000) = 269696
print "El menor numero cuyo cuadrado termina en 269696 es: ", number
print "Y su cuadrado es: ", number*number


// The magic number is 269696, so, starting about its square root,
// find the first integer that, when squared, its last six digits are the magic number.
// The last digits are found with modulo, represented here by the % symbol
const N=269696; [500..].filter1(fcn(n){ n*n%0d1_000_000 == N })


T SMA
   [Float] data
   sum = 0.0
   index = 0
   n_filled = 0
   Int period

   F (period)
      .period = period
      .data = [0.0] * period

   F add(v)
      .sum += v - .data[.index]
      .data[.index] = v
      .index = (.index + 1) % .period
      .n_filled = min(.period, .n_filled + 1)
      R .sum / .n_filled

V sma3 = SMA(3)
V sma5 = SMA(5)

L(e) [1, 2, 3, 4, 5, 5, 4, 3, 2, 1]
   print(‘Added #., sma(3) = #.6, sma(5) = #.6’.format(e, sma3.add(e), sma5.add(e)))


*        Averages/Simple moving average  26/08/2015
AVGSMA   CSECT
         USING  AVGSMA,R12
         LR     R12,R15
         ST     R14,SAVER14
         ZAP    II,=P'0'           ii=0
         LA     R7,1
         LH     R3,NA
         SRA    R3,1               na/2
LOOPA    CR     R7,R3              do i=1 to na/2
         BH     ELOOPA
         AP     II,=P'1000'        ii=ii+1000
         LR     R1,R7              i
         MH     R1,=H'6'
         LA     R4,A-6(R1)
         MVC    0(6,R4),II         a(i)=ii
         LH     R1,NA              na
         SR     R1,R7              -i
         MH     R1,=H'6'
         LA     R4,A(R1)
         MVC    0(6,R4),II         a(na+1-i)=ii
         LA     R7,1(R7)
         B      LOOPA
ELOOPA   XPRNT  =CL30' n     sma3        sma5       ',30
         XPRNT  =CL30' ----- ----------- -----------',30
         LA     R7,1               i=1
LOOP     CH     R7,NA              do i=1 to na
         BH     RETURN
         STH    R7,N               n=i
         XDECO  R7,C               i
         MVC    BUF+1(5),C+7
         MVC    P,=H'3'            p=3
         BAL    R14,SMA
         MVC    C(13),EDMASK
         ED     C(13),SS           sma(3,i)
         MVC    BUF+7(11),C+2
         MVC    P,=H'5'            p=5
         BAL    R14,SMA
         MVC    C(13),EDMASK
         ED     C(13),SS           sma(5,i)
         MVC    BUF+19(11),C+2
         XPRNT  BUF,30             output i,sma3,sma5
         LA     R7,1(R7)
         B      LOOP
*        *****  sub sma(p,n) returns(PL6)
SMA      LH     R5,N
         SH     R5,P
         A      R5,=F'1'           ia=n-p+1
         C      R5,=F'1'
         BH     OKIA
         LA     R5,1               ia=1
OKIA     LH     R6,NA              ib=na
         CH     R6,N
         BL     OKIB
         LH     R6,N               ib=n
OKIB     ZAP    II,=P'0'           ii=0
         ZAP    SS,=P'0'           ss=0
         LR     R3,R5              k=ia
LOOPK    CR     R3,R6              do k=ia to ib
         BH     ELOOPK
         AP     II,=P'1'           ii=ii+1
         LR     R1,R3
         MH     R1,=H'6'
         LA     R4,A-6(R1)
         MVC    C(6),0(R4)         ss=ss+a(k)
         AP     SS,C(6)
         LA     R3,1(R3)
         B      LOOPK
ELOOPK   ZAP    C,SS
         DP     C,II
         ZAP    SS,C(10)           ss=ss/ii
         BR     R14
RETURN   L      R14,SAVER14        restore caller address
         XR     R15,R15
         BR     R14
SAVER14  DS     F
NN       EQU    10
NA       DC     AL2(NN)
A        DS     (NN)PL6
II       DS     PL6
SS       DS     PL6
P        DS     H
N        DS     H
C        DS     CL16
BUF      DC     CL30'                              '  buffer
EDMASK   DC     X'4020202020202021204B202020'  CL13
         YREGS
         END    AVGSMA


generic
   Max_Elements : Positive;
   type Number is digits <>;
package Moving is
   procedure Add_Number (N : Number);
   function Moving_Average (N : Number) return Number;
   function Get_Average return Number;
end Moving;


MODE SMAOBJ  = STRUCT(
  LONG REAL sma,
  LONG REAL sum,
  INT period,
  REF[]LONG REAL values,
  INT lv
);

MODE SMARESULT = UNION (
  REF SMAOBJ # handle #,
  LONG REAL # sma #,
  REF[]LONG REAL # values #
);

MODE SMANEW = INT,
     SMAFREE = STRUCT(REF SMAOBJ free obj),
     SMAVALUES = STRUCT(REF SMAOBJ values obj),
     SMAADD = STRUCT(REF SMAOBJ add obj, LONG REAL v),
     SMAMEAN = STRUCT(REF SMAOBJ mean obj, REF[]LONG REAL v);

MODE ACTION = UNION ( SMANEW, SMAFREE, SMAVALUES, SMAADD, SMAMEAN );

PROC sma = ([]ACTION action)SMARESULT:
(
  SMARESULT result;
  REF SMAOBJ obj;
  LONG REAL v;

  FOR i FROM LWB action TO UPB action DO
    CASE action[i] IN
    (SMANEW period):( # args: INT period #
       HEAP SMAOBJ handle;
       sma OF handle := 0.0;
       period OF handle := period;
       values OF handle := HEAP [period OF handle]LONG REAL;
       lv OF handle := 0;
       sum OF handle := 0.0;
       result := handle
    ),
    (SMAFREE args):( # args: REF SMAOBJ free obj #
       free obj OF args := REF SMAOBJ(NIL) # let the garbage collector do it's job #
    ),
    (SMAVALUES args):( # args: REF SMAOBJ values obj #
       result := values OF values obj OF args
    ),
    (SMAMEAN args):( # args: REF SMAOBJ mean obj #
       result := sma OF mean obj OF args
    ),
    (SMAADD args):( # args: REF SMAOBJ add obj, LONG REAL v #
       obj := add obj OF args;
       v := v OF args;
       IF lv OF obj < period OF obj THEN
         (values OF obj)[lv OF obj+:=1] := v;
         sum OF obj +:= v;
         sma OF obj := sum OF obj / lv OF obj
       ELSE
         sum OF obj -:= (values OF obj)[ 1+ lv OF obj MOD period OF obj];
         sum OF obj +:= v;
         sma OF obj := sum OF obj / period OF obj;
         (values OF obj)[ 1+ lv OF obj  MOD  period OF obj ] := v; lv OF obj+:=1
       FI;
       result := sma OF obj
    )
    OUT
      SKIP
    ESAC
  OD;
  result
);

[]LONG REAL v = ( 1, 2, 3, 4, 5, 5, 4, 3, 2, 1 );

main: (
  INT i;

  REF SMAOBJ h3 := ( sma(SMANEW(3)) | (REF SMAOBJ obj):obj );
  REF SMAOBJ h5 := ( sma(SMANEW(5)) | (REF SMAOBJ obj):obj );

  FOR i FROM LWB v TO UPB v DO
    printf(($"next number "g(0,6)", SMA_3 = "g(0,6)", SMA_5 = "g(0,6)l$,
           v[i], (sma(SMAADD(h3, v[i]))|(LONG REAL r):r), ( sma(SMAADD(h5, v[i])) | (LONG REAL r):r )
    ))
  OD#;

  sma(SMAFREE(h3));
  sma(SMAFREE(h5))
#
)


MsgBox % MovingAverage(5,3)  ; 5, averaging length <- 3
MsgBox % MovingAverage(1)    ; 3
MsgBox % MovingAverage(-3)   ; 1
MsgBox % MovingAverage(8)    ; 2
MsgBox % MovingAverage(7)    ; 4

MovingAverage(x,len="") {    ; for integers (faster)
  Static
  Static sum:=0, n:=0, m:=10 ; default averaging length = 10
  If (len>"")                ; non-blank 2nd parameter: set length, reset
     sum := n := i := 0, m := len
  If (n < m)                 ; until the buffer is not full
     sum += x, n++           ;   keep summing data
  Else                       ; when buffer is full
     sum += x-v%i%           ;   add new, subtract oldest
  v%i% := x, i := mod(i+1,m) ; remember last m inputs, cycle insertion point
  Return sum/n
}


#!/usr/bin/awk -f
# Moving average over the first column of a data file
BEGIN {
    P = 5;
}

{
    x = $1;
    i = NR % P;
    MA += (x - Z[i]) / P;
    Z[i] = x;
    print MA;
}


      MAXPERIOD = 10
      FOR n = 1 TO 5
        PRINT "Number = ";n TAB(12) " SMA3 = ";FNsma(n,3) TAB(30) " SMA5 = ";FNsma(n,5)
      NEXT
      FOR n = 5 TO 1 STEP -1
        PRINT "Number = ";n TAB(12) " SMA3 = ";FNsma(n,3) TAB(30) " SMA5 = ";FNsma(n,5)
      NEXT
      END

      DEF FNsma(number, period%)
      PRIVATE nums(), accum(), index%(), window%()
      DIM nums(MAXPERIOD,MAXPERIOD), accum(MAXPERIOD)
      DIM index%(MAXPERIOD), window%(MAXPERIOD)
      accum(period%) += number - nums(period%,index%(period%))
      nums(period%,index%(period%)) = number
      index%(period%) = (index%(period%) + 1) MOD period%
      IF window%(period%)<period% window%(period%) += 1
      = accum(period%) / window%(period%)


SMA ← {(+´÷≠)¨(1↓𝕨↑↑𝕩)∾<˘𝕨↕𝕩}

v ← (⊢∾⌽)1+↕5
•Show 5 SMA v

SMA2 ← {
  𝕊 size:
  nums ← ⟨⟩
  sum ← 0
  {
    nums ∾↩ 𝕩
     gb ← {(≠nums)≤size ? 0 ; a←⊑nums, nums↩1↓nums, a}
    sum +↩ 𝕩 - gb
    sum ÷ ≠nums
  }
}

fun ← SMA2 5
Fun¨ v


SMA = object.new

SMA.init = { period |
  my.period = period
  my.list = []
  my.average = 0
}

SMA.prototype.add = { num |
  true? my.list.length >= my.period
    { my.list.deq }

  my.list << num
  my.average = my.list.reduce(:+) / my.list.length
}

sma3 = SMA.new 3
sma5 = SMA.new 5
[1, 2, 3, 4, 5, 5, 4, 3, 2, 1].each { n |
  p n, " - SMA3: ", sma3.add(n), " SMA5: ", sma5.add(n)
}


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

typedef struct sma_obj {
  double sma;
  double sum;
  int period;
  double *values;
  int lv;
} sma_obj_t;

typedef union sma_result {
  sma_obj_t *handle;
  double sma;
  double *values;
} sma_result_t;

enum Action { SMA_NEW, SMA_FREE, SMA_VALUES, SMA_ADD, SMA_MEAN };
sma_result_t sma(enum Action action, ...)
{
  va_list vl;
  sma_result_t r;
  sma_obj_t *o;
  double v;

  va_start(vl, action);
  switch(action) {
  case SMA_NEW: // args: int period
    r.handle = malloc(sizeof(sma_obj_t));
    r.handle->sma = 0.0;
    r.handle->period = va_arg(vl, int);
    r.handle->values = malloc(r.handle->period * sizeof(double));
    r.handle->lv = 0;
    r.handle->sum = 0.0;
    break;
  case SMA_FREE: // args: sma_obj_t *handle
    r.handle = va_arg(vl, sma_obj_t *);
    free(r.handle->values);
    free(r.handle);
    r.handle = NULL;
    break;
  case SMA_VALUES: // args: sma_obj_t *handle
    o = va_arg(vl, sma_obj_t *);
    r.values = o->values;
    break;
  case SMA_MEAN: // args: sma_obj_t *handle
    o = va_arg(vl, sma_obj_t *);
    r.sma = o->sma;
    break;
  case SMA_ADD: // args: sma_obj_t *handle, double value
    o = va_arg(vl, sma_obj_t *);
    v = va_arg(vl, double);
    if ( o->lv < o->period ) {
      o->values[o->lv++] = v;
      o->sum += v;
      o->sma = o->sum / o->lv;
    } else {
      o->sum -= o->values[ o->lv % o->period];
      o->sum += v;
      o->sma = o->sum / o->period;
      o->values[ o->lv % o->period ] = v; o->lv++;
    }
    r.sma = o->sma;
    break;
  }
  va_end(vl);
  return r;
}


using System;
using System.Collections.Generic;
using System.Linq;

namespace SMA {
    class Program {
        static void Main(string[] args) {
            var nums = Enumerable.Range(1, 5).Select(n => (double)n);
            nums = nums.Concat(nums.Reverse());

            var sma3 = SMA(3);
            var sma5 = SMA(5);

            foreach (var n in nums) {
                Console.WriteLine("{0}    (sma3) {1,-16} (sma5) {2,-16}", n, sma3(n), sma5(n));
            }
        }

        static Func<double, double> SMA(int p) {
            Queue<double> s = new Queue<double>(p);
            return (x) => {
                if (s.Count >= p) {
                    s.Dequeue();
                }
                s.Enqueue(x);
                return s.Average();
            };
        }
    }
}


#include <iostream>
#include <stddef.h>
#include <assert.h>

using std::cout;
using std::endl;

class SMA {
public:
	SMA(unsigned int period) :
		period(period), window(new double[period]), head(NULL), tail(NULL),
				total(0) {
		assert(period >= 1);
	}
	~SMA() {
		delete[] window;
	}

	// Adds a value to the average, pushing one out if nescessary
	void add(double val) {
		// Special case: Initialization
		if (head == NULL) {
			head = window;
			*head = val;
			tail = head;
			inc(tail);
			total = val;
			return;
		}

		// Were we already full?
		if (head == tail) {
			// Fix total-cache
			total -= *head;
			// Make room
			inc(head);
		}

		// Write the value in the next spot.
		*tail = val;
		inc(tail);

		// Update our total-cache
		total += val;
	}

	// Returns the average of the last P elements added to this SMA.
	// If no elements have been added yet, returns 0.0
	double avg() const {
		ptrdiff_t size = this->size();
		if (size == 0) {
			return 0; // No entries => 0 average
		}
		return total / (double) size; // Cast to double for floating point arithmetic
	}

private:
	unsigned int period;
	double * window; // Holds the values to calculate the average of.

	// Logically, head is before tail
	double * head; // Points at the oldest element we've stored.
	double * tail; // Points at the newest element we've stored.

	double total; // Cache the total so we don't sum everything each time.

	// Bumps the given pointer up by one.
	// Wraps to the start of the array if needed.
	void inc(double * & p) {
		if (++p >= window + period) {
			p = window;
		}
	}

	// Returns how many numbers we have stored.
	ptrdiff_t size() const {
		if (head == NULL)
			return 0;
		if (head == tail)
			return period;
		return (period + tail - head) % period;
	}
};

int main(int argc, char * * argv) {
	SMA foo(3);
	SMA bar(5);

	int data[] = { 1, 2, 3, 4, 5, 5, 4, 3, 2, 1 };
	for (int * itr = data; itr < data + 10; itr++) {
		foo.add(*itr);
		cout << "Added " << *itr << " avg: " << foo.avg() << endl;
	}
	cout << endl;
	for (int * itr = data; itr < data + 10; itr++) {
		bar.add(*itr);
		cout << "Added " << *itr << " avg: " << bar.avg() << endl;
	}

	return 0;
}


(import '[clojure.lang PersistentQueue])

(defn enqueue-max [q p n]
  (let [q (conj q n)]
    (if (<= (count q) p) q (pop q))))

(defn avg [coll] (/ (reduce + coll) (count coll)))

(defn init-moving-avg [p]
  (let [state (atom PersistentQueue/EMPTY)]
    (fn [n]
      (avg (swap! state enqueue-max p n)))))


I = (P) ->
  # The cryptic name "I" follows the problem description;
  # it returns a function that computes a moving average
  # of successive values over the period P, using closure
  # variables to maintain state.
  cq = circular_queue(P)
  num_elems = 0
  sum = 0

  SMA = (n) ->
    sum += n
    if num_elems < P
      cq.add(n)
      num_elems += 1
      sum / num_elems
    else
      old = cq.replace(n)
      sum -= old
      sum / P

circular_queue = (n) ->
  # queue that only ever stores up to n values;
  # Caller shouldn't call replace until n values
  # have been added.
  i = 0
  arr = []

  add: (elem) ->
    arr.push elem
  replace: (elem) ->
    # return value whose age is "n"
    old_val = arr[i]
    arr[i] = elem
    i = (i + 1) % n
    old_val

# The output of the code below should convince you that
# calling I multiple times returns functions with independent
# state.
sma3 = I(3)
sma7 = I(7)
sma11 = I(11)
for i in [1..10]
  console.log i, sma3(i), sma7(i), sma11(i)


(defun simple-moving-average (period &aux
    (sum 0) (count 0) (values (make-list period)) (pointer values))
  (setf (rest (last values)) values)  ; construct circularity
  (lambda (n)
    (when (first pointer)
      (decf sum (first pointer)))     ; subtract old value
    (incf sum n)                      ; add new value
    (incf count)
    (setf (first pointer) n)
    (setf pointer (rest pointer))     ; advance pointer
    (/ sum (min count period))))


def sma(n) Proc(Float64, Float64)
	a = Array(Float64).new
	->(x : Float64) {
		a.shift if a.size == n
		a.push x
		a.sum / a.size.to_f
	}
end

sma3, sma5 = sma(3), sma(5)

# Copied from the Ruby solution.
(1.upto(5).to_a + 5.downto(1).to_a).each do |n|
	printf "%d: sma3 = %.3f - sma5 = %.3f\n", n, sma3.call(n.to_f), sma5.call(n.to_f)
end


import std.stdio, std.traits, std.algorithm;

auto sma(T, int period)() pure nothrow @safe {
    T[period] data = 0;
    T sum = 0;
    int index, nFilled;

    return (in T v) nothrow @safe @nogc {
        sum += -data[index] + v;
        data[index] = v;
        index = (index + 1) % period;
        nFilled = min(period, nFilled + 1);
        return CommonType!(T, float)(sum) / nFilled;
    };
}

void main() {
    immutable s3 = sma!(int, 3);
    immutable s5 = sma!(double, 5);

    foreach (immutable e; [1, 2, 3, 4, 5, 5, 4, 3, 2, 1])
        writefln("Added %d, sma(3) = %f, sma(5) = %f", e, s3(e), s5(e));
}


program Simple_moving_average;

{$APPTYPE CONSOLE}

type
  TMovingAverage = record
  private
    buffer: TArray<Double>;
    head: Integer;
    Capacity: Integer;
    Count: Integer;
    sum, fValue: Double;
  public
    constructor Create(aCapacity: Integer);
    function Add(Value: Double): Double;
    procedure Reset;
    property Value: Double read fValue;
  end;

{ TMovingAverage }

function TMovingAverage.Add(Value: Double): Double;
begin
  head := (head + 1) mod Capacity;
  sum := sum + Value - buffer[head];
  buffer[head] := Value;

  if count < capacity then
  begin
    inc(Count);
    fValue := sum / count;
    exit(fValue);
  end;
  fValue := sum / Capacity;
  Result := fValue;
end;

constructor TMovingAverage.Create(aCapacity: Integer);
begin
  Capacity := aCapacity;
  SetLength(buffer, aCapacity);
  Reset;
end;

procedure TMovingAverage.Reset;
var
  i: integer;
begin
  head := -1;
  Count := 0;
  sum := 0;
  fValue := 0;
  for i := 0 to High(buffer) do
    buffer[i] := 0;
end;

var
  avg3, avg5: TMovingAverage;
  i: Integer;

begin
  avg3 := TMovingAverage.Create(3);
  avg5 := TMovingAverage.Create(5);

  for i := 1 to 5 do
  begin
    write('Inserting ', i, ' into avg3 ', avg3.Add(i): 0: 4);
    writeln(' Inserting ', i, ' into avg5 ', avg5.Add(i): 0: 4);
  end;

  for i := 5 downto 1 do
  begin
    write('Inserting ', i, ' into avg3 ', avg3.Add(i): 0: 4);
    writeln(' Inserting ', i, ' into avg5 ', avg5.Add(i): 0: 4);
  end;

  avg3.Reset;
  for i := 1 to 100000000 do
    avg3.Add(i);
  writeln('100''000''000 insertions ', avg3.Value: 0: 4);

  Readln;
end.


func avg(xs) {
    var acc = 0.0
    var c = 0
    for x in xs {
        c += 1
        acc += x
    }
    acc / c
}

func sma(p) {
    var s = []
    x => {
        if s.Length() >= p {
            s.RemoveAt(0)
        }
        s.Insert(s.Length(), x)
        avg(s)
    };
}

var nums = Iterator.Concat(1.0..5.0, 5.0^-1.0..1.0)
var sma3 = sma(3)
var sma5 = sma(5)

for n in nums {
    print("\(n)\t(sma3) \(sma3(n))\t(sma5) \(sma5(n))")
}


pragma.enable("accumulator")
def makeMovingAverage(period) {
    def values := ([null] * period).diverge()
    var index := 0
    var count := 0

    def insert(v) {
        values[index] := v
        index := (index + 1) %% period
        count += 1
    }

    /** Returns the simple moving average of the inputs so far, or null if there
        have been no inputs. */
    def average() {
        if (count > 0) {
            return accum 0 for x :notNull in values { _ + x } / count.min(period)
        }
    }

    return [insert, average]
}


(lib 'tree) ;; queues operations

(define (make-sma p)
	(define Q (queue (gensym)))
	(lambda (item)
		(q-push Q item)
		(when (> (queue-length Q) p) (q-pop Q))
		(// (for/sum ((x (queue->list Q))) x)  (queue-length Q))))


import system'routines;
import system'collections;
import extensions;

class SMA
{
    object thePeriod;
    object theList;

    constructor new(period)
    {
        thePeriod := period;
        theList :=new List();
    }

    append(n)
    {
        theList.append(n);

        var count := theList.Length;
        count =>
            0 { ^0.0r }
            : {
                if (count > thePeriod)
                {
                    theList.removeAt:0;

                    count := thePeriod
                };

                var sum := theList.summarize(Real.new());

                ^ sum / count
            }
    }
}

public program()
{
    var SMA3 := SMA.new:3;
    var SMA5 := SMA.new:5;

    for (int i := 1, i <= 5, i += 1) {
        console.printPaddingRight(30, "sma3 + ", i, " = ", SMA3.append:i);
        console.printLine("sma5 + ", i, " = ", SMA5.append:i)
    };

    for (int i := 5, i >= 1, i -= 1) {
        console.printPaddingRight(30, "sma3 + ", i, " = ", SMA3.append:i);
        console.printLine("sma5 + ", i, " = ", SMA5.append:i)
    };

    console.readChar()
}


$ cat simple-moving-avg.exs
#!/usr/bin/env elixir

defmodule Math do
  def average([]), do: nil
  def average(enum) do
    Enum.sum(enum) / length(enum)
  end
end

defmodule SMA do

  def sma(l, p \\ 10) do
    IO.puts("\nSimple moving average(period=#{p}):")
    Enum.chunk(l, p, 1)
    |> Enum.map(&(%{"input": &1, "avg": Float.round(Math.average(&1), 3)}))
  end

  defmacro gen_func(p) do
    quote do
      fn l -> SMA.sma(l, unquote(p)) end
    end
  end

  def read_numeric_input do
    IO.stream(:stdio, :line)
    |> Enum.map(&(String.split(&1, ~r{\s+})))
    |> List.flatten()
    |> Enum.reject(&(is_nil(&1) || String.length(&1) == 0))
    |> Enum.map(&(Integer.parse(&1) |> elem(0)))
  end

  def run do
    sma_func_10 = gen_func(10)
    sma_func_15 = gen_func(15)
    numbers = read_numeric_input
    sma_func_10.(numbers) |> IO.inspect
    sma_func_15.(numbers) |> IO.inspect
  end
end

SMA.run


main() ->
    SMA3 = sma(3),
    SMA5 = sma(5),
    Ns = [1, 2, 3, 4, 5, 5, 4, 3, 2, 1],
    lists:foreach(
      fun (N) ->
              io:format("Added ~b, sma(3) -> ~f, sma(5) -> ~f~n",[N,next(SMA3,N),next(SMA5,N)])
      end, Ns),
    stop(SMA3),
    stop(SMA5).

sma(W) ->
    {sma,spawn(?MODULE,loop,[W,[]])}.

loop(Window, Numbers) ->
    receive
        {_Pid, stop} ->
            ok;
        {Pid, N} when is_number(N) ->
            case length(Numbers) < Window of
                true ->
                    Next = Numbers++[N];
                false ->
                    Next = tl(Numbers)++[N]
            end,
            Pid ! {average, lists:sum(Next)/length(Next)},
            loop(Window,Next);
        _ ->
            ok
    end.

stop({sma,Pid}) ->
    Pid ! {self(),stop},
    ok.

next({sma,Pid},N) ->
    Pid ! {self(), N},
    receive
        {average, Ave} ->
            Ave
    end.


>n=1000; m=100; x=random(1,n);
>x10=fold(x,ones(1,m)/m);
>x10=fftfold(x,ones(1,m)/m)[m:n]; // more efficient


let sma period f (list:float list) =
    let sma_aux queue v =
        let q = Seq.truncate period (v :: queue)
        Seq.average q, Seq.toList q
    List.fold (fun s v ->
        let avg,state = sma_aux s v
        f avg
        state) [] list

printf "sma3: "
[ 1.;2.;3.;4.;5.;5.;4.;3.;2.;1.] |> sma 3 (printf "%.2f ")
printf "\nsma5: "
[ 1.;2.;3.;4.;5.;5.;4.;3.;2.;1.] |> sma 5 (printf "%.2f ")
printfn ""


USING: kernel interpolate io locals math.statistics prettyprint
random sequences ;
IN: rosetta-code.simple-moving-avg

:: I ( P -- quot )
    V{ } clone :> v!
    [ v swap suffix! P short tail* v! ] ;

: sma-add ( quot n -- quot' ) swap tuck call( x x -- x ) ;

: sma-query ( quot -- avg v ) first concat dup mean swap ;

: simple-moving-average-demo ( -- )
    5 I 10 <iota> [
        over sma-query unparse
        [I After ${2} numbers Sequence is ${0} Mean is ${1}I] nl
        100 random sma-add
    ] each drop ;

MAIN: simple-moving-average-demo


class MovingAverage
{
  Int period
  Int[] stream

  new make (Int period)
  {
    this.period = period
    stream = [,]
  }

  // add number to end of stream and remove numbers from start if
  // stream is larger than period
  public Void addNumber (Int number)
  {
    stream.add (number)
    while (stream.size > period)
    {
      stream.removeAt (0)
    }
  }

  // compute average of numbers in stream
  public Float average ()
  {
    if (stream.isEmpty)
      return 0.0f
    else
      1.0f * (Int)(stream.reduce(0, |a,b| { (Int) a + b })) / stream.size
  }
}

class Main
{
  public static Void main ()
  { // test by adding random numbers and printing average after each number
    av := MovingAverage (5)

    10.times |i|
    {
      echo ("After $i numbers list is ${av.stream} average is ${av.average}")
      av.addNumber (Int.random(0..100))
    }
  }
}