Babbage problem: Difference between revisions

(Added XPL0 example.)
(188 intermediate revisions by 44 users not shown)
Line 11:
 
 
;Task
{{task heading}}
 
The task is to find out if Babbage had the right answer — and to do so, as far as your language allows it, in code that Babbage himself would have been able to read and understand.
Line 19:
 
 
{{task heading|;Motivation}}
 
The aim of the task is to write a program that is sufficiently clear and well-documented for such a person to be able to read it and be confident that it does indeed solve the specified problem.
Line 25:
 
=={{header|11l}}==
<langsyntaxhighlight lang="11l">V n = 1
L n ^ 2 % 1000000 != 269696
n++
print(n)</langsyntaxhighlight>
 
=={{header|360 Assembly}}==
An assembler program always seems a bit tricky for non system engineer because it deals directly with the operating system and with the hardware instructions. Here we have a 32-bit computer with 16 32-bit registers. The caller (the operating system to keep it simple) is calling you giving your location address stored in register-15 and has stored in register-14 his return address. To save each program context, register-13 points to a 18 word save area. Do not spend time in understanding the context saving and restoring in the prologue and epilogue part of the program. What you have to know, “360” architecture uses 32-bit signed binary arithmetic, so here the maximum integer value is 2^31-1 (2147483647). Therefore the solution must be less than 2147483647. The multiplication and the division use a pair of registers; coding “MR 4,2” means multiply register-5 by register-2 and place result in the (register-4,register-5) pair; the same way “DR 4,2” means divide the (register-4,register-5) pair by register-2 and place the quotient in register-5 and the reminder in register-4. We use in the below program this intermediate 64-bit integers to find a solution with a value up to 2^31-1 even when we have to compute the square of this value.
<langsyntaxhighlight lang="360asm">
* Find the lowest positive integer whose square ends in 269696
* The logic of the assembler program is simple :
Line 65:
BUFFER DC CL80'Solution is: i=............ (i*i=............)'
END BABBAGE end of the control section
</syntaxhighlight>
</lang>
{{out}}
<pre>
Solution is: i= 25264 (i*i= 638269696)
</pre>
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits <br> or android 64 bits with application Termux }}
<syntaxhighlight lang AArch64 Assembly>
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program babbage64.s */
 
/************************************/
/* Constantes */
/************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
 
/*********************************/
/* Initialized data */
/*********************************/
.data
szMessResult: .asciz "Result = "
szMessStart: .asciz "Program 64 bits start.\n"
szCarriageReturn: .asciz "\n"
 
 
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
sZoneConv: .skip 24 // conversion buffer
 
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: // entry of program
ldr x0,qAdrszMessStart
bl affichageMess
ldr x4,qNbStart // start number = 269696
mov x5,#0 // counter multiply
ldr x2,qNbMult // value multiply = 1 000 000
mov x6,x4
1:
mov x0,x6
bl squareRoot // compute square root
mul x1,x0,x0 // compute square
umulh x3,x0,x0
cmp x3,#0 // overflow ?
bne 100f // yes -> end
cmp x1,x6 // perfect square
bne 2f // no -> loop
ldr x1,qAdrsZoneConv
bl conversion10
mov x0,#3 // string number to display
ldr x1,qAdrszMessResult
ldr x2,qAdrsZoneConv // insert conversion in message
ldr x3,qAdrszCarriageReturn
bl displayStrings // display message
b 100f // end
2:
add x5,x5,#1 // increment counter
mul x3,x5,x2 // multiply by 1 000 000
add x6,x3,x4 // add start number
b 1b
100: // standard end of the program
mov x0, #0 // return code
mov x8,EXIT
svc #0 // perform the system call
qAdrszCarriageReturn: .quad szCarriageReturn
qNbStart: .quad 269696
qNbMult: .quad 1000000
qAdrsZoneConv: .quad sZoneConv
qAdrszMessResult: .quad szMessResult
qAdrszMessStart: .quad szMessStart
/***************************************************/
/* Compute integer square root by Héron méthode */
/***************************************************/
/* r0 number */
/* r0 return root */
squareRoot:
stp x1,lr,[sp,-16]! // save registres
stp x2,x3,[sp,-16]! // save registres
cmp x0,#0 //
beq 100f
cmp x0,#4 // if < 4 return 1
mov x1,1
csel x0,x1,x0,lo
blo 100f
lsr x1,x0,#1 // division by 2 -> divisor
1:
mov x3,x1 // save previous result
udiv x2,x0,x1 // divide number by previous result
add x1,x1,x2 // add quotient to previous result
lsr x1,x1,#1 // division by 2
cmp x1,x3 // compare result and previous result
blo 1b // loop if result is smaller then previous result
mov x0,x3 // else return previous result
100:
ldp x2,x3,[sp],16 // restaur registres
ldp x1,lr,[sp],16 // restaur registres
ret
/***************************************************/
/* display multi strings */
/* new version 24/05/2023 */
/***************************************************/
/* x0 contains number strings address */
/* x1 address string1 */
/* x2 address string2 */
/* x3 address string3 */
/* x4 address string4 */
/* x5 address string5 */
/* x6 address string5 */
/* x7 address string6 */
displayStrings: // INFO: displayStrings
stp x8,lr,[sp,-16]! // save registers
stp x2,fp,[sp,-16]! // save registers
add fp,sp,#32 // save paraméters address (4 registers saved * 8 bytes)
mov x8,x0 // save strings number
cmp x8,#0 // 0 string -> end
ble 100f
mov x0,x1 // string 1
bl affichageMess
cmp x8,#1 // number > 1
ble 100f
mov x0,x2
bl affichageMess
cmp x8,#2
ble 100f
mov x0,x3
bl affichageMess
cmp x8,#3
ble 100f
mov x0,x4
bl affichageMess
cmp x8,#4
ble 100f
mov x0,x5
bl affichageMess
cmp x8,#5
ble 100f
mov x0,x6
bl affichageMess
cmp x8,#6
ble 100f
mov x0,x7
bl affichageMess
100:
ldp x2,fp,[sp],16 // restaur registers
ldp x8,lr,[sp],16 // restaur registers
ret
 
/***************************************************/
/* ROUTINES INCLUDE */
/***************************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeARM64.inc"
 
</syntaxhighlight>
{{Out}}
<pre>
Program 64 bits start.
Result = 25264
</pre>
 
=={{header|Ada}}==
 
<langsyntaxhighlight Adalang="ada">-- The program is written in the programming language Ada. The name "Ada"
-- has been chosen in honour of your friend,
-- Augusta Ada King-Noel, Countess of Lovelace (née Byron).
Line 126 ⟶ 289:
-- Ada.Text_IO.Put_Line(...) prints this string, for humans to read.
-- I did already run the program, and it did print out 25264.
end Babbage_Problem;</langsyntaxhighlight>
 
=={{header|Aime}}==
<langsyntaxhighlight lang="aime">integer i;
 
i = sqrt(269696);
Line 136 ⟶ 299:
}
 
o_(i, "\n");</langsyntaxhighlight>
 
=={{header|ALGOL 68}}==
As with other samples, we use "simple" forms such as "a := a + 1" instead of "a +:= 1".
<langsyntaxhighlight lang="algol68">COMMENT text between pairs of words 'comment' in capitals are
for the human reader's information and are ignored by the machine
COMMENT
Line 171 ⟶ 334:
COMMENT print displays the values of its parameters
COMMENT
print( ( v, " when squared is: ", v * v, newline ) )</langsyntaxhighlight>
{{out}}
<pre>
+25264 when squared is: +638269696
</pre>
 
=={{header|Amazing Hopper}}==
<syntaxhighlight lang="c">
#include <basico.h>
 
algoritmo
decimales '0'
número = 0, i=10
ciclo:
iterar grupo( número+=2, \
#( (número^2) % 1000000 != 269696 ), ; )
imprimir ("The smallest number whose square ends in 269696 is: ",\
número,\
"\nIt's square is: ", #(número ^ 2), NL )
i--, jnz(ciclo)
terminar
</syntaxhighlight>
{{out}}
<pre>
The smallest number whose square ends in 269696 is: 25264
It's square is: 638269696
The smallest number whose square ends in 269696 is: 99736
It's square is: 9947269696
The smallest number whose square ends in 269696 is: 150264
It's square is: 22579269696
The smallest number whose square ends in 269696 is: 224736
It's square is: 50506269696
The smallest number whose square ends in 269696 is: 275264
It's square is: 75770269696
The smallest number whose square ends in 269696 is: 349736
It's square is: 122315269696
The smallest number whose square ends in 269696 is: 400264
It's square is: 160211269696
The smallest number whose square ends in 269696 is: 474736
It's square is: 225374269696
The smallest number whose square ends in 269696 is: 525264
It's square is: 275902269696
The smallest number whose square ends in 269696 is: 599736
It's square is: 359683269696
The smallest number whose square ends in 269696 is: 650264
It's square is: 422843269696
</pre>
<p>Comentarios "in spanish":</p>
<p>
Documentación:</p>
<p>Establece que se trabajará con números sin decimales:</p>
"decimales(0)" (A)
La variable que tendrá el número cuyo cuadrado finaliza
con los dígitos 269696. Se inicializa con valor 0:
 
"número" (B)
 
La variable que controlará 11 iteraciones del proceso
principal. Se inicializa con 10, y se decrementará hasta
llegar a 0, de acuerdo a lo descrito en 1.4, 1.5 y 1.6:
 
"i" (C)
 
Esto permitirá encontrar 11 números que cumplan con lo
buscado.
 
-------------------------------------------------------------
 
Establece una etiqueta de salto, donde la ejecución del
programa saltará si se cumple una condición, que será
explicada en 1.4 y 1.5:
"CICLO:" (1.1)
Una macro que iterará el proceso principal donde por cada
incremento de "número" evaluará si los últimos dígitos del
cuadrado de "número" son los dígitos buscados por el señor
Babbage:
"iterar grupo" (1.2)
 
Explicación del proceso descrito en 1.2:
 
número+=2 (1.2.1) : incrementará el valor de la
variable "número" de 2 en 2.
número^2 (1.2.2) : cuadrado de "número".
% : resto módulo, resto de la división.
1000000 : esto permite obtener el resto de la
división de tamaño 6 dígitos.
Si el resultado de "(número^2)%1000000" es igual a
269696, entonces, "número" es el número buscado.
Una macro que dispondrá los mensajes y los resultados de
1.2.1 y 1.2.2, los que serán mostrados en pantalla:
 
"IMPRIMIR" (1.3)
 
Dispone el valor de la variable "i" para ser evaluada por
"JNZ", y luego la decrementará en 1:
"i--" (1.4)
 
Evalúa: si la variable no es cero, entonces saltará a la
posición del programa señalada en 1.1;
 
"JNZ(CICLO)" (1.5)
 
de lo contrario, si "i" es cero, entonces continuará con
el resto del programa, que será "terminar" la ejecución del
algoritmo:
"TERMINAR" (1.6)
 
Comentarios:
JNZ : significa Jump if Non-Zero.
 
#() : macro que permite resolver expresiones infijas en
tiempo de compilación.
 
</p>
 
=={{header|APL}}==
===⍳===
If at all possible, I would sit down at a terminal <i>with</i> Babbage and invite him to experiment with the various functions used in the program.
<langsyntaxhighlight lang="apl"> ⍝ 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:
Line 188 ⟶ 474:
SMALLESTWHERE←{1↑⍒⍵}
⍝ We can now ask the computer for the answer:
SMALLESTWHERE (SQUAREOF N) ENDSIN 269696</langsyntaxhighlight>
{{out}}
<pre>25264</pre>
===⍣===
<syntaxhighlight lang=apl>
⍝ s = 520 + 2 ... + 2 ⍣ <= power
⍝ s × s = n × 1000000 + 269696 | <= remainder
 
2+⍣{269696=1000000|⍺×⍺}520
=={{header|AppleScript}}==
</syntaxhighlight>
 
{{out}}
<pre>
25264
</pre>
 
====Documentation====
<pre>
Answer: n
Yes│
┌── remainder = 269696 ? ──┤
│ │
│ Power No│
│ (⍣) │
│ ▽
n ← n + 2 ◁─────────────────── n ← 520
 
Flow Created with Monodraw
</pre>
 
=={{header|AppleScript}}==
===Functional===
AppleScript's number types are at their limits here, but we can just get to the first Babbage number, after 638 integer root tests on suffixed numbers:
 
<langsyntaxhighlight AppleScriptlang="applescript">-- BABBAGE ------------------------------------------- BABBAGE ------------------------
 
-- babbage :: Int -> [Int]
on babbage(intTests)
 
script test
on toSquare(x)
(x1000000 * 1000000x) + 269696
end toSquare
Line 213 ⟶ 528:
script toRoot
on |λ|(x)
((x1000000 * 1000000x) + 269696) ^ (1 / 2)
end |λ|
end script
Line 221 ⟶ 536:
end babbage
 
 
-- TEST ----------------------------------------------------------------------
--------------------------- TEST -------------------------
on run
-- Try 1000 candidates
unlines(map(curry(intercalate)'s |λ|(" -> "), babbage(1000)))
--> "2.5264E+4 -> 6.38269696E+8"
Line 231 ⟶ 547:
 
 
-- GENERIC FUNCTIONS -------------------------------------- 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]
Line 259 ⟶ 563:
return lst
end enumFromTo
 
 
-- filter :: (a -> Bool) -> [a] -> [a]
Line 272 ⟶ 577:
end tell
end filter
 
 
-- hasIntRoot :: Int -> Bool
Line 279 ⟶ 585:
end hasIntRoot
 
 
-- intercalate :: Text -> [Text] -> Text
on-- intercalate(strText, lstText):: String -> [String] -> String
on intercalate(sep)
set {dlm, my text item delimiters} to {my text item delimiters, strText}
script
set strJoined to lstText as text
set my text item delimiterson to dlm|λ|(xs)
set {dlm, my text item delimiters} to ¬
return strJoined
{my text item delimiters, sep}
set s to xs as text
set my text item delimiters to dlm
s
end |λ|
end script
end intercalate
 
 
-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
-- The list obtained by applying f
-- to each element of xs.
tell mReturn(f)
set lng to length of xs
Line 298 ⟶ 613:
end tell
end map
 
 
-- min :: Ord a => a -> a -> a
Line 307 ⟶ 623:
end if
end min
 
 
-- Lift 2nd class handler function into 1st class script wrapper
Line 319 ⟶ 636:
end if
end mReturn
 
 
-- unlines :: [String] -> String
on unlines(xs)
-- A single string formed by the intercalation
intercalate(linefeed, xs)
-- of a list of strings with the newline character.
set {dlm, my text item delimiters} to ¬
{my text item delimiters, linefeed}
set s to xs as text
set my text item delimiters to dlm
s
end unlines
 
 
-- zip :: [a] -> [b] -> [(a, b)]
Line 333 ⟶ 658:
end repeat
return lst
end zip</langsyntaxhighlight>
{{Out}}
<pre>2.5264E+4 -> 6.38269696E+8</pre>
----
 
===Simple===
 
As far as I can make out, this follows the same approach as above. For some curious technical reason, although the maximum positive value for an AppleScript <tt>integer</tt> object is 536870911, on my current system, the script returns 'testNumber' values much higher than that as integers too!
 
<syntaxhighlight lang="applescript">on babbage(endDigits)
-- Set up an incrementor to the amount in front of the given end digits.
if (endDigits's class is text) then
set increment to 10 ^ (count endDigits) div 1
else
set increment to 10
repeat until (increment > endDigits)
set increment to increment * 10
end repeat
end if
-- I postulate that if no square ending with the given digits is found with less than
-- twice that many digits, then no such square exists; but I can't be certain. :)
set limit to increment * (increment div 10)
-- In any case, AppleScript's precision limit is 1.0E+15.
if (limit > 1.0E+15) then return missing value
-- Test successive values ending with the digits until one is found
-- to have an integer square root or the limit is exceeded.
set testNumber to endDigits div 1
set squareRoot to testNumber ^ 0.5
repeat until ((squareRoot mod 1 = 0) or (testNumber > limit))
set testNumber to testNumber + increment
set squareRoot to testNumber ^ 0.5
end repeat
if (testNumber > limit) then return missing value -- No such square.
return {squareRoot as integer, testNumber} -- {integer, square ending with the digits}
end babbage
 
return {babbage(269696), babbage("00609")}</syntaxhighlight>
 
{{output}}
<syntaxhighlight lang="applescript">{{25264, 638269696}, {3647, 13300609}}</syntaxhighlight>
 
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
<lang ARM Assembly>
 
/* ARM assembly Raspberry PI */
Line 522 ⟶ 885:
bx lr @ leave function
iMagicNumber: .int 0xCCCCCCCD
</syntaxhighlight>
</lang>
{{out}}
<pre>Result = 25264</pre>
 
