Babbage problem: Difference between revisions

(18 intermediate revisions by 12 users not shown)
Line 339:
+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}}==
Line 1,283 ⟶ 1,405:
 
=={{header|COBOL}}==
<syntaxhighlight lang="cobolcobolfree"> 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 1,294 ⟶ 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.</syntaxhighlight>
 
END PROGRAM BABBAGE-PROGRAM.</syntaxhighlight>
{{out}}
<pre>25264</pre>
Line 1,415 ⟶ 1,541:
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
end</syntaxhighlight>
It's square is 638269696</pre>
 
=={{header|D}}==
Line 1,663 ⟶ 1,790:
=={{header|Elena}}==
{{trans|Smalltalk}}
ELENA 46.x :
<syntaxhighlight lang="elena">import extensions;
import system'math;
Line 1,671 ⟶ 1,798:
var n := 1;
until(n.sqr().mod:(1000000) == 269696)
{
n += 1
Line 2,538 ⟶ 2,665:
 
<syntaxhighlight 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
 
</syntaxhighlight>
 
Line 2,665 ⟶ 2,798:
{{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}}==
Line 3,612 ⟶ 3,797:
 
This could certainly be written more concisely. Extra verbiage is included to make the process more clear.
<syntaxhighlight lang="raku" line># For all positivespositive integers from 1 to Infinity
for 1 .. Inf -> $integer {
Line 3,631 ⟶ 3,816:
{{out}}
<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.
 
=={{header|Red}}==
Line 3,896 ⟶ 4,083:
 
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}}==
Line 4,406 ⟶ 4,636:
638269696
</pre>
 
 
=={{header|Transd}}==
Line 4,650 ⟶ 4,879:
<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}}==
Line 4,719 ⟶ 4,980:
=={{header|Wren}}==
{{libheader|Wren-fmt}}
<syntaxhighlight lang="ecmascriptwren">/*
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.
Line 4,725 ⟶ 4,986:
*/
 
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
305

edits