Steady squares: Difference between revisions

Added Oberon-07
(→‎Python :: Functional: Updated accumulating version to use .endswith)
(Added Oberon-07)
(75 intermediate revisions by 16 users not shown)
Line 4:
<br>
The 3-digit number 376 in the decimal numbering system is an example of numbers with the special property that its square ends with the same digits: '''376*376 = 141376'''. Let's call a number with this property a steady square. Find steady squares under '''10.000'''
 
=={{header|ABC}}==
<syntaxhighlight lang="abc">
HOW TO REPORT n is.steady.square.below power.of.ten:
REPORT ( n * n ) mod power.of.ten = n
 
HOW TO MIGHT n BE A STEADY SQUARE BELOW power.of.ten:
IF n is.steady.square.below power.of.ten:
WRITE ( ( ( n << 1 ) ^ "^2 = " ) >> 10 ) ^ ( ( n * n ) >> 1 ) /
 
PUT 10 IN power.of.ten
PUT -10 IN n
FOR i IN { 0 .. 1000 }:
PUT n + 10 IN n
IF n = power.of.ten:
PUT power.of.ten * 10 IN power.of.ten
MIGHT ( n + 1 ) BE A STEADY SQUARE BELOW power.of.ten
MIGHT ( n + 5 ) BE A STEADY SQUARE BELOW power.of.ten
MIGHT ( n + 6 ) BE A STEADY SQUARE BELOW power.of.ten
</syntaxhighlight>
{{out}}
<pre>
1^2 = 1
5^2 = 25
6^2 = 36
25^2 = 625
76^2 = 5776
376^2 = 141376
625^2 = 390625
9376^2 = 87909376
</pre>
 
=={{header|Action!}}==
{{Trans|PROMAL}}
<syntaxhighlight lang="action!">
;;; find some steady squares - numbers whose squares end in the number
;;; e.g. 376^2 = 141 376
 
PROC Main()
CARD p ; the number to square, with the final digit replaced by 0
CARD n ; the number to square
CARD d10 ; 10^the number of digits in p, n
CARD s ; the square of n modulo d10
CARD f ; loop counter to choose 1, 5 or 6 as the final digit of q
CARD front ; the first 2 digits of n
CARD back ; the last two digits of n
 
d10 = 10
FOR p = 0 TO 10000 STEP 10 DO
IF p = d10 THEN
d10 ==* 10
FI
FOR f = 1 TO 3 DO
IF f = 1 THEN
n = p + 1
ELSEIF f = 2 THEN
n = p + 5
ELSE
n = p + 6
FI
IF n <= 255 THEN
s = ( n * n )
ELSE
front = n / 100
back = n MOD 100
s = ( back * back ) + ( 200 * ( ( front * back ) MOD 100 ) )
FI
s ==MOD d10
IF s = n THEN
Put(' ) PrintC( n )
FI
OD
OD
RETURN
</syntaxhighlight>
{{out}}
<pre>
1 5 6 25 76 376 625 9376
</pre>
 
=={{header|ALGOL 60}}==
{{works with|GNU Marst|Any - tested with release 2.7}}
<syntaxhighlight lang="algol60">
begin comment find steady squares - numbers whose square ends in the number
e.g.: 376^2 = 141 376 ;
 
integer powerOfTen, p;
powerOfTen := 10;
 
comment note the final digit must be 1, 5 or 6 ;
for p := 0 step 10 until 10 000 do begin
integer d;
if p = powerOfTen then begin
comment number of digits has increased ;
powerOfTen := powerOfTen * 10
end;
for d := 1, 5, 6 do begin
integer m, n, n2;
n := p + d;
n2 := n * n;
m := n2 - ( ( n2 % powerOfTen ) * powerOfTen ) ;
if m = n then outinteger( 1, n )
end
end
end
</syntaxhighlight>
{{out}}
<pre>
1 5 6 25 76 376 625 9376
</pre>
 
=={{header|ALGOL 68}}==
Using the observation that the final digit must be 1, 5 or 6 (See Talk page).
<syntaxhighlight lang="algol68">BEGIN # find some steady squares - numbers whose squares end in the number #
# e.g. 376^2 = 141 376 #
INT max number = 10 000; # maximum number we will consider #
INT power of ten := 10;
[]INT last digit = ( 1, 5, 6 );
FOR n FROM 0 BY 10 TO max number DO
IF n = power of ten THEN
# the number of digits just increased #
power of ten *:= 10
FI;
FOR d FROM LWB last digit TO UPB last digit DO
INT nd = n + last digit[ d ];
INT n2 = nd * nd;
IF n2 MOD power of ten = nd THEN
# have a steady square #
print( ( whole( nd, -5 ), "^2 = ", whole( n2, 0 ), newline ) )
FI
OD
OD
END</syntaxhighlight>
{{out}}
<pre>
1^2 = 1
5^2 = 25
6^2 = 36
25^2 = 625
76^2 = 5776
376^2 = 141376
625^2 = 390625
9376^2 = 87909376
</pre>
 
=={{header|ALGOL W}}==
<syntaxhighlight lang="algolw">
begin % find steady squares - numbers whose square ends in the number %
% e.g.: 376^2 = 141 376 %
 
% checks wheher n^2 mod p10 = n, i.e. n is a steady square and displays %
% a message if it is %
procedure possibleSteadySuare ( integer value n, p10 ) ;
if ( n * n ) rem p10 = n then write( i_w := 4, s_w := 0, n, "^2: ", i_w := 1, n * n );
 
integer powerOfTen;
powerOfTen := 10;
 
% note the final digit must be 1, 5 or 6 %
for p := 0 step 10 until 10000 do begin;
if p = powerOfTen then begin
% number of digits have increased %
powerOfTen := powerOfTen * 10
end if_p_eq_powerOfTen ;
possibleSteadySuare( p + 1, powerOfTen );
possibleSteadySuare( p + 5, powerOfTen );
possibleSteadySuare( p + 6, powerOfTen )
end
end.
</syntaxhighlight>
{{out}}
<pre>
1^2: 1
5^2: 25
6^2: 36
25^2: 625
76^2: 5776
376^2: 141376
625^2: 390625
9376^2: 87909376
</pre>
 
=={{header|Arturo}}==
{{trans|C}}
<syntaxhighlight lang="arturo">steady?: function [n][
mask: 1
d: n
while -> d <> 0 [
mask: mask * 10
d: d / 10
]
n = (n * n) % mask
]
 
loop 0..1000 'n [
loop [1 5 6] 'd [
r: d + 10 * n ; only check numbers that end with 1, 5, 6
if steady? r -> print ~"|r|^2 = |r*r|"
]
]</syntaxhighlight>
 
{{out}}
 
<pre>1^2 = 1
5^2 = 25
6^2 = 36
25^2 = 625
76^2 = 5776
376^2 = 141376
625^2 = 390625
9376^2 = 87909376</pre>
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f STEADY_SQUARES.AWK
BEGIN {
Line 21 ⟶ 232:
exit(0)
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 40 ⟶ 251:
 
=={{header|BASIC}}==
==={{header|Applesoft BASIC}}===
{{trans|GW-BASIC}}
<syntaxhighlight lang="qbasic">100 HOME
110 FOR n = 1 TO 10000
120 m$ = STR$(n)
130 n2$ = STR$(n*n)
140 IF RIGHT$(n2$,LEN(m$)) = m$ THEN HTAB(5-LEN(m$)): PRINT m$;"^2 = ";N2$
150 NEXT n
160 END</syntaxhighlight>
 
==={{header|ASIC}}===
Compile with the ''Extended math'' option.
{{trans|C}}
<langsyntaxhighlight lang="basic">
REM Steady squares
FOR I = 1 TO 9999
Line 73 ⟶ 294:
ENDIF
RETURN
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 84 ⟶ 305:
625 ^ 2 = 390625
9376 ^ 2 = 87909376
</pre>
 
==={{header|BASIC256}}===
<syntaxhighlight lang="freebasic">for i = 1 to 9999
if isSteady(i) then
print rjust(i,4); "^2 = "; rjust(i * i,8)
end if
next i
end
 
function isSteady(n)
mask = 1
d = n
while d <> 0
mask *= 10
d = int(d / 10)
end while
return ((n * n) mod mask = n)
end function</syntaxhighlight>
{{out}}
<pre>Same as FreeBASIC entry.</pre>
 
=== {{header|Chipmunk Basic}} ===
{{trans|GW-BASIC}}
<syntaxhighlight lang="basic">
10 rem Steady squares
20 for n = 1 to 10000
30 m$ = str$(n)
40 n2$ = str$(n*n)
50 if right$(n2$,len(m$)) = m$ then print m$,n2$
60 next n
70 end
</syntaxhighlight>
{{out}}
<pre>
1 1
5 25
6 36
25 625
76 5776
376 141376
625 390625
9376 87909376
</pre>
 
==={{header|FreeBASIC}}===
<langsyntaxhighlight lang="freebasic">function numdig( byval n as uinteger ) as uinteger
'number of decimal digits in n
dim as uinteger d=0
Line 104 ⟶ 368:
for i as uinteger = 1 to 10000
if is_steady_square(i) then print using "####^2 = ########";i;i^2
next i</langsyntaxhighlight>
{{out}}
<pre>
Line 116 ⟶ 380:
9376^2 = 87909376
</pre>
 
==={{header|Gambas}}===
{{trans|FreeBASIC}}
<syntaxhighlight lang="vbnet">Public Sub Main()
For i As Integer = 1 To 10000
If is_steady_square(i) Then Print Format$(i, "####"); "^2 = "; Format$(i ^ 2, "########")
Next
End
 
Function numdig(n As Integer) As Integer
 
Dim d As Integer = 0
While n
d += 1
n \= 10
Wend
Return d
 
End Function
 
Function is_steady_square(n As Integer) As Boolean
 
Dim n2 As Integer = n ^ 2
Return IIf(n2 Mod CInt(10 ^ numdig(n)) = n, True, False)
 
End Function
</syntaxhighlight>
{{out}}
<pre>Same as FreeBASIC entry.</pre>
 
==={{header|GW-BASIC}}===
{{works with|BASICA}}
<lang gwbasic>10 FOR N = 1 TO 10000
<syntaxhighlight lang="gwbasic">10 FOR N = 1 TO 10000
20 M$ = STR$(N)
30 M2#=N*N
Line 125 ⟶ 421:
60 A = LEN(M$)
70 IF RIGHT$(N2$,A)= M$ THEN PRINT M$,N2$
80 NEXT N</langsyntaxhighlight>
{{out}}
<pre>
Line 141 ⟶ 437:
{{trans|C}}
{{works with|Just BASIC|any}}
<syntaxhighlight lang="lb">
<lang lb>
rem Steady squares
for i = 1 to 9999
Line 159 ⟶ 455:
isSteady = ((n * n) mod mask = n)
end function
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 172 ⟶ 468:
</pre>
 
==={{header|TinyMSX BASICBasic}}===
{{trans|GW-BASIC}}
Because TinyBASIC is limited to signed 16-bit integers, we need to perform the squaring by repeated addition and then take modulus. That makes for a pretty inefficient solution.
<syntaxhighlight lang="qbasic">10 CLS
20 FOR N = 1 TO 10000
30 M$ = STR$(N)
40 M2# = N*N
50 M$ = RIGHT$(M$,LEN(M$)-1)
60 N2$ = STR$(M2#)
70 A = LEN(M$)
80 IF RIGHT$(N2$,A)= M$ THEN LOCATE 5-LEN(M$): PRINT M$;"^2 =";N2$
90 NEXT N
100 END</syntaxhighlight>
 
==={{header|QBasic}}===
<lang tinybasic>REM N = THE NUMBER TO BE SQUARED
{{works with|QBasic|1.1}}
{{works with|QuickBasic|4.5}}
<syntaxhighlight lang="qbasic">FUNCTION isSteady! (n!)
mask = 1
d = n
WHILE d <> 0
mask = mask * 10
d = INT(d / 10)
WEND
isSteady = ((n * n) MOD mask = n)
END FUNCTION
 
FOR i = 1 TO 9999
IF isSteady(i) THEN
PRINT USING ("####^2 = ########"); i; i * i
END IF
NEXT i
</syntaxhighlight>
{{out}}
<pre>Same as FreeBASIC entry.</pre>
 
==={{header|Run BASIC}}===
{{works with|Just BASIC}}
{{works with|Liberty BASIC}}
<syntaxhighlight lang="lb">for i = 1 to 9999
if isSteady(i) then
print using("####",i); "^2 = "; using("########", i * i)
end if
next i
end
 
function isSteady(n)
mask = 1
d = n
while d <> 0
mask = mask * 10
d = int(d / 10)
wend
isSteady = ((n * n) mod mask = n)
end function</syntaxhighlight>
{{out}}
<pre>Same as FreeBASIC entry.</pre>
 
==={{header|Tiny BASIC}}===
{{works with|TinyBasic}}
Although TinyBASIC is limited to signed 16-bit integers, we can still handle the basic task by noting that we can split a four digit number into the first pair of digits and the seoncd pair. If we call these F and B say, then the number squared module 10000 is B*B + 200 * ( F*B MOD 100 ). Additionally, (as other samples have noted), we only need to consider numbers ending in 1, 5 or 6.
<syntaxhighlight lang="basic">
REM P = THE NUMBER TO SQUARE, WITH THE FINAL DIGIT REPLACED BY 0
REM X = THE FINAL DIGIT OF THE NUMBER, 1, 5 OR 6
REM N = THE NUMBER TO BE SQUARED
REM D = 10^THE NUMBER OF DIGITS IN N
REM MS = THE SQUARE OF N, MODULO D
REM TF = TEMPTHE COPYFRONT (FIRST TWO DIGITS) OF N
REM B = THE BACK (LAST TWO DIGITS) OF N
 
10 LET N P= 10
20 LET D = 10
10 IF N > 9 THEN30 LET D X= 1001
40 IF N > 99D=P THEN LET D = 1000D*10
50 LET N=P+X
IF N > 999 THEN LET D = 10000
60 LET M F= 0N/100
70 LET T B= N-F*100
20 80 LET M S= M B*B+ N200*(F*B-F*B/100*100)
90 IF LET M = M S- (MS/D)*D=N THEN PRINT N
100 LET T X= T - 1X+4
110 IF T > 0 THENX=10 GOTOLET 20P=P+10
120 IF X=10 LET X=1
rem PRINT N, " ", M
130 IF MX=9 LET X= N THEN PRINT N6
140 IF P<9990 LETTHEN NGOTO = N + 140
150 END
IF N < 10000 THEN GOTO 10
</syntaxhighlight>
END</lang>
 
{{out}}<pre>
<pre>
1
1
5
5
6
6
25
25
76
76
376
376
625
625
9376</pre>
9376
</pre>
 
==={{header|True BASIC}}===
<syntaxhighlight lang="qbasic">FUNCTION issteady(n)
LET mask = 1
LET d = n
DO WHILE d <> 0
LET mask = mask*10
LET d = INT(d/10)
LOOP
LET res = MOD((n * n), mask)
IF res = n THEN
LET issteady = res
ELSE
LET issteady = 0
END IF
END FUNCTION
 
FOR i = 1 TO 9999
IF issteady(i) <> 0 THEN
PRINT USING("####"):i;
PRINT "^2 = ";
PRINT USING("########"): i*i
END IF
NEXT i
END</syntaxhighlight>
{{out}}
<pre>Same as FreeBASIC entry.</pre>
 
==={{header|Yabasic}}===
<syntaxhighlight lang="yabasic">// Rosetta Code problem: http://rosettacode.org/wiki/Steady_squares
// by Galileo, 04/2022
 
for i = 1 to 10000
r$ = str$(i^2, "%9.f")
if i = val(right$(r$, len(str$(i)))) print i, "\t=", r$
next</syntaxhighlight>
{{out}}
<pre>1 = 1
5 = 25
6 = 36
25 = 625
76 = 5776
376 = 141376
625 = 390625
9376 = 87909376
---Program done, press RETURN---</pre>
 
=={{header|C}}==
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <stdbool.h>
Line 225 ⟶ 630:
printf("%4d^2 = %8d\n", i, i * i);
return 0;
}</langsyntaxhighlight>
{{out}}
<pre> 1^2 = 1
Line 235 ⟶ 640:
625^2 = 390625
9376^2 = 87909376</pre>
 
=={{header|C++}}==
{{trans|C}}
<syntaxhighlight lang="cpp">#include <iostream>
using namespace std;
 
bool steady(int n) {
int mask = 1;
for (int d = n; d != 0; d /= 10)
mask *= 10;
return (n * n) % mask == n;
}
int main() {
for (int i = 1; i < 10000; i++)
if (steady(i)) printf("%4d^2 = %8d\n", i, i * i);
}</syntaxhighlight>
{{out}}
<pre>Same as C entry.</pre>
 
=={{header|CLU}}==
<langsyntaxhighlight lang="clu">n_digits = proc (n: int) returns (int)
i: int := 0
while n>0 do
Line 260 ⟶ 684:
stream$putl(po, "")
end
end start_up</langsyntaxhighlight>
{{out}}
<pre> 1^2 = 1
Line 270 ⟶ 694:
625^2 = 390625
9376^2 = 87909376</pre>
 
=={{header|Dart}}==
{{trans|C}}
<syntaxhighlight lang="dart">bool steady(int n) {
int mask = 1;
for (int d = n; d != 0; d ~/= 10) mask *= 10;
return (n * n) % mask == n;
}
 
void main() {
for (int i = 1; i < 10000; i++) if (steady(i)) print('$i^2 = ${i * i}');
}</syntaxhighlight>
{{out}}
<pre>1^2 = 1
5^2 = 25
6^2 = 36
25^2 = 625
76^2 = 5776
376^2 = 141376
625^2 = 390625
9376^2 = 87909376</pre>
 
=={{header|Delphi}}==
{{works with|Delphi|6.0}}
{{libheader|SysUtils,StdCtrls}}
 
 
<syntaxhighlight lang="Delphi">
{This routine is normally part of a separate library, but it is included here for clarity}
 
procedure GetDigits(N: integer; var IA: TIntegerDynArray);
{Get an array of the integers in a number}
{Numbers returned from least to most significant}
var T,I,DC: integer;
begin
DC:=Trunc(Log10(N))+1;
SetLength(IA,DC);
for I:=0 to DC-1 do
begin
T:=N mod 10;
N:=N div 10;
IA[I]:=T;
end;
end;
 
 
 
function IsSteadySquare(N: integer): boolean;
{compare digits of N and N^2 and see if they matchs}
var Dig1,Dig2: TIntegerDynArray;
var I: integer;
begin
Result:=False;
{Get digits}
GetDigits(N,Dig1);
GetDigits(N*N,Dig2);
{Compare digits}
for I:=0 to High(Dig1) do
if Dig1[I]<>Dig2[I] then exit;
Result:=True
end;
 
 
procedure ShowSteadySquares(Memo: TMemo);
var I: integer;
begin
for I:=1 to 10000-1 do
if IsSteadySquare(I) then
Memo.Lines.Add(Format('%6.0n^2 = %10.0n',[I+0.0,I*I+0.0]));
end;
 
 
</syntaxhighlight>
{{out}}
<pre>
1^2 = 1
5^2 = 25
6^2 = 36
25^2 = 625
76^2 = 5,776
376^2 = 141,376
625^2 = 390,625
9,376^2 = 87,909,376
Elapsed Time: 11.168 ms.
 
</pre>
 
 
=={{header|Draco}}==
<langsyntaxhighlight lang="draco">proc nonrec steady(ulong n) bool:
ulong mask;
mask := 1;
Line 286 ⟶ 797:
fi
od
corp</langsyntaxhighlight>
{{out}}
<pre> 1^2 = 1
Line 296 ⟶ 807:
625^2 = 390625
9376^2 = 87909376</pre>
 
=={{header|Euler}}==
The original Euler implementations didn't have loops built-in, however they can be constructed using labels and gotos.
As procedures can take literal procedures as parameters, procedures to provide a loops can be defined. This is used here to define a "while" loop procedure.
<br>
Note that text between ` and ' is a procedure literal. The text "new while; while <- `...'" defines a new variable and assigned the while-loop procedure to it. When called, the text of the condition and loop body must be enclosed in ` and ' to make them procedures - otherwise they would not be evaluated each time as requried.
<br>
All Euler variables are declared using "new var" (only one variable per "new"), labels must be declared with "label" and procedure parametrers are declared with "formal" (again, only one label or parameter per "label" or "formal" declaration).
<br>
Everything is Euler is an expression (apart from new/label/formal) and returns a value (although the value of a "goto" can't be used), so the "else" part of an "if" is not optional, hence the "else 0"s appearing in the code below.
'''begin'''
'''new''' maxNumber; '''new''' powerOfTen; '''new''' lastDigit; '''new''' n;
'''new''' while;
while &lt;- ` '''formal''' condition; '''formal''' loopBody;
'''begin'''
'''label''' again;
again: '''if''' condition '''then''' '''begin''' loopBody; '''goto''' again '''end''' '''else''' 0
'''end'''
&apos;
;
maxNumber &lt;- 10 000;
powerOfTen &lt;- 10;
lastDigit &lt;- ( 1, 5, 6 );
n &lt;- -10;
while( ` [ n &lt;- n + 10 ] &lt;= maxNumber &apos;
, ` '''begin'''
'''new''' d;
'''if''' n = powerOfTen '''then''' powerOfTen &lt;- powerOfTen * 10
'''else''' 0;
d &lt;- 0;
while( ` [ d &lt;- d + 1 ] &lt;= '''length''' lastDigit &apos;
, ` '''begin'''
'''new''' nd; '''new''' n2;
nd &lt;- n + lastDigit[ d ];
n2 &lt;- nd * nd;
'''if''' n2 '''mod''' powerOfTen = nd '''then''' '''out''' nd '''else''' 0
'''end'''
&apos;
)
'''end'''
&apos;
)
'''end'''
$
{{out}}
<pre>
NUMBER 1
NUMBER 5
NUMBER 6
NUMBER 25
NUMBER 76
NUMBER 376
NUMBER 625
NUMBER 9376
</pre>
 
=={{header|F_Sharp|F#}}==
Line 301 ⟶ 869:
Implements [http://www.rosettacode.org/wiki/Talk:Steady_Squares No Search Required].
large values may be produced using only integers.
<langsyntaxhighlight lang="fsharp">
// Steady Squares. Nigel Galloway: December 21st., 2021
let fN g=let n=List.fold2(fun z n g->z+n*g) 0L g (g|>List.rev) in (n,g)
Line 307 ⟶ 875:
let stdySq(g0,N)=let rec fG n (g,l)=seq{let i=Array.item(int((n+g)%10L)) N in yield i; yield! (fG((n+g+2L*g0*i)/10L)(fN(i::l)))}
seq{yield g0; yield! fG(g0*g0/10L)(0L,[])}
</syntaxhighlight>
</lang>
===Some Examples===
<langsyntaxhighlight lang="fsharp">
stdySq six|>Seq.take 80|>Seq.rev|>Seq.iter(printf "%d");printfn ""
stdySq five|>Seq.take 80|>Seq.rev|>Seq.iter(printf "%d");printfn ""
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 319 ⟶ 887:
</pre>
;Confirming Phix's example for 999 digits (in 11 thousands of sec).
<langsyntaxhighlight lang="fsharp">
stdySq six|>Seq.skip 920|>Seq.take 79|>Seq.rev|>Seq.iter(printf "%d");printfn "..."
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 328 ⟶ 896:
</pre>
;9999 digits
<langsyntaxhighlight lang="fsharp">
stdySq six|>Seq.skip 9920|>Seq.take 79|>Seq.rev|>Seq.iter(printf "%d");printfn "...";;
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 337 ⟶ 905:
</pre>
;If you have 57secs to spare then do 99999 digits, I leave it to the faithless to prove that this a Steady Square.
<langsyntaxhighlight lang="fsharp">
stdySq six|>Seq.skip 99920|>Seq.take 79|>Seq.rev|>Seq.iter(printf "%d");printfn "...";;
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 349 ⟶ 917:
Only checking numbers that end with 1, 5, and 6. See [[Talk:Steady_Squares]] for more details.
{{works with|Factor|0.99 2021-06-02}}
<langsyntaxhighlight lang="factor">USING: formatting kernel math math.functions
math.functions.integer-logs prettyprint sequences
tools.memory.private ;
Line 359 ⟶ 927:
[ 10 * ] dip + dup steady?
[ dup sq commas "%4d^2 = %s\n" printf ] [ drop ] if
] cartesian-each</langsyntaxhighlight>
{{out}}
<pre>
Line 370 ⟶ 938:
625^2 = 390,625
9376^2 = 87,909,376
</pre>
 
=={{header|Fe}}==
<syntaxhighlight lang="clojure">
(= steadySquares
(fn (maxNumber) ; max number to consider
(let powerOfTen 10) ; 10^(the number of digits in n
(let lastDigit (list 1 5 6)); a steady square must end with 1, 5 or 6
(let lastResult (cons 0 nil)); latest steady square start with a dummy 0
(let result lastResult) ; list of steady squares - dummy leading 0
(let n -10) ; multiple of 10 to consider
(while (do (= n (+ n 10)) ; find steady squares up to maxNumber
(<= n maxNumber)
)
(if (is n powerOfTen)
(= powerOfTen (* powerOfTen 10)); number of digits has increased
)
(let d lastDigit)
(while (not (atom d)) ; try n + each possible lastDigit
(let nd (+ n (car d)))
(let n2 (* nd nd))
; Fe doesn't have a mod operator, integer division or a way
; to truncate a float to an integer, so we calculate
; n2 mod powerOfTen using repeated subtraction - but see
; FizzBuzz for an example of doing it with a C function
(let n2%p10 n2)
(let mDivisor (* powerOfTen powerOfTen))
(while (<= powerOfTen mDivisor)
(while (<= mDivisor n2%p10)
(= n2%p10 (- n2%p10 mDivisor))
)
(= mDivisor (/ mDivisor 10))
)
(if (is nd n2%p10)
(do (setcdr lastResult (cons nd nil))
(= lastResult (cdr lastResult))
)
)
(= d (cdr d))
)
)
(cdr result) ; return the list of steady squares without the dummy 0
)
)
(print (steadySquares 10000))
</syntaxhighlight>
{{out}}
<pre>
(1 5 6 25 76 376 625 9376)
</pre>
 
=={{header|Fermat}}==
<langsyntaxhighlight lang="fermat">Func Isstead( n ) =
m:=n;
d:=1;
Line 384 ⟶ 1,001:
for i = 1 to 9999 do
if Isstead(i) then !!(i,'^2 = ',i^2) fi;
od;</langsyntaxhighlight>
{{out}}
<pre>
Line 400 ⟶ 1,017:
{{trans|Wren}}
{{libheader|Go-rcu}}
<langsyntaxhighlight lang="go">package main
 
import (
Line 432 ⟶ 1,049:
}
}
}</langsyntaxhighlight>
 
{{out}}
Line 449 ⟶ 1,066:
=={{header|Haskell}}==
 
<langsyntaxhighlight lang="haskell">import Control.Monad (join)
import Data.List (isSuffixOf)
 
Line 462 ⟶ 1,079:
main =
print $
takeWhile (< 10000) $ filter p [0 ..]</langsyntaxhighlight>
{{Out}}
<pre>[0,1,5,6,25,76,376,625,9376]</pre>
 
 
or retaining the string pair when the test succeeds:
Or, obtaining the squares by addition, rather than multiplication:
<langsyntaxhighlight lang="haskell">import Control.Monad (join)
import Data.Bifunctor (bimap)
import Data.List (isSuffixOf)
 
---------------------- STEADY NUMBERS --------------------
 
steadyPair :: Int -> [(String, String)]
steadyPair n =
[ (s, s2)
| let (s, s2) = join bimap show (n, n * n),
s `isSuffixOf` s2
]
 
--------------------------- TEST -------------------------
main :: IO ()
main =
( \xs ->
let (w, w2) = join bimap length (last xs)
in mapM_
( putStrLn . uncurry ((<>) . (<> " -> "))
. bimap
(justifyRight w ' ')
(justifyRight w2 ' ')
)
xs
)
$ [0 .. 10000] >>= steadyPair
 
------------------------- GENERIC ------------------------
 
justifyRight :: Int -> Char -> String -> String
justifyRight n c = (drop . length) <*> (replicate n c <>)</syntaxhighlight>
{{Out}}
<pre> 0 -> 0
1 -> 1
5 -> 25
6 -> 36
25 -> 625
76 -> 5776
376 -> 141376
625 -> 390625
9376 -> 87909376</pre>
 
 
or obtaining the squares by addition, rather than multiplication:
<syntaxhighlight lang="haskell">import Control.Monad (join)
import Data.Bifunctor (bimap)
import Data.List (isSuffixOf)
Line 495 ⟶ 1,157:
(scanl (+) 0 [1, 3 ..])
)
)</langsyntaxhighlight>
{{Out}}
<pre>0 -> 0
Line 506 ⟶ 1,168:
625 -> 390625
9376 -> 87909376</pre>
 
=={{header|Haxe}}==
<syntaxhighlight lang="haxe">
class Main // steady squares
{
static inline var MAX_NUMBER = 10000;
 
static function main()
{
var powerOfTen = 10;
var pad = ' ';
var lastDigit = [ 1, 5, 6 ]; // possible final digits
var n = -10;
for ( n10 in 0...Math.floor( MAX_NUMBER / 10 ) + 1 ) {
n += 10;
if( n == powerOfTen ) { // the number of digits just increased
powerOfTen *= 10;
pad = pad.substr( 1 );
}
for( d in 0...lastDigit.length ){
var nd = n + lastDigit[ d ];
var n2 = nd * nd;
if( n2 % powerOfTen == nd ){ // have a steady square
Sys.println( '$pad$nd^2 = $n2' );
}
}
}
}
 
}
</syntaxhighlight>
{{out}}
<pre>
1^2 = 1
5^2 = 25
6^2 = 36
25^2 = 625
76^2 = 5776
376^2 = 141376
625^2 = 390625
9376^2 = 87909376
</pre>\
 
=={{header|J}}==
 
Implementation: <syntaxhighlight lang="j">issteady=: {{ Y-:N{.":*:y[N=.-#Y=.":y }}"0
issteady=: (": -: -@#@": {. ":@*:)"0 NB. tacit alternative</syntaxhighlight>Task example:<syntaxhighlight lang="j"> I.issteady i.1e4
0 1 5 6 25 76 376 625 9376</syntaxhighlight>Note that for larger values we would want to take advantage of the suffix characteristics of these numbers (a multi-digit steady square would have a suffix which is a steady square).
 
For example:
<syntaxhighlight lang=J>bigsteady=: {{
Y=. 1+s=.0x
whilst. Y < y do.
s=. (#~ issteady) ,(Y*i.10)+/s
Y=. Y*10
end.
s #~ y>s
}}</syntaxhighlight>
 
Example use:
 
<pre> $bigsteady 1e20
37
$bigsteady 1e30
54
q:54
2 3 3 3
9 6$bigsteady 1e30
0 1 5 6 25 76
376 625 9376 90625 109376 890625
2890625 7109376 12890625 87109376 212890625 787109376
1787109376 8212890625 18212890625 81787109376 918212890625 9918212890625
40081787109376 59918212890625 259918212890625 740081787109376 3740081787109376 6259918212890625
43740081787109376 56259918212890625 256259918212890625 743740081787109376 2256259918212890625 7743740081787109376
92256259918212890625 392256259918212890625 607743740081787109376 2607743740081787109376 7392256259918212890625 22607743740081787109376
77392256259918212890625 977392256259918212890625 9977392256259918212890625 19977392256259918212890625 80022607743740081787109376 380022607743740081787109376
619977392256259918212890625 3380022607743740081787109376 6619977392256259918212890625 93380022607743740081787109376 106619977392256259918212890625 893380022607743740081787109376
</pre>
 
== {{header|JavaScript}} ==
Line 511 ⟶ 1,251:
{{trans|TypeScript}}
{{trans|C}}
<langsyntaxhighlight lang="javascript">// Steady squares
 
function steady(n) {
Line 524 ⟶ 1,264:
if (steady(i))
console.log(i.toString().padStart(4, ' ') + "^2 = " +
(i * i).toString().padStart(8, ' '));</langsyntaxhighlight>
{{out}}
<pre> 1^2 = 1
Line 537 ⟶ 1,277:
 
=== Functional ===
<langsyntaxhighlight lang="javascript">(() => {
"use strict";
 
Line 594 ⟶ 1,334:
// MAIN ---
return main();
})();</langsyntaxhighlight>
{{Out}}
<pre>0, 1, 5, 6, 25, 76, 376, 625, 9376
Line 611 ⟶ 1,351:
{{works with|jq}}
'''Works with gojq, the Go implementation of jq'''
<langsyntaxhighlight lang="jq"># Input: an upper bound, or null for infinite
def steady_squares:
range(0; . // infinite)
Line 618 ⟶ 1,358:
 
10000
| steady_squares</langsyntaxhighlight>
{{out}}
<pre>
Line 633 ⟶ 1,373:
 
=={{header|Julia}}==
<langsyntaxhighlight lang="julia">issteadysquare(n) = (s = "$n"; s == "$(n * n)"[end+1-length(s):end])
 
println(filter(issteadysquare, 1:10000)) # [1, 5, 6, 25, 76, 376, 625, 9376]
</syntaxhighlight>
</lang>
 
 
 
=={{header|Lua}}==
{{Trans|ALGOL W}}
Uses the fact the final digit can only be 1, 5 or 6 (see the talk page).
<syntaxhighlight lang="lua">
do --[[ find steady squares - numbers whose square ends in the number
e.g.: 376^2 = 141 376
--]]
 
-- checks wheher n^2 mod p10 = n, i.e. n is a steady square and displays
-- a message if it is
local function possibleSteadySuare ( n, p10 )
if ( n * n ) % p10 == n then
io.write( string.format( "%4d", n ), "^2: ", n * n, "\n" )
end
end
 
local powerOfTen = 10
 
-- note the final digit must be 1, 5 or 6
for p = 0,10000,10 do
if p == powerOfTen then
-- number of digits has increased
powerOfTen = powerOfTen * 10
end
possibleSteadySuare( p + 1, powerOfTen )
possibleSteadySuare( p + 5, powerOfTen )
possibleSteadySuare( p + 6, powerOfTen )
end
end</syntaxhighlight>
{{out}}
<pre>
1^2: 1
5^2: 25
6^2: 36
25^2: 625
76^2: 5776
376^2: 141376
625^2: 390625
9376^2: 87909376
</pre>
 
=={{header|MAD}}==
<langsyntaxhighlight MADlang="mad"> NORMAL MODE IS INTEGER
VECTOR VALUES FMT = $I4,7H **2 = ,I8*$
THROUGH LOOP, FOR I=1, 1, I.G.10000
Line 651 ⟶ 1,432:
END OF CONDITIONAL
LOOP CONTINUE
END OF PROGRAM</langsyntaxhighlight>
{{out}}
<pre> 1**2 = 1
Line 661 ⟶ 1,442:
625**2 = 390625
9376**2 = 87909376</pre>
 
=={{header|Miranda}}==
<syntaxhighlight lang="miranda">main :: [sys_message]
main = [Stdout (lay (map showsteady (takewhile (< 10000) steadies)))]
where showsteady n = shownum n ++ "^2 = " ++ shownum (n^2)
 
steadies :: [num]
steadies = filter steady [1..]
 
steady :: num->bool
steady n = n = n^2 mod 10^numdigits n
 
numdigits :: num->num
numdigits n = 1, if n<10
= 1 + numdigits (n div 10), otherwise</syntaxhighlight>
{{out}}
<pre>1^2 = 1
5^2 = 25
6^2 = 36
25^2 = 625
76^2 = 5776
376^2 = 141376
625^2 = 390625
9376^2 = 87909376</pre>
 
=={{header|Nim}}==
<syntaxhighlight lang="Nim">import std/[algorithm, strutils]
 
var ends = @["1", "5", "6"]
var steady = @[1, 5, 6]
while ends.len != 0:
var newEnds: seq[string]
for e in ends:
for d in '1'..'9':
let s = d & e
let n = parseInt(s)
if n >= 10_000: break
if ($(n * n)).endsWith(s):
steady.add n
newEnds.add s
ends = newEnds
 
echo "Steady squares under 10_000: "
for n in sorted(steady):
echo n, "² = ", n * n
</syntaxhighlight>
 
{{out}}
<pre>Steady squares under 10_000:
1² = 1
5² = 25
6² = 36
25² = 625
76² = 5776
376² = 141376
625² = 390625
9376² = 87909376
</pre>
 
=={{header|Oberon-07}}==
<syntaxhighlight lang="modula2">
(* find some steady squares - numbers whose squares end in the number *)
(* e.g. 376^2 = 141 376 *)
 
MODULE SteadySquares;
IMPORT Out;
 
CONST maxNumber = 10000;
VAR n, powerOfTen :INTEGER;
 
PROCEDURE PossibleSteadySquare( r: INTEGER );
VAR r2: INTEGER;
BEGIN
r2 := r * r;
IF ( r2 MOD powerOfTen ) = r THEN
Out.Int( r, 6 );Out.String( "^2 = " );Out.Int( r2, 1 );Out.Ln
END
END PossibleSteadySquare;
 
BEGIN
powerOfTen := 10;
FOR n := 0 TO maxNumber BY 10 DO
IF n = powerOfTen THEN
(* the number of digits has increased *)
powerOfTen := powerOfTen * 10
END;
PossibleSteadySquare( n + 1 );
PossibleSteadySquare( n + 5 );
PossibleSteadySquare( n + 6 )
END
END SteadySquares.
</syntaxhighlight>
{{out}}
<pre>
1^2 = 1
5^2 = 25
6^2 = 36
25^2 = 625
76^2 = 5776
376^2 = 141376
625^2 = 390625
9376^2 = 87909376
</pre>
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">#!/usr/bin/perl
 
use strict; # https://rosettacode.org/wiki/Steady_Squares
use warnings;
 
($_ ** 2) =~ /$_$/ and printf "%5d %d\n", $_, $_ ** 2 for 1 .. 10000;</langsyntaxhighlight>
{{out}}
<pre>
Line 687 ⟶ 1,571:
in other words every successful 3-digit n must end with one of the previously successful answers (maybe zero padded), and so on for 4 digits, etc.<br>
I stopped after 8 digits to avoid the need to fire up gmp. Finishes near-instantly, of course.
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">success</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">5</span><span style="color: #0000FF;">,</span><span style="color: #000000;">6</span><span style="color: #0000FF;">}</span> <span style="color: #000080;font-style:italic;">-- (as above)</span>
Line 707 ⟶ 1,591:
<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;">"%,11d^2 = %,21d\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">si</span><span style="color: #0000FF;">,</span><span style="color: #000000;">si</span><span style="color: #0000FF;">*</span><span style="color: #000000;">si</span><span style="color: #0000FF;">})</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 729 ⟶ 1,613:
=== mpz (super fast to 1000 digits) ===
Obsessed with the idea the series could in fact be finite, I wheeled out gmp anyway... As per the talk page, it turns out that all steady squares (apart from 1) are in fact on a 5-chain and a 6-chain, which carry on forever. The following easily finishes in less than a second.
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">include</span> <span style="color: #004080;">mpfr</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
Line 766 ⟶ 1,650:
<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;">"%13s^2 = %25s\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">success</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">],</span><span style="color: #000000;">squared</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]})</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</langsyntaxhighlight>-->
No doubt you could significantly improve that by replacing the mul/div with mpz_powm_ui(r10, cand, 2, t10) and o/c not even trying to print any of the silly-length numbers.
{{out}}
Line 802 ⟶ 1,686:
Note that should this produce two steady squares of the same length that begin with the same digit, the one that ends in 5 would be shown first, even if it is numerically after then one that ends in 6, not that there are any such < 1e1000. In other words add a flag that effectively swaps the <code>ch = ch5</code> and <code>ch = ch6</code> lines.
=== No Search Required using strings ===
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #004080;">atom</span> <span style="color: #000000;">t0</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">time</span><span style="color: #0000FF;">()</span>
Line 846 ⟶ 1,730:
<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 steady squares &lt; 1e%d found\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">count</span><span style="color: #0000FF;">,</span><span style="color: #000000;">limit</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">})</span>
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">elapsed</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">time</span><span style="color: #0000FF;">()-</span><span style="color: #000000;">t0</span><span style="color: #0000FF;">)</span>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 914 ⟶ 1,798:
</pre>
Which is a whopping 35-fold speedup, so obviously ''all'' I need to do is make the compiler emit similarly efficient code...
 
=={{header|PL/0}}==
<syntaxhighlight lang="pascal">
const maxnumber = 10000;
var p10, n, d, nd, n2;
begin
p10 := 10;
n := 0;
while n <= maxnumber do begin
if n = p10 then p10 := p10 * 10;
d := 0;
while d < 6 do begin
if d = 5 then d := 6;
if d = 1 then d := 5;
if d = 0 then d := 1;
nd := n + d;
n2 := nd * nd;
n2 := n2 - ( ( n2 / p10 ) * p10 );
if n2 = nd then ! nd
end;
n := n + 10
end
end.
</syntaxhighlight>
{{out}}
<pre>
1
5
6
25
76
376
625
9376
</pre>
 
=={{header|PL/M}}==
{{works with|8080 PL/M Compiler}} ... under CP/M (or an emulator)
Although integers are restricted to unsigned 16-bit, 8080 PL/M also allows the use of BCD values.
This sample uses 8-digit BCD to find the steady squares. As with other samples, only numbers ending in 1, 5 or 6 are considered (see the Discussion page).
<syntaxhighlight lang="plm">
100H: /* FIND SOME STEADY SQUARES - NUMBERS WHOSE SQUARES END IN THE NUMBER */
/* E.G. 376^2 = 141$376 */
 
/* CP/M SYSTEM CALL AND I/O ROUTINES */
BDOS: PROCEDURE( FN, ARG ); DECLARE FN BYTE, ARG ADDRESS; GOTO 5; END;
PR$CHAR: PROCEDURE( C ); DECLARE C BYTE; CALL BDOS( 2, C ); END;
PR$STRING: PROCEDURE( S ); DECLARE S ADDRESS; CALL BDOS( 9, S ); END;
PR$NL: PROCEDURE; CALL PR$CHAR( 0DH ); CALL PR$CHAR( 0AH ); END;
PR$NUMBER: PROCEDURE( N ); /* PRINTS A NUMBER IN THE MINIMUN FIELD WIDTH */
DECLARE N ADDRESS;
DECLARE V ADDRESS, N$STR ( 6 )BYTE, W BYTE;
V = N;
W = LAST( N$STR );
N$STR( W ) = '$';
N$STR( W := W - 1 ) = '0' + ( V MOD 10 );
DO WHILE( ( V := V / 10 ) > 0 );
N$STR( W := W - 1 ) = '0' + ( V MOD 10 );
END;
CALL PR$STRING( .N$STR( W ) );
END PR$NUMBER;
 
/* BCD ARITHMETIC */
 
DECLARE DEC$LAST LITERALLY '3'; /* SUBSCRIPT OF LAST DIGIT PAIR */
DECLARE DEC$LEN LITERALLY '4'; /* LENGTH OF AN 8-DIGIT BCD NUMBER */
DECLARE DEC$8 LITERALLY '( DEC$LEN )BYTE'; /* TYPE DECLARATION OF AN */
/* 8-DIGIT BCD NUMBER - 4 BYTES */
 
 
PR$DEC: PROCEDURE( A$PTR ); /* PRINT AN UNSIGNED BCD NUMBER */
DECLARE A$PTR ADDRESS;
DECLARE A BASED A$PTR DEC$8;
DECLARE ( D, ZERO$CHAR, I, V ) BYTE;
ZERO$CHAR = ' ';
DO I = 0 TO DEC$LAST - 1;
V = A( I );
D = SHR( V AND 0F0H, 4 );
IF D = 0 THEN CALL PR$CHAR( ZERO$CHAR );
ELSE CALL PR$CHAR( D + ( ZERO$CHAR := '0' ) );
D = V AND 0FH;
IF D = 0 THEN CALL PR$CHAR( ZERO$CHAR );
ELSE CALL PR$CHAR( D + ( ZERO$CHAR := '0' ) );
END;
V = A( DEC$LAST );
D = SHR( V AND 0F0H, 4 );
IF D = 0 THEN CALL PR$CHAR( ZERO$CHAR );
ELSE CALL PR$CHAR( D + '0' );
D = V AND 0FH;
CALL PR$CHAR( D + '0' );
END PR$DEC ;
 
INIT$DEC: PROCEDURE( A$PTR ); /* SETS THE BCD VALUE IN A TO 0 */
DECLARE A$PTR ADDRESS;
DECLARE A BASED A$PTR DEC$8;
DECLARE I BYTE;
DO I = 0 TO DEC$LAST;
A( I ) = 0;
END;
END INIT$DEC ;
 
SET$DEC: PROCEDURE( A$PTR, B ); /* SETS THE BCD VALUE IN A TO B */
DECLARE ( A$PTR, B ) ADDRESS;
DECLARE A BASED A$PTR DEC$8;
DECLARE ( I, P, D1, D2 ) BYTE;
DECLARE V ADDRESS;
V = B;
P = DEC$LAST;
DO I = 0 TO DEC$LAST;
IF V = 0
THEN A( P ) = 0;
ELSE DO;
D1 = V MOD 10;
D2 = ( V := V / 10 ) MOD 10;
A( P ) = SHL( D2, 4 ) OR D1;
V = V / 10;
END;
P = P - 1;
END;
END SET$DEC ;
 
MOV$DEC: PROCEDURE( A$PTR, B$PTR ); /* ASSIGN THE BCD VALUE IN B TO A */
DECLARE ( A$PTR, B$PTR ) ADDRESS;
DECLARE A BASED A$PTR DEC$8, B BASED B$PTR DEC$8;
DECLARE I BYTE;
DO I = 0 TO DEC$LAST;
A( I ) = B( I );
END;
END MOV$DEC ;
 
ADD$DEC: PROCEDURE( A$PTR, B$PTR ); /* 8-DIGIT BCD ADDITION RESULT IN A */
DECLARE ( A$PTR, B$PTR ) ADDRESS;
DECLARE A BASED A$PTR DEC$8, B BASED B$PTR DEC$8;
DECLARE ( A0, A1, A2, A3 ) BYTE;
DECLARE ( B0, B1, B2, B3 ) BYTE;
/* SEPARATE THE DIGIT PAIRS */
A0 = A( 0 ); A1 = A( 1 ); A2 = A( 2 ); A3 = A( 3 );
B0 = B( 0 ); B1 = B( 1 ); B2 = B( 2 ); B3 = B( 3 );
/* DO THE ADDITIONS */
A3 = DEC( A3 + B3 );
A2 = DEC( A2 PLUS B2 );
A1 = DEC( A1 PLUS B1 );
A0 = DEC( A0 PLUS B0 );
/* RETURN THE RESULT */
A( 0 ) = A0; A( 1 ) = A1; A( 2 ) = A2; A( 3 ) = A3;
END ADD$DEC;
 
/* 8-DIGIT BCD MULTIPLICATION BY AN UNSIGNED INTEGER VIA ETHIOPIAN */
/* MULTIPLICATION, RESULT IN A */
MUL$DEC: PROCEDURE( A$PTR, B );
DECLARE ( A$PTR, B ) ADDRESS;
DECLARE V ADDRESS, R DEC$8, ACCUMULATOR DEC$8;
CALL MOV$DEC( .R, A$PTR );
V = B;
CALL INIT$DEC( .ACCUMULATOR );
DO WHILE( V > 0 );
IF ( V AND 1 ) = 1 THEN DO;
CALL ADD$DEC( .ACCUMULATOR, .R );
END;
V = SHR( V, 1 );
CALL ADD$DEC( .R, .R );
END;
CALL MOV$DEC( A$PTR, .ACCUMULATOR );
END MUL$DEC ;
 
BIN$DEC4: PROCEDURE( A$PTR )ADDRESS; /* CONVERT A 4-DIGIT BCD NUMBER TO */
DECLARE A$PTR ADDRESS; /* BINARY */
DECLARE A BASED A$PTR DEC$8;
DECLARE ( D, V, RESULT ) ADDRESS, I BYTE;
RESULT = 0;
DO I = DEC$LAST - 1 TO DEC$LAST;
V = A( I );
D = SHR( V AND 0F0H, 4 );
RESULT = ( RESULT * 10 ) + D;
D = V AND 0FH;
RESULT = ( RESULT * 10 ) + D;
END;
RETURN RESULT;
END BIN$DEC4 ;
 
/* TASK */
 
DECLARE ( P, Q, F, POWER$OF$10 ) ADDRESS;
DECLARE SQ DEC$8;
 
POWER$OF$10 = 10;
 
DO P = 0 TO 10$000 BY 10;
IF P = POWER$OF$10 THEN DO;
/* REACHED THE CURRENT POWER OF TEN - THE NUMBERS NOW HAVE ANOTHER */
/* DIGIT */
POWER$OF$10 = POWER$OF$10 * 10;
END;
DO F = 0 TO 2;
DO CASE F;
/* 0 */ Q = P + 1;
/* 1 */ Q = P + 5;
/* 2 */ Q = P + 6;
END;
CALL SET$DEC( .SQ, Q );
CALL MUL$DEC( .SQ, Q );
/* CONVERT THE LAST 4 DIGITS OF THE DECIMAL NUMBER TO BINARY */
/* AND COMPARE THE MODULI */
IF BIN$DEC4( .SQ ) MOD POWER$OF$10 = Q THEN DO;
/* FOUND ANOTHER STEADY SQUARE */
IF Q < 10 THEN CALL PR$CHAR( ' ' );
IF Q < 100 THEN CALL PR$CHAR( ' ' );
IF Q < 1000 THEN CALL PR$CHAR( ' ' );
CALL PR$NUMBER( Q );
CALL PR$STRING( .'**2: $' );
CALL PR$DEC( .SQ );
CALL PR$NL;
END;
END;
END;
 
EOF
</syntaxhighlight>
{{out}}
<pre>
1**2: 1
5**2: 25
6**2: 36
25**2: 625
76**2: 5776
376**2: 141376
625**2: 390625
9376**2: 87909376
</pre>
 
=={{header|Prolog}}==
works with swi-prolog
<syntaxhighlight lang="prolog">
steadySquare([], _, []).
steadySquare([N| NTail], Modulo, SteadyList):-
Modulo =< N,!,
Modulo1 is Modulo * 10,
steadySquare([N| NTail], Modulo1, SteadyList).
steadySquare([N| NTail], Modulo, [N| SteadyList]):-
N ^ 2 mod Modulo =:= N,!,
steadySquare(NTail, Modulo, SteadyList).
steadySquare([_| NTail], Modulo, SteadyList):-
steadySquare(NTail, Modulo, SteadyList).
 
candidateList(Limit, List):-
candidateList(5, Limit, List0),
append([0,1], List0, List).
 
candidateList(N, Limit, [N, N1| Tail]):-
N < Limit,!,
N1 is N + 1,
N10 is N + 10,
candidateList(N10, Limit, Tail).
candidateList(_, _, []).
 
showList(_, []):-!.
showList(FrmStr, [StSquare| Tail]):-
Sqr is StSquare ^ 2,
format(FrmStr, [StSquare, Sqr]),
showList(FrmStr, Tail).
do:- candidateList(1000000, List),
steadySquare(List, 1, SteadySquareList),
last(SteadySquareList, LastStSqr),
LastLen is 1 + floor(log10(LastStSqr)),
LastSqrLen is 1 + floor(log10(LastStSqr ^ 2)),
swritef(FrmStr, '~|~t~d~%d+ ~|~t~d~%d+~n', [LastLen, LastSqrLen]),
showList(FrmStr, SteadySquareList).
</syntaxhighlight>
{{out}}
<pre>
?- time(do).
0 0
1 1
5 25
6 36
25 625
76 5776
376 141376
625 390625
9376 87909376
90625 8212890625
109376 11963109376
890625 793212890625
% 900,133 inferences, 0.235 CPU in 0.235 seconds (100% CPU, 3834748 Lips)
true.
</pre>
 
=={{header|PROMAL}}==
As with the Tiny BASIC sample, 16-bit languages must avoid overflow when solving this task. Uses long multiplication modulo the appropriate power of ten and the fact that the final digit must be 1, 5 or 6 (see the Discussion page).
<syntaxhighlight lang="promal">
PROGRAM steadySquares
INCLUDE LIBRARY
 
WORD p ; the number to square, with the final digit replaced by 0
WORD n ; the number to square
WORD d10 ; 10^the number of digits in p, n
WORD s ; the square of n modulo d10
WORD f ; loop counter to choose 1, 5 or 6 as the final digit of n
WORD front ; the first two digits of n
WORD back ; the last two digits of n
 
BEGIN
d10 = 10
p = 0
WHILE p < 10000
IF p = d10
d10 = d10 * 10
FOR f = 1 TO 3
CHOOSE f
1
n = p + 1
2
n = p + 5
ELSE
n = p + 6
IF n <= 255
s = ( n * n )
ELSE
front = n / 100
back = n % 100
s = ( back * back ) + ( 200 * ( ( front * back ) % 100 ) )
s = s % d10
IF s = n
OUTPUT " #W", n
p = p + 10
END
</syntaxhighlight>
{{out}}
<pre>
1 5 6 25 76 376 625 9376
</pre>
 
=={{header|Python}}==
===Procedural===
<langsyntaxhighlight lang="python">print("working...")
print("Steady squares under 10.000 are:")
limit = 10000
Line 929 ⟶ 2,145:
print(str(n) + " " + str(square))
 
print("done...")</langsyntaxhighlight>
{{out}}
<pre>working...
Line 944 ⟶ 2,160:
 
===Functional===
<langsyntaxhighlight lang="python">'''Steady squares'''
 
from itertools import chain
Line 967 ⟶ 2,183:
ns = range(1, 1 + 10000)
xs = concatMap(steadyPair)(ns)
w, w2 = [(len(x) for x in xs[-1]])
 
print([n for n in ns if steadyPair(n)])
Line 996 ⟶ 2,212:
# MAIN ---
if __name__ == '__main__':
main()</langsyntaxhighlight>
{{Out}}
<pre>[1, 5, 6, 25, 76, 376, 625, 9376]
Line 1,011 ⟶ 2,227:
 
Or, defining the squares as an additive accumulation:
<langsyntaxhighlight lang="python">'''Steady Squares'''
 
from itertools import accumulate, chain, count, takewhile
Line 1,036 ⟶ 2,252:
# MAIN ---
if __name__ == '__main__':
main()</langsyntaxhighlight>
{{Out}}
<pre>0 -> 0
Line 1,049 ⟶ 2,265:
 
=={{header|Raku}}==
<syntaxhighlight lang="raku" perl6line>.say for ({$++²}…*).kv.grep( {$^v.ends-with: $^k} )[1..10]</langsyntaxhighlight>
{{out}}
<pre>(1 1)
Line 1,061 ⟶ 2,277:
(90625 8212890625)
(109376 11963109376)</pre>
 
=={{header|Quackery}}==
 
<syntaxhighlight lang="Quackery"> [ 1 swap
[ 10 / dup while
dip 1+ again ]
drop ] is digitcount ( n --> n )
 
[ dup 2 **
over digitcount
10 swap **
mod = ] is steady ( n --> b )
 
[]
10000 times
[ i^ steady if [ i^ join ] ]
echo</syntaxhighlight>
 
{{out}}
 
<pre>[ 0 1 5 6 25 76 376 625 9376 ]</pre>
 
=={{header|Refal}}==
<syntaxhighlight lang="refal">$ENTRY Go {
= <FindSteady 1 9999>;
};
 
FindSteady {
s.N s.Max, <Compare s.N s.Max>: '+' = ;
s.N s.Max, <Steady <Symb s.N>>: F = <FindSteady <+ s.N 1> s.Max>;
s.N s.Max = <ShowSteady s.N> <FindSteady <+ s.N 1> s.Max>;
};
 
ShowSteady {
s.N = <Prout <Symb s.N> '^2 = ' <* s.N s.N>>;
};
 
Steady {
e.N, <Symb <* <Numb e.N> <Numb e.N>>>: e.X e.N = T;
e.N = F;
};</syntaxhighlight>
{{out}}
<pre>1^2 = 1
5^2 = 25
6^2 = 36
25^2 = 625
76^2 = 5776
376^2 = 141376
625^2 = 390625
9376^2 = 87909376</pre>
 
=={{header|REXX}}==
<langsyntaxhighlight lang="rexx">/* REXX */
Numeric Digits 50
Call time 'R'
Line 1,076 ⟶ 2,342:
End
End
Say time('E')</langsyntaxhighlight>
{{out}}
<pre>Steady squares below 1000000000
Line 1,099 ⟶ 2,365:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
see "working..." +nl
see "Steady squatres under 10.000 are:" + nl
Line 1,115 ⟶ 2,381:
 
see "done..." +nl
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,130 ⟶ 2,396:
done...
</pre>
 
== {{header|RPL}} ==
===Brute force approach===
Numbers are converted into strings to make comparison easier.
≪ { 1 } 5 ROT '''FOR''' n
n →STR n SQ →STR
DUP SIZE 3 PICK SIZE - 1 + OVER SIZE SUB
'''IF''' == '''THEN''' n + '''END'''
'''NEXT'''
≫ ‘STEDY’ STO
 
10000 STEDY
{{out}}
<pre>
1: { 1 5 6 25 76 376 625 9376 }
</pre>
===Slight optimization===
Steady numbers must end with 5 or 6, but there's no double-digits-or-more ones ending with 1: if ##b1 was the base 10 representation of such a number, the 2nd digit from the right shall be b (because of steadiness) and 2b (because of the elevation to square), which means b=0. By recurrence, all digits shall be zero.
≪ { 1 } 0 ROT '''FOR''' n
5 6 '''FOR''' j
n j + →STR LAST SQ →STR
DUP SIZE 3 PICK SIZE - 1 + OVER SIZE SUB
'''IF''' == '''THEN''' n j + + '''END'''
'''NEXT'''
10 '''STEP'''
≫ ‘STEDY’ STO
 
== {{header|Ruby}} ==
<syntaxhighlight lang="ruby">p (0..10_000).select{|n| (n*n).to_s.end_with? n.to_s }
</syntaxhighlight>
{{out}}
<pre>[0, 1, 5, 6, 25, 76, 376, 625, 9376]
</pre>
 
=={{header|Rust}}==
<syntaxhighlight lang="rust">
fn is_steady_square(n: u32) -> bool {
fn iter(n: u32, m: u32) -> u64 {
if m <= n {iter(n, 10 * m)}
else {m as u64}
}
let nl = n as u64;
nl * nl % iter(n, 1) == nl
}
 
fn main() {
let start = std::time::Instant::now();
let limit = 10_000_000;
let list5 = (5..=limit).step_by(10)
.flat_map(|n|[n, n+1])
.filter(|&n| is_steady_square(n));
let list: Vec<u32> = (0..2).into_iter().chain(list5).collect();
 
let max = *list.iter().last().unwrap();
let maxl = max as u64;
let duration = start.elapsed().as_millis();
let max_len = max.to_string().len();
let sqr_len = (maxl*maxl).to_string().len();
println!("{:>max_len$} {:>sqr_len$}", "num", "square");
for n in list {
let nl = n as u64;
println!("{:max_len$} {:sqr_len$}", n, nl*nl);
}
println!("time(ms): {duration}");
}
</syntaxhighlight>
{{out}}
<pre>
num square
0 0
1 1
5 25
6 36
25 625
76 5776
376 141376
625 390625
9376 87909376
90625 8212890625
109376 11963109376
890625 793212890625
2890625 8355712890625
7109376 50543227109376
time(ms): 50
</pre>
 
=={{header|Scala}}==
ready for Scala3
<syntaxhighlight lang="scala">
def steadySquares(cand: Seq[Int], modulo: Long, acc: Seq[Int]): Seq[Int] = {
if (cand.isEmpty) return acc
val num = cand.head
val numl = num.toLong
val modulo1 = if (modulo > numl) modulo else 10 * modulo
val acc1 = if (numl * numl % modulo1 != numl) acc
else acc :+ num
steadySquares(cand.tail, modulo1, acc1)
}
 
val limit = 1_000_000
val candidates = Seq(0, 1) ++ (5 to limit by 10).flatMap(n => Seq(n, n + 1))
val list = steadySquares(candidates, 1, Seq())
 
@main def main = {
val start = System.currentTimeMillis
val max = list.last.toLong
val Seq(maxLen, sqrLen) = Seq(max, max * max).map(_.toString.length)
for (steadySquare <- list) {
val stSqr = steadySquare.toLong
val sqr = stSqr * stSqr
println("%%%dd %%%dd".format(maxLen, sqrLen).format(stSqr, sqr))
}
val duration = System.currentTimeMillis - start
println(s"time(ms): $duration")
}
</syntaxhighlight>
{{out}}
<pre>
0 0
1 1
5 25
6 36
25 625
76 5776
376 141376
625 390625
9376 87909376
90625 8212890625
109376 11963109376
890625 793212890625
time(ms): 7
</pre>
 
=={{header|SETL}}==
<syntaxhighlight lang="setl">program steady_squares;
loop for n in [1..10000] | steady n do
print(str n + "^2 = " + str (n**2));
end loop;
 
op steady(n);
return n**2 mod 10**#str n = n;
end op;
end program;</syntaxhighlight>
{{out}}
<pre>1^2 = 1
5^2 = 25
6^2 = 36
25^2 = 625
76^2 = 5776
376^2 = 141376
625^2 = 390625
9376^2 = 87909376</pre>
 
== {{header|TypeScript}} ==
{{trans|C}}
<langsyntaxhighlight lang="javascript">// Steady squares
 
function steady(n: number): bool {
Line 1,147 ⟶ 2,565:
console.log(i.toString().padStart(4, ' ') + "^2 = " +
(i * i).toString().padStart(8, ' '));
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,158 ⟶ 2,576:
625^2 = 390625
9376^2 = 87909376
</pre>
 
=={{header|VTL-2}}==
{{Trans|Tiny BASIC}}
<syntaxhighlight lang="vtl2">
110 P=0
120 D=10
130 X=1
140 D=D=P*9*D+D
150 N=P+X
160 F=N/100
170 B=N-(F*100)
180 S=F*B-(F*B/100*100)*200+(B*B)
190 #=S-(S/D*D)=N=0*220
200 ?=N
210 $=32
220 X=X+4
230 #=X=10=0*260
240 P=P+10
250 X=1
260 #=X=9=0*280
270 X=6
280 #=P<9990*140
</syntaxhighlight>
{{out}}
<pre>
1 5 6 25 76 376 625 9376
</pre>
 
Line 1,163 ⟶ 2,608:
{{libheader|Wren-fmt}}
Although it hardly matters for a small range such as this, one can cut down the numbers to be examined by observing that a steady square must end in 1, 5 or 6.
<langsyntaxhighlight ecmascriptlang="wren">import "./fmt" for Fmt
 
System.print("Steady squares under 10,000:")
Line 1,171 ⟶ 2,616:
var sq = i * i
if (sq.toString.endsWith(i.toString)) Fmt.print("$,5d -> $,10d", i, sq)
}</langsyntaxhighlight>
 
{{out}}
Line 1,187 ⟶ 2,632:
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">int N, P;
[for N:= 0 to 10000-1 do
[P:= 1;
Line 1,198 ⟶ 2,643:
];
];
]</langsyntaxhighlight>
 
{{out}}
Line 1,212 ⟶ 2,657:
9376^2 = 87909376
</pre>
 
=={{header|Yabasic}}==
<lang Yabasic>// Rosetta Code problem: http://rosettacode.org/wiki/Steady_squares
// by Galileo, 04/2022
 
for i = 1 to 10000
r$ = str$(i^2, "%9.f")
if i = val(right$(r$, len(str$(i)))) print i, "\t=", r$
next</lang>
{{out}}
<pre>1 = 1
5 = 25
6 = 36
25 = 625
76 = 5776
376 = 141376
625 = 390625
9376 = 87909376
---Program done, press RETURN---</pre>
3,043

edits