=={{header|Arturo}}==
 
<syntaxhighlight lang="rebol">n: new 0
while [269696 <> (n^2) % 1000000]
-> inc 'n
 
print n</syntaxhighlight>
 
{{out}}
 
<pre>25264</pre>
 
=={{header|Asymptote}}==
<syntaxhighlight lang="Asymptote">int n = 519;
 
while (269696 != (n^2) % 1000000) {
++n;
}
 
write("The smallest number whose square ends in 269696 is: ", n);
write("It's square is ", n*n);</syntaxhighlight>
{{out}}
<pre>The smallest number whose square ends in 269696 is 25264
Its square is 638269696</pre>
 
=={{header|AutoHotkey}}==
<syntaxhighlight lang="autokotkey">
<lang AutoKotkey>
; Give n an initial value
n = 519
Line 539 ⟶ 927:
; Display n as value
msgbox, %n%
</syntaxhighlight>
</lang>
{{out}}
<pre>25264</pre>
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# 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.
Line 568 ⟶ 956:
exit(0)
} # end of program
</syntaxhighlight>
</lang>
<p>Output:</p>
<pre>
Line 578 ⟶ 966:
==={{header|Applesoft BASIC}}===
This is an implementation based on the alternative solution for the BBC BASIC. We know that 269696 is not a perfect square, so we can safely start with N=1269696 and add 1000000 each time N is not a perfect square. The ST function returns the remainder of the difference between N and the square of the integer part of the root (R). There are a couple of quirks in AppleSoft BASIC, the largest integer is 32767, but the largest number not displayed on scientific notation is 999999999, which explains the strange IF statement in line <code>170</code>.
<langsyntaxhighlight lang="basic">
100 :
110 REM BABBAGE PROBLEM
Line 596 ⟶ 984:
FOR VALUES SMALLER"; CHR$(13);
"THAN 999999999."
</syntaxhighlight>
</lang>
{{out}}
<pre>]RUN
Line 604 ⟶ 992:
==={{header|Commodore BASIC}}===
Based on the C language implementation
<langsyntaxhighlight lang="basic">10 rem This code is an implementation of Babbage Problem
20 num = 100 : rem We can safely start at 100
30 s = num*num
Line 615 ⟶ 1,003:
100 print:print "The smallest number whose square ends in 269696 is:"
110 print num;"....";num;"squared = ";s
120 end</langsyntaxhighlight>
 
==={{header|BASIC256}}===
<syntaxhighlight lang="basic256">
<lang BASIC256>
#This code is an implementation of Babbage Problem
number = 2
Line 626 ⟶ 1,014:
PRINT "The smallest number whose square ends in 269696 is: "; number
PRINT "It's square is "; number*number
</syntaxhighlight>
</lang>
 
==={{header|BBC BASIC}}===
Clarity has been preferred over all other considerations. The line <tt>LET n = n + 1</tt>, for instance, would more naturally be written <tt>n% += 1</tt>, using an integer variable and a less verbose assignment syntax; but this optimization did not seem to justify the additional explanations Professor Babbage would probably need to understand it.
<langsyntaxhighlight lang="bbcbasic">REM Statements beginning 'REM' are explanatory remarks: the machine will ignore them.
 
REM We shall test positive integers from 1 upwards until we find one whose square ends in 269,696.
Line 646 ⟶ 1,034:
PRINT "The smallest number whose square ends in 269696 is" n
 
PRINT "Its square is" n^2</langsyntaxhighlight>
{{out}}
<pre>The smallest number whose square ends in 269696 is 25264
Line 654 ⟶ 1,042:
{{trans|PowerShell}}
The algorithm given in the alternative PowerShell implementation may be substantially more efficient, depending on how long <tt>SQR</tt> takes, and I think could well be more comprehensible to Babbage.
<langsyntaxhighlight lang="bbcbasic">REM Lines that begin 'REM' are explanatory remarks addressed to the human reader.
 
REM The machine will ignore them.
Line 678 ⟶ 1,066:
PRINT "The smallest number whose square ends in 269696 is" root
 
PRINT "Its square is" n</langsyntaxhighlight>
{{out}}
Identical to the first BBC BASIC version.
 
==={{header|Chipmunk Basic}}===
{{works with|Chipmunk Basic|3.6.4}}
{{trans|BASIC256}}
<syntaxhighlight lang="qbasic">10 cls
20 number = 2
30 while ((number^2) mod 1000000) <> 269696
40 number = number+2
50 wend
60 print "The smallest number whose square ends in 269696 is: " number
70 print "It's square is " number*number
80 end</syntaxhighlight>
 
==={{header|GW-BASIC}}===
{{works with|MSX_BASIC}}
{{works with|PC-BASIC|any}}
{{trans|Applesoft BASIC}}
<syntaxhighlight lang="qbasic">10 CLS
20 DEF FN ST(A#) = N# - INT (A#) * INT (A#)
30 N# = 269696!
40 N# = N# + 1000000!
50 R# = SQR(N#)
60 IF FN ST(R#) <> 0 AND N# < 999999999# THEN GOTO 40
70 IF N# > 999999999# THEN GOTO 110
80 PRINT "The smallest number whose square ends in 269696 is:";R#
90 PRINT "It's square is:";N#
100 END
110 PRINT "There is no solution for values smaller than 999999999."</syntaxhighlight>
{{out}}
<pre>The smallest number whose square ends in 269696 is: 25264
It's square is: 638269696</pre>
 
==={{header|MSX Basic}}===
The [[#GW-BASIC|GW-BASIC]] solution works without any changes.
 
==={{header|QBasic}}===
{{works with|QBasic}}
{{works with|QuickBasic}}
{{trans|Yabasic}}
<syntaxhighlight lang="qbasic">number = 524
DO
NUMBER = number + 2
LOOP UNTIL ((number ^ 2) MOD 1000000) = 269696
PRINT "The smallest number whose square ends in 269696 is: "; number
PRINT "It's square is "; number ^ 2
END</syntaxhighlight>
 
==={{header|True BASIC}}===
{{trans|Yabasic}}
<syntaxhighlight lang="qbasic">LET number = 2
DO
LET number = number + 2
LOOP UNTIL REMAINDER((number ^ 2), 1000000) = 269696
PRINT "The smallest number whose square ends in 269696 is: "; number
PRINT "It's square is "; number ^ 2
END</syntaxhighlight>
==={{header|uBasic/4tH}}===
{{trans|FreeBASIC}}
<syntaxhighlight lang="text">n = 524 ' first number to try
Do
' square the number
' look at the last 6 digits, if they match print the number
Until (n*n) % 1000000 = 269696
' increase the number with 2, number end on a 6
n = n + 2
Until n = 99736
' if the number = 99736 then we haved found a smaller number, so stop
' look at the last 6 digits, if they match print the number
Until (n*n) % 1000000 = 269696
' increase the number with 8, number ends on a 4
n = n + 8
Loop
If n = 99736 Then
Print "No smaller number was found"
Else
' we found a smaller number, print the number and its square
Print "The number = ";n ; " and its square = "; n*n
EndIf</syntaxhighlight>
 
==={{header|IS-BASIC}}===
<langsyntaxhighlight ISlang="is-BASICbasic">100 PROGRAM "Babbage.bas"
110 LET N=2
120 DO
Line 689 ⟶ 1,157:
140 LOOP UNTIL MOD(N*N,1000000)=269696
150 PRINT "The smallest number whose square ends in 269696 is:";N
160 PRINT "It's square is";N^2</langsyntaxhighlight>
Alternative method:
<langsyntaxhighlight ISlang="is-BASICbasic">100 PROGRAM "Babbage.bas"
110 LET N=269696
120 DO
Line 698 ⟶ 1,166:
150 LOOP UNTIL R=INT(R)
160 PRINT "The smallest number whose square ends in 269696 is:";R
170 PRINT "It's square is";N</langsyntaxhighlight>
 
==={{header|XBasic}}===
{{works with|Windows XBasic}}
<syntaxhighlight lang="qbasic">PROGRAM "Babbage problem"
VERSION "0.0000"
 
DECLARE FUNCTION Entry ()
 
FUNCTION Entry ()
number = 524
DO
number = number + 2
LOOP UNTIL ((number ** 2) MOD 1000000) = 269696
PRINT "The smallest number whose square ends in 269696 is: "; number
PRINT "It's square is "; number ** 2
PRINT "It's square is "; number * number
END FUNCTION
END PROGRAM</syntaxhighlight>
 
=={{header|Batch File}}==
<langsyntaxhighlight lang="dos">
:: This line is only required to increase the readability of the output by hiding the lines of code being executed
@echo off
Line 724 ⟶ 1,210:
echo %number% * %number% = %numbersquared%
pause>nul
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 734 ⟶ 1,220:
Befunge is not an easily readable language, but with a basic understanding of the syntax, I think an intelligent person should be able to follow the logic of the code below.
 
<langsyntaxhighlight lang="befunge"> 1+ ::* "d"::** % "V8":** -! #v_ > > > > >
v
increment n n*n modulo 1000000 equal to 269696? v if false, loop to right
Line 751 ⟶ 1,237:
"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</langsyntaxhighlight>
 
{{out}}
Line 758 ⟶ 1,244:
 
=={{header|Bracmat}}==
<syntaxhighlight lang="bracmat">
<lang Bracmat>
(
500:?number {A child knows that 269696 is larger than 500*500,
Line 786 ⟶ 1,272:
)
)
</syntaxhighlight>
</lang>
 
{{out}}
Line 792 ⟶ 1,278:
 
=={{header|C}}==
<syntaxhighlight lang="c">
<lang C>
// This code is the implementation of Babbage Problem
 
Line 818 ⟶ 1,304:
return 0 ;
}
</syntaxhighlight>
</lang>
 
{{out}}
<pre>The smallest number whose square ends in 269696 is 25264</pre>
 
=={{header|C sharp|C#}}==
 
<langsyntaxhighlight lang="csharp">namespace Babbage_Problem
{
class iterateNumbers
Line 859 ⟶ 1,345:
}
}
}}</langsyntaxhighlight>
{{out}}
<pre>The smallest integer whose square ends in 269,696 is 25264
Line 865 ⟶ 1,351:
 
=={{header|C++}}==
<langsyntaxhighlight Cpplang="cpp">#include <iostream>
 
int main( ) {
Line 873 ⟶ 1,359:
std::cout << "The square of " << current << " is " << (current * current) << " !\n" ;
return 0 ;
}</langsyntaxhighlight>
 
{{out}}
Line 880 ⟶ 1,366:
 
=={{header|Caché ObjectScript}}==
<langsyntaxhighlight Cachélang="caché ObjectScriptobjectscript">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
Line 897 ⟶ 1,383:
}
quit ; exit routine</langsyntaxhighlight>
 
{{out}}<pre>SAMPLES>do ^BABBAGE
Line 904 ⟶ 1,390:
 
=={{header|Clojure}}==
<langsyntaxhighlight lang="clojure">; 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
Line 914 ⟶ 1,400:
; (We're exploiting Clojure's laziness here; (range) with no parameters returns
; an infinite series.)
(first (filter babbage? (range)))</langsyntaxhighlight>
{{out}}
<pre>25264</pre>
 
=={{header|COBOL}}==
<langsyntaxhighlight cobollang="cobolfree"> 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.
DATA DIVISION.
WORKING-STORAGE SECTION.
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
Line 930 ⟶ 1,417:
* 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.
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.</lang>
 
END PROGRAM BABBAGE-PROGRAM.</syntaxhighlight>
{{out}}
<pre>25264</pre>
 
=={{header|Common Lisp}}==
<syntaxhighlight lang="lisp">
<lang Lisp>
(defun babbage-test (n)
"A generic function for any ending of a number"
Line 959 ⟶ 1,449:
((= (mod (* i i) d) n) i) )))
</syntaxhighlight>
</lang>
 
{{out}}
Line 967 ⟶ 1,457:
I use [https://franz.com/downloads/clp/survey Allegro CL 10.1]
 
<langsyntaxhighlight lang="lisp">
; Project : Babbage problem
 
Line 981 ⟶ 1,471:
(format t "~a" "Its square is: ")
(write (* n n))
</syntaxhighlight>
</lang>
Output:
<pre>
Line 992 ⟶ 1,482:
With some improvements of Common Lisp [https://lisp-lang.org/style-guide/ style]
 
<langsyntaxhighlight lang="lisp">;; * The package definition
(defpackage :babbage
(:use :common-lisp))
Line 1,009 ⟶ 1,499:
(format t "The smallest number whose square ends in ~D is: ~D~%" end num)
(format t "Its square is: ~D~%" square)
(return num)))</langsyntaxhighlight>
 
{{out}}
<pre>ABBAGE> (babbage 269696)
The smallest number whose square ends in 269696 is: 25264
Its square is: 638269696</pre>
25264</pre>
 
=={{header|Component Pascal}}==
{{Works with|BlackBox Component Builder}}
<langsyntaxhighlight lang="oberon2">
MODULE BabbageProblem;
IMPORT StdLog;
Line 1,035 ⟶ 1,524:
 
END BabbageProblem.
</syntaxhighlight>
</lang>
<pre>Execute: ^Q BabbageProble.Do</pre>
{{out}}
Line 1,041 ⟶ 1,530:
25264
</pre>
 
=={{header|Craft Basic}}==
<syntaxhighlight lang="basic">print "calculating..."
 
let n = 2
 
do
 
let n = n + 2
wait
 
loopuntil (n ^ 2) % 1000000 = 269696
 
print "The smallest number whose square ends in 269696 is: ", n
print "It's square is ", n * n</syntaxhighlight>
{{out| Output}}<pre>calculating...
The smallest number whose square ends in 269696 is: 25264
It's square is 638269696</pre>
 
=={{header|D}}==
<langsyntaxhighlight Dlang="d">// 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.
Line 1,065 ⟶ 1,572:
// display output
writefln("%d * %d = %d", k, k, k*k);
}</langsyntaxhighlight>
 
{{out}}
Line 1,072 ⟶ 1,579:
 
=={{header|Dafny}}==
<langsyntaxhighlight lang="dafny">
// Helper function for mask: does the actual computation.
function method mask_(v:int,m:int):int
Line 1,135 ⟶ 1,642:
print smallest, "\n";
}
</syntaxhighlight>
</lang>
 
=={{header|Dart}}==
<langsyntaxhighlight lang="dart">
 
Line 1,148 ⟶ 1,655:
print('$x');
}
</syntaxhighlight>
</lang>
=={{header|Delphi}}==
See [https://rosettacode.org/wiki/Babbage_problem#Pascal Pascal].
 
=={{header|Dyalect}}==
 
Simple approach:
<lang dyalect>for i in 2..Integer.max() {
 
<syntaxhighlight lang="dyalect">var i = 0
while i * i % 1000000 != 269696 {
i += 1
}
 
print("\(i) is the smallest number that ends with 269696")</syntaxhighlight>
 
Using a non-strict range and iteration:
 
<syntaxhighlight lang="dyalect">for i in 2..Integer.Max {
if i * i % 1000000 == 269696 {
print("\(i) is the smallest number that ends with 269696")
break
}
}</langsyntaxhighlight>
 
{{out}}
Line 1,164 ⟶ 1,684:
 
=={{header|EasyLang}}==
<syntaxhighlight lang="text">while n * n mod 1000000 <> 269696
n += 1
.
print n</langsyntaxhighlight>
 
=={{header|EDSAC order code}}==
Line 1,178 ⟶ 1,698:
This of course is the principle that Babbage used in his Difference Engine.
 
One inconvenience of EDSAC was that a programmer who wanted to define a 35-bit constant by means of pseudo-orders could specify the low and high 17-bit words, but not the middle bit ("sandwich digit"), which had to be 0. So a constant such as 1000000, with middle bit 1, could not be defined by pseudo-orders. In this case the programmer could usually define the negative of the desired constant and work with that instead, as illustrated below.
One inconvenience of EDSAC was that a programmer who wanted a 35-bit constant
 
could specify the low and high 17-bit words, but not the middle bit ("sandwich digit"),
A more convenient way to define 35-bit constants was to use a library subroutine to read them from the input tape in decimal format, with no worries about the sandwich digit. This is demonstrated in the EDSAC solution to the linear congruential generator.
which had to be 0.
 
So a constant such as 1000000, with middle bit 1, could not be defined.
<syntaxhighlight lang="edsac">
In this case the programmer could usually define the negative of the desired constant
and work with that instead, as illustrated below.
<lang edsac>
[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.
Line 1,194 ⟶ 1,712:
@&*SOLUTION!TO!BABBAGE!PROBLEM@&#
..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]
Line 1,200 ⟶ 1,718:
GKA3FT25@H29@VFT4DA3@TFH30@S6@T1FV4DU4DAFG26@
TFTFO5FA4DF4FS4FL4FT4DA1FS3@G9@EFSFO31@E20@J995FJF!F
[Main routine. Load after subroutine P6.
Must be at an even address because each double
Line 1,206 ⟶ 1,724:
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]
[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]
Line 1,227 ⟶ 1,748:
RD [right shift]
T4#@ [(1st difference for n^2) := -64]
 
[Start of loop]
[22] TF [clear acc]
Line 1,247 ⟶ 1,768:
S8#@ [test for acc = 0 by subtracting 8]
E22@ [loop back if residue > 269696]
 
[Here with the solution]
TF [clear acc]
Line 1,258 ⟶ 1,779:
O16@ [print null, to flush printer buffer]
ZF [stop]
E17Z [define relativeentry start addresspoint]
PF [enter with acc = 0]
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,269 ⟶ 1,790:
=={{header|Elena}}==
{{trans|Smalltalk}}
ELENA 46.x :
<langsyntaxhighlight lang="elena">import extensions;
import system'math;
Line 1,277 ⟶ 1,798:
var n := 1;
until(n.sqr().mod:(1000000) == 269696)
{
n += 1
Line 1,283 ⟶ 1,804:
console.printLine(n)
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,290 ⟶ 1,811:
 
=={{header|Elixir}}==
<langsyntaxhighlight lang="elixir">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)</langsyntaxhighlight>
or
<langsyntaxhighlight lang="elixir">Stream.iterate(2, &(&1+2))
|> Enum.find(&rem(&1*&1, 1000000) == 269696)
|> IO.puts</langsyntaxhighlight>
 
{{out}}
Line 1,307 ⟶ 1,828:
 
=={{header|Erlang}}==
<syntaxhighlight lang="erlang">
<lang Erlang>
-module(solution1).
-export([main/0]).
Line 1,319 ⟶ 1,840:
main()->
babbage(4,4).
</syntaxhighlight>
</lang>
 
=={{header|F_Sharp|F#}}==
<syntaxhighlight lang="f#">
<lang f#>
let mutable n=1
while(((n*n)%( 1000000 ))<> 269696) do
n<-n+1
printf"%i"n
</syntaxhighlight>
</lang>
 
Same as above, sans mutable state.
<langsyntaxhighlight lang="fsharp">
Seq.initInfinite id
|> Seq.skipWhile (fun n->(n*n % 1000000) <> 269696)
|> Seq.head |> printfn "%d"
</syntaxhighlight>
</lang>
 
Not the same as above, see discussion page!!!!
<syntaxhighlight lang="fsharp">
let rec fN g=seq{yield g; yield g+2; yield! fN(g+10)}
printfn "%d" (fN 524|>Seq.find(fun n->n*n%1000000=269696))
</syntaxhighlight>
{{out}}
256264
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">! 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).
Line 1,469 ⟶ 1,998:
! Putting the entire program together, it looks like this:
 
! 518 99,736 2 <range> [ sq 1,000,000 mod 269,696 = ] find . drop</langsyntaxhighlight>
{{out}}
<pre>
Line 1,477 ⟶ 2,006:
=={{header|Forth}}==
Can a Forth program be made readable to a novice, without getting into what a stack is? We shall see.
<langsyntaxhighlight lang="forth">( First we set out the steps the computer will use to solve the problem )
 
: BABBAGE
Line 1,493 ⟶ 2,022:
( Now we ask the machine to carry out these instructions )
 
BABBAGE</langsyntaxhighlight>
{{out}}
<pre>25264</pre>
Line 1,507 ⟶ 2,036:
Sincerely, <br>
John Backus - September 1956 <br>
<langsyntaxhighlight lang="fortran"> DO 3 N=1,99736
IF(MODF(N*N,1000000)-269696)3,4,3
3 CONTINUE
Line 1,513 ⟶ 2,042:
5 FORMAT(I6)
STOP
</syntaxhighlight>
</lang>
{{out}}
<pre>25264</pre>
Line 1,523 ⟶ 2,052:
===Modern Fortran===
{{trans|F#}}
<langsyntaxhighlight lang="fortran">
program babbage
implicit none
Line 1,534 ⟶ 2,063:
print*, n
end program babbage
</syntaxhighlight>
</lang>
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">' version 25-10-2016
' compile with: fbc -s console
 
Line 1,578 ⟶ 2,107:
Print : Print "hit any key to end program"
Sleep
End</langsyntaxhighlight>
{{out}}
<pre>The number = 25,264 and its square = 638,269,696</pre>
 
=={{header|Frink}}==
<langsyntaxhighlight lang="frink">// This is a solver for the Rosetta Code problem "Babbage problem"
// https://rosettacode.org/wiki/Babbage_problem
 
Line 1,596 ⟶ 2,125:
// This prints i and i²
println[i + "² = " + i²]
exit[] // This terminates the program. if a solution is found.
}
i = i + 1
}</langsyntaxhighlight>
 
{{out}}
Line 1,605 ⟶ 2,134:
 
=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">window 1
<lang qbasic>include "ConsoleWindow"
 
dim as long i
 
for i = 1 to 1000000
Line 1,613 ⟶ 2,142:
next
print @"The smallest number whose square ends in 269696 is "; i
print @"Its square is "; i ^ 2</lang>
 
HandleEvents</syntaxhighlight>
 
{{out}}
<pre>The smallest number whose square ends in 269696 is 25264
Line 1,621 ⟶ 2,153:
=={{header|Fōrmulæ}}==
 
In [{{FormulaeEntry|page=https://wiki.formulae.org/?script=examples/Babbage_problem this] page you can see the solution of this task.}}
 
'''Solution'''
 
[[File:Fōrmulæ - Babbage problem 01.png]]
Fōrmulæ programs are not textual, visualization/edition of programs is done showing/manipulating structures but not text ([http://wiki.formulae.org/Editing_F%C5%8Drmul%C3%A6_expressions more info]). Moreover, there can be multiple visual representations of the same program. Even though it is possible to have textual representation &mdash;i.e. XML, JSON&mdash; they are intended for transportation effects more than visualization and edition.
 
[[File:Fōrmulæ - Babbage problem 02.png]]
The option to show Fōrmulæ programs and their results is showing images. Unfortunately images cannot be uploaded in Rosetta Code.
 
=={{header|Gambas}}==
'''[https://gambas-playground.proko.eu/?gist=08eafccbe3febb79ec62301ca84e3662 Click this link to run this code]'''
<langsyntaxhighlight lang="gambas">Public Sub Main()
Dim iNum As Long
 
Line 1,638 ⟶ 2,172:
Print "The lowest number squared that ends in '269696' is " & Str(iNum)
 
End</langsyntaxhighlight>
Output:
<pre>
Line 1,645 ⟶ 2,179:
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 1,664 ⟶ 2,198:
}
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,671 ⟶ 2,205:
 
=={{header|Groovy}}==
<syntaxhighlight lang="groovy">
<lang Groovy>
int n=104; ///starting point
while( (n**2)%1000000 != 269696 )
Line 1,678 ⟶ 2,212:
}
println n+"^2== "+n**2 ;
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,686 ⟶ 2,220:
=={{header|Haskell}}==
====head====
<langsyntaxhighlight Haskelllang="haskell">--Calculate squares, testing for the last 6 digits
findBabbageNumber :: Integer
findBabbageNumber =
Line 1,697 ⟶ 2,231:
(++)
(show <$> ([id, (^ 2)] <*> [findBabbageNumber]))
[" ^ 2 equals", " !"])</langsyntaxhighlight>
{{out}}
<pre>25264 ^ 2 equals 638269696 !</pre>
Line 1,704 ⟶ 2,238:
Or, if we incline to the ''nullius in verba'' approach, are not yet convinced that there really are any such numbers below 100,000, and look uncertainly at '''head''' – a partial function which simply fails on empty lists, we could import the Safe module, and use the '''headMay''' alternative, which, more cautiously and experimentally, returns a Maybe value:
 
<langsyntaxhighlight lang="haskell">import Data.List (intercalate)
import Data.Maybe (maybe)
import Safe (headMay)
Line 1,721 ⟶ 2,255:
(intercalate " ^ 2 -> " .
fmap show . (<*>) [floor . sqrt . fromInteger, id] . pure)
(maybeBabbage upperLimit)</langsyntaxhighlight>
{{Out}}
<pre>25264 ^ 2 -> 638269696</pre>
Line 1,731 ⟶ 2,265:
We can then harvest as many as we need from an infinite stream of babbages, Mr Babbage.
 
<langsyntaxhighlight lang="haskell">import Data.List (intercalate)
 
 
--------------------- BABBAGE PROBLEM --------------------
 
babbagePairs :: [[Integer]]
babbagePairs =
[0, 1000000 ..] >>= -- Drawing from a succession of N * 10^6
>>= \x -> -- Drawing from a succession of N * 10^6
\x ->
let y = (x + 269696) -- The next number ending in 269696,
r = (sqrtroot y . fromIntegral) y -- its square root,
i = floor r -- and the integer part of that root.
in [ [i, y] -- Root and square harvested together,
| r == fromIntegral i ] -- only if that root is an integer.
]
 
root :: Integer -> Double
root = sqrt. fromIntegral
 
--------------------------- TEST -------------------------
main :: IO ()
main = mapM_ (putStrLn . arrowed) $ take 10 babbagePairs
main = do
 
let arrowed = intercalate " ^ 2 -> " . fmap show
arrowed :: [Integer] -> String
mapM_ putStrLn (arrowed <$> take 10 babbagePairs)</lang>
arrowed = intercalate " ^ 2 -> " . fmap show</syntaxhighlight>
{{Out}}
<pre>25264 ^ 2 -> 638269696
Line 1,760 ⟶ 2,302:
599736 ^ 2 -> 359683269696</pre>
 
A quick glance at these results suggests that Mr Babbage would have done well to inspectconsider more closely the way in which the final digits of the square constrain the final digits of the root.
 
We can get to the solution almost immediately, after only a handful of tests, well within the reach of pencil and paper, if we discern that the root itself, to produce the 269692 suffix in its square, must have one of only four different final digit sequences: (0264, 5264, 4736, or 9736).
 
With a machine, this approach can industrialise the babbage harvest, yielding thousands of pairs in less than a second:
<syntaxhighlight lang="haskell">---------------------- BABBAGE PAIRS ---------------------
<lang haskell>import Data.List (intercalate)
 
babbagePairs :: [[(Integer], Integer)]
babbagePairs =
[0, 10000 ..] >>=
>>= \x ->
(<*>) [(:(,) <*> return . (^ 2)]) . ((+ x) <$> [0264, 5264, 9736, 4736]+) >>=
\ <$> [a264, b]5264, ->9736, 4736]
[ [a, b])
|>>= \((269696a, ==b) . flip rem 1000000) b ]->
[ (a, b)
| ((269696 ==) . flip rem 1000000) b
]
 
--------------------------- TEST -------------------------
main :: IO ()
main =
mapM_
mapM_ putStrLn (intercalate " ^ 2 -> " . fmap show <$> take 4000 babbagePairs)</lang>
putStrLn
( (\(a, b) -> show a <> " ^2 -> " <> show b)
<$> take 2000 babbagePairs
)</syntaxhighlight>
 
=={{header|Hoon}}==
<syntaxhighlight lang="hoon">
:: This is Hoon, a language for writing human-legible
:: instructions to a machine called Urbit.
::
:: A pair of non-alphanumeric symbols is called a rune.
:: Each rune begins a unique expression.
::
:: An expression can be an instruction to the machine,
:: or a description of essential information.
:: Each rune specifies a different expression.
:: Each expression can contain other expressions.
:: (In practice, every expression contains
:: at least one of the expressions that follow it.)
::
:: :: tells the machine to ignore the rest of a line
:: these lines allow commentary for a human reader
:: like the question this program will answer:
::
:: What is the smallest positive integer whose
:: square ends in the digits 269,696?
::
:: The program of instructions for solving this,
:: uninterrupted by commentary, is:
::
:: :- %say
:: |= [*]
:: :- %noun
:: ^- @ud
:: =/ n 0
:: |-
:: ?: =(269.696 (mod (pow n 2) 1.000.000))
:: n
:: %= $
:: n +(n)
:: ==
::
:: The first three significant lines describe
:: two things: our program's input, and its structure.
:: They specify the program requires no input.
:: Otherwise, we can ignore them for our purposes.
::
:: ^- describes the desired output of our program.
:: @ud signifies an unknown positive integer.
:: The output will be a positive integer.
:: The output will be our answer.
:- %say
|= [*]
:- %noun
^- @ud
::
:: =/ assigns a value to a name, for future reference.
:: Here we assign value 0 to "n", as in algebra.
=/ n 0
::
:: |- begins a recursive, iterative process.
:: It might not end until a condition is met.
|-
::
:: ?: does two things.
:: First, it returns a Boolean true-or-false answer
:: to the question that follows.
:: Second, it evaluates one of two expressions
:: branching on whether the answer is true or false.
::
:: Here we rephrase our question for the machine:
:: "Is 269,696 equal to the remainder of
:: n^2 divided by 1,000,000?"
?: =(269.696 (mod (pow n 2) 1.000.000))
::
:: If so, we get our answer: the current value of n.
n
::
:: If not, we run the whole program again,
:: but this time n is replaced by (n+1).
:: n will be incremented by 1 until our
:: ?: question has the answer "true",
:: upon which it will return n.
:: If n is 0, it will now be 1.
:: If n is 25,263, it will now be 25,264 which,
:: as this program shows, is the smallest positive
:: integer whose square ends in the digits 269,696.
::
:: %= runs the whole program again, but
:: with the listed names, on the left, assigned
:: new values on the right. It could take an
:: arbitrary number of children, so unlike the
:: other runes here which take a fixed number,
:: this expression must end in a == rune, which
:: just brings the expression to an end.
%= $
n +(n)
==
</syntaxhighlight>
 
=={{header|J}}==
Line 1,786 ⟶ 2,431:
So let's break the implementation into some named pieces and present enough detail that a mathematician can verify that the result is both consistent and reasonable:
 
<langsyntaxhighlight Jlang="j"> square=: ^&2
modulo1e6=: 1000000&|
trythese=: i. 1000000 NB. first million nonnegative integers
which=: I. NB. position of true values
which 269696=modulo1e6 square trythese NB. right to left <-
25264 99736 150264 224736 275264 349736 400264 474736 525264 599736 650264 724736 775264 849736 900264 974736</langsyntaxhighlight>
 
The smallest of these values is 25264.
Line 1,798 ⟶ 2,443:
==== Alternatively, inspired by the APL example that makes the sentence sound natural ====
 
<syntaxhighlight lang="j">
<lang J>
NB. In the interactive environment.
NB. First here, Mr Babbage, we'll make the computer's words more meaningful to an english speaker.
Line 1,830 ⟶ 2,475:
25264
 
</syntaxhighlight>
</lang>
 
=={{header|Java}}==
<langsyntaxhighlight lang="java">public class Test {
 
public static void main(String[] args) {
Line 1,852 ⟶ 2,497:
System.out.println(n);
}
}</langsyntaxhighlight>
<pre>25264</pre>
 
=={{header|JavaScript}}==
====Iteration====
<langsyntaxhighlight lang="javascript">// Every line starting with a double slash will be ignored by the processing machine,
// just like these two.
//
Line 1,875 ⟶ 2,520:
// need to send it to the monitoring device (named console).
console.log(n)
</syntaxhighlight>
</lang>
====Functional composition====
 
Line 1,881 ⟶ 2,526:
 
{{works with|ES6}}
<langsyntaxhighlight JavaScriptlang="javascript">(() => {
'use strict';
 
Line 1,991 ⟶ 2,636:
// MAIN ---
return main();
})();</langsyntaxhighlight>
{{Out}}
<pre>25264^2 -> 638269696
Line 2,019 ⟶ 2,664:
=={{header|Julia}}==
 
<langsyntaxhighlight lang="julia">
"""
babbage(x::Integer)
Returns the smallest positive integer whose square ends in `x`
"""
function babbage(x::Integer)
i = big(0) # start with 0 and increase by 1 until target reaached
i = big(0)
d = 10^ndigits(x) # smallest power of 10 greater than x
d = floor(log10(x)) + 1
while (i ^* 2i) % 10 ^ d != x
i += 1 # try next squre of numbers 0, 1, 2, ...
i += 1
end
return i
end
 
</lang>
</syntaxhighlight>
 
{{out}}
Line 2,039 ⟶ 2,690:
=={{header|Kotlin}}==
 
<langsyntaxhighlight lang="scala">fun main(args: Array<String>) {
var number = 520L
var square = 520 * 520L
Line 2,052 ⟶ 2,703:
square = number * number
}
}</langsyntaxhighlight>
 
{{out}}
Line 2,058 ⟶ 2,709:
The smallest number is 25264 whose square is 638269696
</pre>
 
=={{header|Lambdatalk}}==
<syntaxhighlight lang="scheme">
{S.map {lambda {:n}
{if {= {% {* :n :n} 1000000} 269696}
then :n{sup 2} = {* :n :n}
else}}
{S.serie 2 100000 2}}
-> 25264^2 = 638269696 99736^2 = 9947269696
...
</syntaxhighlight>
 
=={{header|Liberty BASIC}}==
Now Mr. Babbage -- May I call you Charlie? No. OK -- we'll first start with 'n' equal to zero, then multiply it by itself to square it. If the last six digits of the result are not 269696, we'll add one to 'n' then go back and square it again. On our modern computer it should only take a moment to find the answer...
<syntaxhighlight lang="lb">
<lang lb>
[start]
if right$(str$(n*n),6)="269696" then
Line 2,069 ⟶ 2,731:
if n<100000 then n=n+1: goto [start]
print "Program complete."
</syntaxhighlight>
</lang>
Eureka! We found it! --
<syntaxhighlight lang="sh">
<lang sh>
n = 25,264 n*n = 638,269,696
n = 99,736 n*n = 9,947,269,696
Program complete.
</syntaxhighlight>
</lang>
Now my question for you, Sir, is how did you know that the square of ANY number would end in 269696??
Oh, and by the way, 99,736 is an answer too.
 
=={{header|Limbo}}==
<langsyntaxhighlight Limbolang="limbo">implement Babbage;
 
include "sys.m";
Line 2,101 ⟶ 2,763:
print("%d", current);
}
</syntaxhighlight>
</lang>
 
=={{header|Lua}}==
{{trans|D}}
<langsyntaxhighlight lang="lua">-- get smallest number <= sqrt(269696)
k = math.floor(math.sqrt(269696))
 
Line 2,118 ⟶ 2,780:
end
 
io.write(string.format("%d * %d = %d\n", k, k, k * k))</langsyntaxhighlight>
 
=={{header|M2000 Interpreter}}==
<langsyntaxhighlight M2000lang="m2000 Interpreterinterpreter">Def Long k=1000000, T=269696, n
n=Sqrt(269696)
For n=n to k {
Line 2,127 ⟶ 2,789:
}
Report format$("The smallest number whose square ends in {0} is {1}, Its square is {2}", T, n, n**2)
</syntaxhighlight>
</lang>
{{out}}
<pre>The smallest number whose square ends in 269696 is 25264, Its square is 638269696</pre>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
Solving up to his guess would show that there is indeed a smaller integer with that property.
<langsyntaxhighlight Mathematicalang="mathematica"> Solve[Mod[x^2, 10^6] == 269696 && 0 <= x <= 99736, x, Integers]</langsyntaxhighlight>
{{out}}
<pre>{{x->25264},{x->99736}}</pre>
 
 
=={{header|MATLAB}}==
<syntaxhighlight lang="MATLAB">
clear all;close all;clc;
BabbageProblem();
 
function BabbageProblem
% Initialize x to 524, as the square root of 269696 is approximately 519.something
x = 524;
% Loop until the square of x modulo 1000000 equals 269696
while mod(x^2, 1000000) ~= 269696
% If the last digit of x is 4, increment x by 2
% Otherwise, increment x by 8
if mod(x, 10) == 4
x = x + 2;
else
x = x + 8;
end
end
% Display the result
fprintf('The smallest positive integer whose square ends in 269696 = %d\n', x);
end
</syntaxhighlight>
{{out}}
<pre>
The smallest positive integer whose square ends in 269696 = 25264
</pre>
 
=={{header|Maxima}}==
<syntaxhighlight lang="maxima">
/* Function that returns a list of digits given a nonnegative integer */
decompose(num) := block([digits, remainder],
digits: [],
while num > 0 do
(remainder: mod(num, 10),
digits: cons(remainder, digits),
num: floor(num/10)),
digits
)$
 
/* Test case */
block(babbage_param:269696,i:isqrt(babbage_param)+1,cache_babbage:decompose(babbage_param),
while rest(decompose(i^2),(length(decompose(i^2))-6))#cache_babbage do i:i+2,
i);
</syntaxhighlight>
{{out}}
<pre>
25264
</pre>
 
=={{header|MAXScript}}==
<langsyntaxhighlight lang="maxscript">-- MAXScript : Babbage problem : N.H.
posInt = 1
while posInt < 1000000 do
Line 2,145 ⟶ 2,861:
Print "The smallest number whose square ends in 269696 is " + ((posInt) as string)
Print "Its square is " + (((pow posInt 2) as integer) as string)
</syntaxhighlight>
</lang>
{{out}}
Output to MAXScript Listener:
Line 2,154 ⟶ 2,870:
=={{header|Microsoft Small Basic}}==
{{trans|VBscript}}
<langsyntaxhighlight lang="smallbasic">' Babbage problem
' The quote (') means a comment
' The equals sign (=) means assign
Line 2,178 ⟶ 2,894:
TextWindow.WriteLine("Its square is " + (n*n) + ".")
 
' End of Program. </langsyntaxhighlight>
{{out}}
<pre>
Line 2,186 ⟶ 2,902:
 
=={{header|MiniScript}}==
<langsyntaxhighlight MiniScriptlang="miniscript">// Lines that start with "//" are "comments" that are ignored
// by the computer. We use them to explain the code.
 
Line 2,207 ⟶ 2,923:
 
// The first such number we find is our answer.
print k + "^2 = " + k^2</langsyntaxhighlight>
 
{{out}}
Line 2,213 ⟶ 2,929:
 
=={{header|Modula-2}}==
<langsyntaxhighlight lang="modula2">MODULE BabbageProblem;
FROM FormatString IMPORT FormatString;
FROM RealMath IMPORT sqrt;
Line 2,239 ⟶ 2,955:
 
ReadChar
END BabbageProblem.</langsyntaxhighlight>
 
=={{header|Nanoquery}}==
<langsyntaxhighlight Nanoquerylang="nanoquery">n = 0
 
while not (n ^ 2 % 1000000) = 269696
Line 2,248 ⟶ 2,964:
end
 
println n</langsyntaxhighlight>
 
{{out}}
Line 2,255 ⟶ 2,971:
=={{header|NetRexx}}==
{{trans|Groovy}}
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
options replace format comments java crossref symbols nobinary utf8
numeric digits 5000 -- set up numeric precision
Line 2,289 ⟶ 3,005:
 
return n -- end the function and return the result
</syntaxhighlight>
</lang>
{{out}}
<pre> 25,264² == 638,269,696</pre>
 
=={{header|NewLisp}}==
<syntaxhighlight lang="newlisp">
<lang NewLisp>
;;; Start by assigning n the integer square root of 269696
;;; minus 1 to be even
Line 2,303 ⟶ 3,019:
;;; Show the result and its square
(println n "^2 = " (* n n))
</syntaxhighlight>
</lang>
{{output}}
<pre>
Line 2,310 ⟶ 3,026:
 
=={{header|Nim}}==
<syntaxhighlight lang="nim">
<lang Nim>
var n : int = 0
while n*n mod 1_000_000 != 269_696:
inc(n)
echo n
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,321 ⟶ 3,037:
 
=={{header|Objeck}}==
<langsyntaxhighlight lang="objeck">class Babbage {
function : Main(args : String[]) ~ Nil {
cur := 0;
Line 2,333 ⟶ 3,049:
}
}
</syntaxhighlight>
</lang>
 
{{output}}
Line 2,341 ⟶ 3,057:
 
=={{header|OCaml}}==
<syntaxhighlight lang="ocaml">
<lang OCaml>
let rec f a=
if (a*a) mod 1000000 != 269696
Line 2,349 ⟶ 3,065:
let a= f 1 in
Printf.printf "smallest positive integer whose square ends in the digits 269696 is %d\n" a
</syntaxhighlight>
</lang>
 
=={{header|Ol}}==
<langsyntaxhighlight lang="scheme">
(print
(let loop ((i 2))
Line 2,358 ⟶ 3,074:
i
(loop (+ i 1)))))
</syntaxhighlight>
</lang>
{{out}}
<pre>25264</pre>
 
=={{header|PARI/GP}}==
<langsyntaxhighlight lang="parigp">m=269696;
k=1000000;
{for(n=1,99736,
Line 2,370 ⟶ 3,086:
return(n) \\ If so, return this number and STOP.
)
)}</langsyntaxhighlight>
 
=={{header|Pascal}}==
<langsyntaxhighlight lang="pascal">program BabbageProblem;
(* Anything bracketed off like this is an explanatory comment. *)
var n : longint; (* The VARiable n can hold a 'long', ie large, INTeger. *)
Line 2,383 ⟶ 3,099:
(* 'n * n' means 'n times n'; 'mod' means 'modulo'. *)
write(n)
end.</langsyntaxhighlight>
{{out}}
<pre>25264</pre>
 
=={{header|Perl}}==
===Naive===
<lang Perl>#!/usr/bin/perl
<syntaxhighlight lang="perl">#!/usr/bin/perl
use strict ;
use warnings ;
Line 2,396 ⟶ 3,113:
$current++ ;
}
print "The square of $current is " . ($current * $current) . " !\n" ;</langsyntaxhighlight>
 
{{out}}
<pre>The square of 25264 is 638269696 !</pre>
 
===More efficient and well documented===
 
I am pretty sure that comments and efficient code would be appreciated by Mr. Babbage.
 
<syntaxhighlight lang="perl"># Dear Mr. Babbage,
# in the following code, $number is the variable to contain the number
# we're looking for. '%' is the modulo division operator and '!='
# means "not equal to".
 
# We start to search with 518, because no smaller number can be even
# squared to 269696. We also increment the number always by 2, as no
# odd number can be part of the solution. We do this, because
# computational power - even in 2022 - does not grow on trees.
# And even if it did, we have less of them than you did.
 
my $number = 518;
while ( ($number ** 2) % 1000000 != 269696 ) {
$number += 2 ;
}
print "The square of $number is " . ($number ** 2) . " !\n";</syntaxhighlight>
 
{{out}}
Line 2,404 ⟶ 3,145:
We can omit anything odd, as any odd number squared is obviously always odd.<br>
Mr Babbage might need the whole "i is a variable" thing explained, and that "?i" prints the value of i, nowt else springs to mind.
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>for i=2 to 99736 by 2 do
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
if remainder(i*i,1000000)=269696 then ?i exit end if
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">2</span> <span style="color: #008080;">to</span> <span style="color: #000000;">99736</span> <span style="color: #008080;">by</span> <span style="color: #000000;">2</span> <span style="color: #008080;">do</span>
end for</lang>
<span style="color: #008080;">if</span> <span style="color: #7060A8;">remainder</span><span style="color: #0000FF;">(</span><span style="color: #000000;">i</span><span style="color: #0000FF;">*</span><span style="color: #000000;">i</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1000000</span><span style="color: #0000FF;">)=</span><span style="color: #000000;">269696</span> <span style="color: #008080;">then</span> <span style="color: #0000FF;">?</span><span style="color: #000000;">i</span> <span style="color: #008080;">exit</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
25264
</pre>
===Proper method===
This might confuse poor old Mr Babbage and require much more explanation, but I like to think he'd be quietly impressed with the approach.<br>
Create a list of one-digit numbers whose square ends in 6, then use that list to create/filter
all two-digit numbers whose square ends in 96, and so on. <br>
For simplicity and with some poetic licence we start with {0} as the list of all zero-digit numbers that end in "" aka nothing specific.
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">procedure</span> <span style="color: #000000;">solve_babbage_problem</span><span style="color: #0000FF;">()</span> <span style="color: #000080;font-style:italic;">-- (so that return quits 3 loops)</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">cands</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">0</span><span style="color: #0000FF;">},</span> <span style="color: #000080;font-style:italic;">-- n-digit candidates (n initially 0)</span>
<span style="color: #000000;">nextc</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{}</span> <span style="color: #000080;font-style:italic;">-- n+1-digit candidates, aka next ""</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">p10</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000080;font-style:italic;">-- power of 10 for adding prefixes</span>
<span style="color: #000000;">r10</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">10</span><span style="color: #0000FF;">,</span> <span style="color: #000080;font-style:italic;">-- power of 10 for getting remainder</span>
<span style="color: #000000;">cc</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span> <span style="color: #000080;font-style:italic;">-- count of calculations</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">digits</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">6</span> <span style="color: #008080;">do</span> <span style="color: #000080;font-style:italic;">-- aka 1..length("269696")</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">prefix</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span> <span style="color: #008080;">to</span> <span style="color: #000000;">9</span><span style="color: #0000FF;">*</span><span style="color: #000000;">p10</span> <span style="color: #008080;">by</span> <span style="color: #000000;">p10</span> <span style="color: #008080;">do</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">cand</span> <span style="color: #008080;">in</span> <span style="color: #7060A8;">sq_add</span><span style="color: #0000FF;">(</span><span style="color: #000000;">prefix</span><span style="color: #0000FF;">,</span><span style="color: #000000;">cands</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
<span style="color: #004080;">atom</span> <span style="color: #000000;">square</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">cand</span><span style="color: #0000FF;">*</span><span style="color: #000000;">cand</span>
<span style="color: #000000;">cc</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
<span style="color: #008080;">if</span> <span style="color: #7060A8;">remainder</span><span style="color: #0000FF;">(</span><span style="color: #000000;">square</span><span style="color: #0000FF;">,</span><span style="color: #000000;">r10</span><span style="color: #0000FF;">)</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">remainder</span><span style="color: #0000FF;">(</span><span style="color: #000000;">269696</span><span style="color: #0000FF;">,</span><span style="color: #000000;">r10</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">digits</span><span style="color: #0000FF;">=</span><span style="color: #000000;">6</span> <span style="color: #008080;">then</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Solution: %d (%d calcs)\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">cand</span><span style="color: #0000FF;">,</span><span style="color: #000000;">cc</span><span style="color: #0000FF;">})</span>
<span style="color: #008080;">return</span> <span style="color: #000080;font-style:italic;">-- leave solve_babbage_problem()</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #000000;">nextc</span> <span style="color: #0000FF;">&=</span> <span style="color: #000000;">cand</span> <span style="color: #000080;font-style:italic;">-- add candidate for next iteration</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #0000FF;">{</span><span style="color: #000000;">cands</span><span style="color: #0000FF;">,</span><span style="color: #000000;">nextc</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">nextc</span><span style="color: #0000FF;">,{}}</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%d-digit candidates: %v\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">digits</span><span style="color: #0000FF;">,</span><span style="color: #000000;">cands</span><span style="color: #0000FF;">})</span>
<span style="color: #000000;">p10</span> <span style="color: #0000FF;">*=</span> <span style="color: #000000;">10</span>
<span style="color: #000000;">r10</span> <span style="color: #0000FF;">*=</span> <span style="color: #000000;">10</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
<span style="color: #000000;">solve_babbage_problem</span><span style="color: #0000FF;">()</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
1-digit candidates: {4,6}
2-digit candidates: {14,36,64,86}
3-digit candidates: {236,264,736,764}
4-digit candidates: {264,2236,2764,4736,5264,7236,7764,9736}
5-digit candidates: {264,24736,25264,49736,50264,74736,75264,99736}
Solution: 25264 (193 calcs)
</pre>
As you can see this would be significantly quicker (by hand) than adding 2 about 12,500 times, or even starting from 514 and only checking numbers that end in 4 or 6, still nearly 5,000 of 'em, whereas this is a mere 193 calculations/squares. Of course the answer we are looking for is the first/lowest 6-digit candidate found. Note a depth-first search finds at least 6 larger solutions before the lowest, whereas the breadth-first approach as used does not.
 
Should you replace "if digits=6 then" with "if remainder(cand2,1e6)=269696 then", which anyone performing this manually would find unmissable, then you get the answer in just 131 calculations (r10 is 1e5 when that triggers).
 
For reference and from a previous version, the full list of 6-digit candidates would be:
<pre>
6-digit candidates: {25264,99736,150264,224736,275264,349736,400264,474736,525264,599736,650264,724736,775264,849736,900264,974736}
</pre>
Notice that "0264" '''is''' a valid 4-digit candidate, and "00264" a valid 5-digit one, as proved by the presence of 400264 and 900264.
 
=={{header|PHP}}==
 
<langsyntaxhighlight PHPlang="php"><?php
 
for (
Line 2,422 ⟶ 3,219:
);
 
echo $i, ' * ', $i, ' = ', ($i * $i), PHP_EOL; // Print the result</langsyntaxhighlight>
 
{{out}}
<pre>25264 * 25264 = 638269696</pre>
 
=={{header|Picat}}==
===Iterative===
<syntaxhighlight lang="picat">main =>
N = 1,
while (N**2 mod 1000000 != 269696)
N := N + 1
end,
println(N).</syntaxhighlight>
 
{{out}}
<pre>25264</pre>
 
===Constraint modelling===
<syntaxhighlight lang="picat">import cp.
 
main =>
N*N mod 1000000 #= 269696, % ends with "269696"
N #> 0, % positive integer
solve($[min(N)],[N]), % minimize N
println(n=N).</syntaxhighlight>
 
{{out}}
<pre>25264</pre>
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">: (for N 99736 # Iterate N from 1 to 99736
(T (= 269696 (% (* N N) 1000000)) N) ) # Stop if remainder is 269696
-> 25264</langsyntaxhighlight>
 
=={{header|PILOT}}==
<langsyntaxhighlight lang="pilot">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.
Line 2,451 ⟶ 3,272:
Type:The smallest number whose square ends in 269696 is #n. Its square is #square.
Remark:The end.
End:</langsyntaxhighlight>
 
=={{header|Plain English}}==
<langsyntaxhighlight lang="plainenglish">To run:
Start up.
Put 1 into a number.
Line 2,464 ⟶ 3,285:
Write "The answer is " then the number on the console.
Wait for the escape key.
Shut down.</langsyntaxhighlight>
{{out}}
<pre>
The answer is 25264
</pre>
 
=={{header|PL/I}}==
<syntaxhighlight lang="pli">
/* 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;
</syntaxhighlight>
{{out}}
<pre>
The smallest number whose square ends in 269696 is 25264
The corresponding square is 638269696
</pre>
 
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
<lang PowerShell>
###########################################################################################
#
Line 2,517 ⟶ 3,371:
 
$integer
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 2,525 ⟶ 3,379:
{{works with|PowerShell|2}}
By looping through potential squares instead of potential square roots, we reduce the number of loops by a factor of 40.
<langsyntaxhighlight PowerShelllang="powershell"># Start with the smallest potential square number
$TestSquare = 269696
Line 2,548 ⟶ 3,402:
# Display the result and its square
$Root
$TestSquare</langsyntaxhighlight>
{{out}}
<pre>25264
Line 2,554 ⟶ 3,408:
 
=={{header|Processing}}==
<langsyntaxhighlight lang="java">// Lines that begin with two slashes, thus, are comments: they
// will be ignored by the machine.
 
Line 2,587 ⟶ 3,441:
// println is short for 'print line'
 
println(n);</langsyntaxhighlight>
{{out}}
<pre>25264</pre>
Line 2,593 ⟶ 3,447:
=={{header|Prolog}}==
Works with Swi-Prolog version 7+
<langsyntaxhighlight lang="prolog">:- use_module(library(clpfd)).
 
babbage_(B, B, Sq) :-
Line 2,605 ⟶ 3,459:
babbage :-
once(babbage_(1, Num, Square)),
format('lowest number is ~p which squared becomes ~p~n', [Num, Square]).</langsyntaxhighlight>
{{out}}
<pre>
1 ?- babbage.
lowest number is 25264 which squared becomes 638269696
true.
</pre>
===alternative===
with swi-prolog buildin between -> Output is the same
<syntaxhighlight lang="prolog">
babbage :-
Start is ceil(sqrt(269696)),
between(Start, inf, N),
Square is N * N,
Square mod 100 =:= 96, % speed up
Square mod 1000000 =:= 269696,!, % break after first true
format('lowest number is ~d which squared becomes ~d~n', [N, Square]).
</syntaxhighlight>
 
=={{header|PureBasic}}==
<langsyntaxhighlight PureBasiclang="purebasic">EnableExplicit
Macro putresult(n)
If OpenConsole("Babbage_problem")
Line 2,634 ⟶ 3,499:
For n = 2 To q Step 2
If (n*n) % #DIV = #GOAL : putresult(n) : Break : EndIf
Next</langsyntaxhighlight>
{{out}}
<pre>The smallest number whose square ends in 269696 is 25264</pre>
 
=={{header|Python}}==
<langsyntaxhighlight lang="python">
# Lines that start by # are a comments:
# they will be ignored by the machine
Line 2,651 ⟶ 3,516:
 
# n**2 -> n squared
# % -> 'modulo' or remainerremainder after division
# != -> not equal to
Line 2,657 ⟶ 3,522:
 
print(n) # prints n
</syntaxhighlight>
 
# shortShort version:
>>><syntaxhighlight [lang="python">print(next(x for x in range(30000) if pow(x*x), %2, 1000000) == 269696] [0]))</syntaxhighlight>
25264
</lang>
{{out}}
<pre>25264</pre>
Or, by chaining iterators, without multiplication or exponentiation:
<syntaxhighlight lang="python">from itertools import accumulate, count
 
print(*next(filter(lambda t: t[1] % 1000000 == 269696, enumerate(accumulate(count(1, 2)), 1))))</syntaxhighlight>
{{out}}
<pre>25264 638269696</pre>
 
Or, generating a non-finite stream of numbers which are the sum of 269696 and some integer multiple of one million, and also have an integer square root:
{{Works with|Python|3.7}}
<langsyntaxhighlight lang="python">'''Babbage problem'''
 
from math import (floor, sqrt)
Line 2,773 ⟶ 3,641:
# MAIN ---
if __name__ == '__main__':
main()</langsyntaxhighlight>
{{Out}}
<pre>Smallest positive integers whose squares end in the digits 269,696:
Line 2,791 ⟶ 3,659:
 
As a footnote on what Babbage might have managed with pencil and paper – applying the '''squaresWithSuffix(n)''' function to shorter suffixes (6, 96, 696 ...) enables us to explore the way in which the final digits of the integer root constrain and determine those of the perfect square. It quickly becomes apparent that Mr Babbage need only have considered roots ending in the digit sequences 264 or 736, a constraint which, had he deduced it with pencil and paper, would have allowed him to reach 25264 after testing the squares of only 24 other numbers.
 
=={{header|Quackery}}==
 
<syntaxhighlight lang="quackery">( . . . . . . . . . . . . . . . . . . )
( 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
( . . . . . . . . . . . . . . . . . . )</syntaxhighlight>
 
{{out}}
 
<pre>25264</pre>
 
=={{header|R}}==
<syntaxhighlight lang="r">
<lang R>
babbage_function=function(){
n=0
Line 2,802 ⟶ 3,732:
}
babbage_function()[length(babbage_function())]
</syntaxhighlight>
</lang>
{{out}}
<pre>25264</pre>
 
=={{header|Racket}}==
<langsyntaxhighlight lang="racket">;; Text from a semicolon to the end of a line is ignored
;; This lets the racket engine know it is running racket
#lang racket
Line 2,854 ⟶ 3,784:
(display (square-ends-in-269696? first-number-that-when-squared-ends-in-269696))
(newline)
;; that all seems satisfactory</langsyntaxhighlight>
 
{{out}}
Line 2,866 ⟶ 3,796:
(formerly Perl 6)
 
{{works with|Rakudo|2016.03}}
This could certainly be written more concisely. Extra verbiage is included to make the process more clear.
<syntaxhighlight lang="raku" perl6line># For all positivespositive integers from 1 to Infinity
for 1 .. Inf -> $integer {
Line 2,876 ⟶ 3,805:
# 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;
}</langsyntaxhighlight>
 
{{out}}
<pre>25264² equals 638269696</pre>
 
Alternatively,More theconcisely following(but just may be declarativeclear enough to allow Mr. Babbage to understand what's going on?):
<syntaxhighlight lang="raku" line>.say and exit if $_² % 1e6 == 269696 for ^∞;</syntaxhighlight>
 
{{out}}
<lang perl6>say $_ if ($_² % 1000000 == 269696) for 1..99736;</lang>
<pre>25264</pre>
 
Notice that `exit` ends the process itself instead of ending just the loop, as `last` would. `exit` would arguably be easier to understand for Babbage though, so it may better fill the task requirement.
{{out}}
<pre>
25264
99736
</pre>
 
=={{header|Red}}==
<langsyntaxhighlight Redlang="red">Red []
number: 510 ;; starting number
;; repeat, until the last condition in the block is true
Line 2,903 ⟶ 3,831:
]
?? number
</syntaxhighlight>
</lang>
{{out}}
<pre>number: 25264</pre>
Line 2,975 ⟶ 3,903:
 
===examine the right-most six digits of square===
<langsyntaxhighlight lang="rexx">/*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</langsyntaxhighlight>
{{out|output}}
<pre>
Line 2,986 ⟶ 3,914:
 
===examine remainder after dividing by one million===
<langsyntaxhighlight lang="rexx">/*REXX program finds the lowest (positive) integer whose square ends in 269,696. */
do j=2 by 2 /*start J at two, increment by two. */
if ((j * j) // 1000000) == 269696 then leave /*is square mod one million our target?*/
end /*◄── signifies the end of the DO loop.*/
/* [↑] // is division remainder.*/
say "The smallest integer whose square ends in 269,696 is: " j</langsyntaxhighlight>
{{out|output|text=&nbsp; is identical to the 1<sup>st</sup> REXX version.}} <br><br>
 
===examine only numbers ending in 4 or 6===
<langsyntaxhighlight lang="rexx">/*REXX program finds the lowest (positive) integer whose square ends in 269,696. */
/*─────────────────── we will only examine integers that are ending in four or six. */
do j=4 by 10 /*start J at four, increment by ten.*/
Line 3,005 ⟶ 3,933:
end /*◄── signifies the end of the DO loop.*/
/* [↑] * means multiplication. */
say "The smallest integer whose square ends in 269,696 is: " k</langsyntaxhighlight>
{{out|output|text=&nbsp; is identical to the 1<sup>st</sup> REXX version.}} <br><br>
 
===start with smallest possible number===
<langsyntaxhighlight lang="rexx">/*REXX ----------------------------------------------------------------
* The solution must actually be larger than sqrt(269696)=519.585
*--------------------------------------------------------------------*/
Line 3,021 ⟶ 3,949:
End
Say "The smallest integer whose square ends in 269696 is:" z
Say ' 'z'**2 =' z**2</langsyntaxhighlight>
{{out}}
<pre>The smallest integer whose square ends in 269696 is: 25264
Line 3,027 ⟶ 3,955:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
n = 0
while pow(n,2) % 1000000 != 269696
Line 3,035 ⟶ 3,963:
see "The smallest number whose square ends in 269696 is : " + n + nl
see "Its square is : " + pow(n,2)
</syntaxhighlight>
</lang>
Output:
<pre>
The smallest number whose square ends in 269696 is : 25264
Its square is : 638269696
</pre>
 
=={{header|RPL}}==
Whoever trying to make easy-to-understand RPL code faces 3 main roadblocks:
# data handling relies on a stack, even if variables can also be used
# syntax is postfixed - which makes sense with stack-based operations
# comments cannot be freely inserted within the code
Mr Babbage was a great mathematician and, having worked on the task, he had to know that the solution s is a multiple of 8, since
s^2 = n.10^6 + 269696 = 64 * (15625.n + 4214)
and that it is greater than the square root of 269696. A simple but efficient algorithm is then to test all multiples of 8 from 512, which is the multiple just below the square root of 269696, up to the solution. In the worst case, the loop would end at 99736..
 
But without some previous training, even a very clever man like Mr. Babbage would have some difficulty to decipher such an algorithm within the uncommented RPL code to solve the task:
≪ 512 '''DO''' 8 + '''UNTIL''' DUP n SQ 1E6 MOD 269696 == '''END''' ≫
 
To better answer the task, it is then needed to adopt a coding style closer to the one used by Mr. Babbage (and Mrs. Lovelace) to program the Analytic Engine (AE).
Such programs were actually tables, one line figuring one program step, the left columns (the 'Mill' = the CPU) describing the arithmetic operations to perform from registers to registers, called 'variables' and named v0..vn, represented by the columns on the right (the 'Store' = the RAM). Due to this syntax, it was not possible in the same instruction to use a variable both as an operand and a destination, i.e. <code>x = x + y </code> could not be directly coded.
 
Operations were restricted to <code>+-*/</code>. What seems today basic like <code>x^y</code> or <code>MOD(x)</code> was not wired in the AE. And don't even think about a function calculating the square root...
 
Branch instructions were not available : AE's human operator, in charge of initializing the variables and turning the crank (= both the CPU clock and the power supply), had also to analyze the results and react accordingly, thus assuming the responsibility of properly executing all the <code>IF..THEN..ELSE</code> and <code>DO..UNTIL</code> that algorithms would require.
 
The following program mimics Mr. Babbage's programming way, inspired by these [https://collection.sciencemuseumgroup.org.uk/documents/aa110000065%20on%20solving%20two%20simultaneous%20equations| notes on solving two simultaneous equations] kept by the Science Museum Group Collection.
After a short initialisation sequence affecting values to some column variables, the « Mill » calls 2 variables line after line, performs an arithmetic operation and put back the result in a specific column variable of the « Store ». Once the calculation sequence is completed, the AE operator shall take a decision, according to the value of column v4;
{{works with|Halcyon Calc|4.2.7}}
{| class="wikitable"
! Code for Mr. Babbage
! Comments for Rosetta Coders
|-
|
≪ 512 0 8 1000000 269696
'v0' 'v10' 'v11' 'v12' 'v13'
→STORE
'''DO'''
''Mill Store''
v0 v11 + 'v1' °END
v1 v10 + 'v0' °END
v0 v1 * 'v2' °END
v2 v12 / 'v3' °END
v3 v12 * 'v4' °END
v2 v4 - 'v3' °END
v3 v13 - 'v4' °END
'''UNTIL''' v4 IS°NIL END
PRINT v4
|
Store the starting values of n and constants
into each variable below
Let's start turning the crank
v1 = v0 + v11 = n + 8
v0 = v1 + 0 = n + 8 // the only way to copy a register into another
v2 = v0 x v1 = n^2
v3 = v2 % v12 = n^2 % 10000
v4 = v3 * v12 = (n^2 % 10000)*10000
v3 = v2 - v4 = n^2 mod 10000
v4 = v3 - v13 = (n^2 mod 10000) - 269696
Exit condition
Babbage's machine had a printer!
|}
Some words have been especially created to improve Babbage-readability: <code>→STORE</code> stores values in the appropriate variables, <code>IS°NIL</code> compares stack content to zero, <code>°END</code> actually stores stack content into the variable named just before; <code>Mill</code>, <code>Store</code> and <code>PRINT</code> do absolutely nothing and are actually one-word comments:
≪ 6 2 '''FOR''' n n ROLL SWAP STO -1 '''STEP''' ≫ '→STORE' STO
≪ 0 == ≫ 'IS°NIL' STO
≪ SWAP IP SWAP STO ≫ '°END' STO
≪ ≫ 'Mill' STO
≪ ≫ 'Store' STO
≪ ≫ 'PRINT' STO
{{out}}
<pre>
1: 25264
</pre>
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">n = 0
n = n + 2 until (n*n).modulo(1000000) == 269696
print n
</syntaxhighlight>
</lang>
 
=={{header|Run BASIC}}==
<langsyntaxhighlight lang="runbasic">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</langsyntaxhighlight>
<pre>The smallest number whose square ends in 269696 is 25264
Its square is 638269696
Line 3,061 ⟶ 4,060:
=={{header|Rust}}==
=== Imperative version ===
<langsyntaxhighlight lang="rust">fn main() {
let mut current = 0;
while (current * current) % 1_000_000 != 269_696 {
Line 3,070 ⟶ 4,069:
current
);
}</langsyntaxhighlight>
{{out}}
<pre>
Line 3,077 ⟶ 4,076:
 
=== Finding in infinite range ===
<langsyntaxhighlight lang="rust">fn main() {
if let Some(n) = (1..).find(|x| x * x % 1_000_000 == 269_696) {
println!("The smallest number whose square ends in 269696 is {}", n)
}
}</langsyntaxhighlight>
 
Which outputs the same thing as above.
 
=={{header|S-BASIC}}==
Because we have to use double-precision floating point to represent the required number of digits, and because the approach to calculating a double-precision n mod 1000000 to isolate the right-most six digits of the square is particularly inefficient, the program will take a long time to find the solution (but it will, eventually!)
<syntaxhighlight lang="BASIC">
$lines
 
$constant true = FFFFH
$constant false = 0
 
var n, sq, r = real.double
var done = integer
 
print "Finding smallest number whose square ends in 269696"
 
n = 520 rem - no smaller number has a square that large
done = false
 
rem - no need to search beyond the number Babbage already knew
while not done and n <= 99736.0 do
begin
sq = n * n
rem - compute sq mod 1000000 by repeated subtraction
r = sq
while r >= 1000000.0 do
r = r - 1000000.0
if r = 269696.0 then
begin
print using "The smallest number is ######"; n
print using "and its square is ##,###,###,###"; sq
done = true
end
rem - only even numbers can have a square ending in 6
n = n + 2
end
 
end
</syntaxhighlight>
{{out}}
<pre>
Finding smallest number whose square ends in 269696
The smallest number is 25264
and its square is 638,269,696
</pre>
 
=={{header|Scala}}==
<langsyntaxhighlight lang="scala">
object BabbageProblem {
def main( args:Array[String] ): Unit = {
Line 3,100 ⟶ 4,142:
}
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,108 ⟶ 4,150:
or same solution with a functional implementation
 
<langsyntaxhighlight lang="scala">
import scala.annotation.tailrec
 
Line 3,127 ⟶ 4,169:
 
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,135 ⟶ 4,177:
=={{header|Scheme}}==
 
<syntaxhighlight lang="scheme">
<lang Scheme>
(define (digits n)
(string->list (number->string n)))
Line 3,160 ⟶ 4,202:
 
;; 25264
</syntaxhighlight>
</lang>
 
=={{header|Scilab}}==
{{trans|Pascal}}
<syntaxhighlight lang="text">n=2;
flag=%F
while ~flag
Line 3,172 ⟶ 4,214:
end
end
disp(n);</langsyntaxhighlight>
{{out}}
<pre> 25264.</pre>
Line 3,178 ⟶ 4,220:
=={{header|Seed7}}==
 
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
 
const proc: main is func
Line 3,188 ⟶ 4,230:
end while;
writeln("The square of " <& current <& " is " <& current ** 2);
end func;</langsyntaxhighlight>
 
{{out}}
Line 3,197 ⟶ 4,239:
=={{header|SenseTalk}}==
 
<langsyntaxhighlight lang="sensetalk">
(*
Answer Charles Babbage's question:
Line 3,214 ⟶ 4,256:
end repeat
 
</syntaxhighlight>
</lang>
 
Note that because SenseTalk sees things as an ordinary person does, there is no need to make a distinction between a number and its text representation.
 
=={{header|SequenceL}}==
<langsyntaxhighlight lang="sequencel">main() := babbage(0);
babbage(current) :=
current when current * current mod 1000000 = 269696
else
babbage(current + 1);</langsyntaxhighlight>
 
{{out}}
Line 3,233 ⟶ 4,275:
 
=={{header|Shen}}==
<langsyntaxhighlight lang="shen">(define babbage
N -> N where (= 269696 (shen.mod (* N N) 1000000)))
N -> (babbage (+ N 1))
 
(babbage 1)</langsyntaxhighlight>
{{out}}
<pre>25264</pre>
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">var n = 0
while (n*n % 1000000 != 269696) {
n += 2
}
say n</langsyntaxhighlight>
{{out}}
<pre>
Line 3,253 ⟶ 4,295:
 
=={{header|Simula}}==
<langsyntaxhighlight lang="simula">BEGIN
INTEGER PROBE, SQUARE;
BOOLEAN DONE;
Line 3,274 ⟶ 4,316:
END;
 
END</langsyntaxhighlight>
{{out}}
<pre>
Line 3,282 ⟶ 4,324:
 
=={{header|Smalltalk}}==
<langsyntaxhighlight lang="smalltalk">"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</langsyntaxhighlight>
{{out}}
<pre>25264</pre>
 
=={{header|SQL}}==
{{works with|ORACLE 19c}}
<syntaxhighlight lang="sql">
/*
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;
</syntaxhighlight>
 
{{out}}
<pre>
The exact square of an integer cannot end with '2', so there is no such smallest number whose square ends in '222'
The exact square of an integer cannot end with '3', so there is no such smallest number whose square ends in '33'
The exact square of an integer cannot end with '7', so there is no such smallest number whose square ends in '17'
The exact square of an integer cannot end with '8', so there is no such smallest number whose square ends in '888'
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 '1000'
100 is the smallest number, whose square 10'000' ends in '000'
25264 is the smallest number, whose square 638'269696' ends in '269696'
25264 is the smallest number, whose square 638'269696' ends in '269696'
There is no such smallest number before 1000000 whose square ends in '169696'
12236 is the smallest number, whose square 1497'19696' ends in '19696'
48 is the smallest number, whose square 23'04' ends in '04'
</pre>
 
=={{header|Swift}}==
<langsyntaxhighlight Swiftlang="swift">import Swift
 
for i in 2...Int.max {
Line 3,298 ⟶ 4,417:
break
}
}</langsyntaxhighlight>
{{out}}
<pre>25264 is the smallest number that ends with 269696</pre>
Line 3,304 ⟶ 4,423:
=={{header|Tcl}}==
Hope Mr Babbage can understand this one-liner...
<langsyntaxhighlight Tcllang="tcl">for {set i 1} {![string match *269696 [expr $i*$i]]} {incr i} {}
puts "$i squared is [expr $i*$i]"</langsyntaxhighlight>
<pre>
25264 squared is 638269696
Line 3,312 ⟶ 4,431:
=== Scalable version ===
I have added some comments to the code, but left out a Tcl tutorial.
<syntaxhighlight lang="tcl">
<lang Tcl>
# The last k digits of a square x**2 are determined by the last k digits of
## the number x, and independent of all higher digits.
Line 3,462 ⟶ 4,581:
puts "(did $::didSqs squarings upto now)"
## You may want to try 08315917380318501319044 for solution 9999999156746824862
</syntaxhighlight>
</lang>
{{out}}
<pre> List of suffixes of length 1 has 2 elements:
Line 3,484 ⟶ 4,603:
In 1996 was manufactured the TI-83, a handheld graphing calculators with a basic language called TI-83 Basic.
The language is small and neat. For example to store 500 into a variable, it is done without twisting the meaning in mathematics of the equal sign (=).
<syntaxhighlight lang ="ti83b">536→N</langsyntaxhighlight>
Do not be attracted by brute force, let's do some basic maths:
<br>As
Line 3,497 ⟶ 4,616:
N must ends by 4 or 6 &rArr; N&ge;536
So, Lord Babbage here is your program:
<langsyntaxhighlight lang="ti83b">536→N
While remainder(N*N,1000000)≠269696
i+8→N
End
Disp N</langsyntaxhighlight>
And within a minute you have the answer:
{{out}}
Line 3,516 ⟶ 4,635:
<pre>
638269696
</pre>
 
=={{header|Transd}}==
<syntaxhighlight lang="scheme">#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)
) )
}</syntaxhighlight>{{out}}
<pre>
25264
</pre>
 
Line 3,523 ⟶ 4,658:
{{works with|Z Shell}}
 
<langsyntaxhighlight lang="bash"># Program to determine the smallest positive integer whose square
# has a decimal representation ending in the digits 269,696.
 
Line 3,539 ⟶ 4,674:
# To get here we must have found an integer whose square meets the
# condition; display that final result
echo $trial_value</langsyntaxhighlight>
{{Out}}
<pre>25264</pre>
Line 3,557 ⟶ 4,692:
are replaced by "expr".
 
<langsyntaxhighlight lang="bash">#!/bin/dash
 
# Babbage problem:
Line 3,641 ⟶ 4,776:
sort -n | # numbers in ascending order
head -n 1 # show only smallest
</syntaxhighlight>
</lang>
 
{{out}}
Line 3,653 ⟶ 4,788:
=={{header|UTFool}}==
 
<syntaxhighlight lang="utfool">
<lang UTFool>
···
http://rosettacode.org/wiki/Babbage_problem
Line 3,664 ⟶ 4,799:
if ("⸨number × number⸩").endsWith "269696"
System.exit number
</syntaxhighlight>
</lang>
 
=={{header|VAX Assembly}}==
<syntaxhighlight lang="vax assembly">
<lang VAX Assembly>
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
Line 3,693 ⟶ 4,828:
$ run bab
25264
</syntaxhighlight>
</lang>
 
=={{header|VBA}}==
<syntaxhighlight lang="vb">
<lang vb>
Sub Baggage_Problem()
Dim i As Long
Line 3,710 ⟶ 4,845:
"Its square is : " & i * i
End Sub
</syntaxhighlight>
</lang>
<pre>The smallest positive integer whose square ends in the digits 269 696 is : 25264
Its square is : 638269696</pre>
 
=={{header|VBScript}}==
<langsyntaxhighlight lang="vb">'Sir, this is a script that could solve your problem.
 
'Lines that begin with the apostrophe are comments. The machine ignores them.
Line 3,740 ⟶ 4,875:
 
'End of Program.
</syntaxhighlight>
</lang>
{{Out}}
<pre>The smallest positive integer whose square ends in 269696 is 25264.
Its square is 638269696.</pre>
 
=={{header|Vedit macro language}}==
<syntaxhighlight lang="vedit">
// Vedit Macro Language stores numerical values in numeric registers,
// referred as #0 to #255.
 
// Check all positive integer values until the required value found
for (#1 = 1; #1 < MAXNUM; #1++) {
 
#2 = #1 * #1 // #2 = square of the value
 
// The operator % is the modulo operator (the remainder of division).
// Modulo 1000000 gives the last 6 digits of a value.
#3 = #2 % 1000000
 
if (#3 == 269696) {
break // We found it, lets stop here
}
}
 
if (#1 < MAXNUM) {
Message("The smallest number whose square ends in 269696 is ", NOCR)
Num_Type(#1)
Message("The square is ", NOCR)
Num_Type(#2)
} else {
Message("Condition not satisfied before MAXNUM reached.)
}
</syntaxhighlight>
{{Out}}
<pre>The smallest number whose square ends in 269696 is 25264
The square is 638269696</pre>
 
=={{header|Verilog}}==
<syntaxhighlight lang="Verilog">module main;
real n;
 
initial begin
while (((n**2) % 1000000) != 269696) n=n+2;
$display("The smallest number whose square ends in 269696 is ", n);
$display("It's square is ", n*n);
end
endmodule</syntaxhighlight>
 
=={{header|Visual Basic .NET}}==
{{trans|C#}}
<langsyntaxhighlight lang="vbnet">Module Module1
 
Function Right6Digits(num As Long) As Long
Line 3,772 ⟶ 4,950:
End Sub
 
End Module</langsyntaxhighlight>
{{out}}
<pre>The smallest integer whose square ends in 269,696 is 25264
The square is 638269696</pre>
 
=={{header|V (Vlang)}}==
{{trans|go}}
<syntaxhighlight lang="v (vlang)">
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
}
}
}</syntaxhighlight>
 
{{out}}
<pre>
The smallest number whose square ends with 269696 is 25264
</pre>
 
=={{header|Wren}}==
{{libheader|Wren-fmt}}
<syntaxhighlight lang ecmascript="wren">/*
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.
However, we can skip numbers which don't end in 4 or 6 as their squares can't end in 6.
*/
 
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
Line 3,797 ⟶ 4,998:
break // break from the loop and end the program
}
if (i =% i10 +== 26) { // get the last digit by taking the //remainder increaseafter 'i'division by 210
i = i + 8 // if the last digit is 6 add 8 (to end in 4)
}</lang>
} else {
i = i + 2 // otherwise add 2
}
}</syntaxhighlight>
 
{{out}}
Line 3,808 ⟶ 5,013:
=={{header|x86 Assembly}}==
'''AT&T syntax''' {{works with|gas}}
<langsyntaxhighlight lang="asmatt"># 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):
Line 3,886 ⟶ 5,091:
ret
 
# The end.</langsyntaxhighlight>
{{out}}
<pre>25264</pre>
 
=={{header|XLISP}}==
<langsyntaxhighlight lang="scheme">; 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.
Line 3,915 ⟶ 5,120:
; We supply our function with 1 as an initial value to test, and ask the computer to print the final result.
 
(print (try 1))</langsyntaxhighlight>
{{out}}
<pre>25264</pre>
Line 3,921 ⟶ 5,126:
=={{header|XPL0}}==
Some preliminary tests show that the number to be squared (N) must end with 4 or 6 to get N^2 ending with 6. Additional tests show N must end 236, 264, 736 or 764. This leaves only 100 tests to determine the final number, which could be done by hand.
<langsyntaxhighlight XPL0lang="xpl0">int N, C, R;
[C:= 0;
for N:= sqrt(269696) to -1>>1 do \to infinity (2^31-1)
Line 3,942 ⟶ 5,147:
];
];
]</langsyntaxhighlight>
 
{{out}}
Line 3,949 ⟶ 5,154:
100
</pre>
 
 
=={{header|Yabasic}}==
<syntaxhighlight lang="yabasic">// 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</syntaxhighlight>
{{out}}
<pre>
El menor numero cuyo cuadrado termina en 269696 es: 25264
Y su cuadrado es: 638269696
</pre>
 
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">// 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 })</langsyntaxhighlight>
{{out}}
<pre>
305

edits