Steady squares: Difference between revisions
m (→{{header|J}}) |
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
||
Line 7: | Line 7: | ||
=={{header|ALGOL 68}}== |
=={{header|ALGOL 68}}== |
||
Using the observation that the final digit must be 1, 5 or 6 (See Talk page). |
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 # |
# e.g. 376^2 = 141 376 # |
||
INT max number = 10 000; # maximum number we will consider # |
INT max number = 10 000; # maximum number we will consider # |
||
Line 26: | Line 26: | ||
OD |
OD |
||
OD |
OD |
||
END</ |
END</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 40: | Line 40: | ||
=={{header|AWK}}== |
=={{header|AWK}}== |
||
<syntaxhighlight lang="awk"> |
|||
<lang AWK> |
|||
# syntax: GAWK -f STEADY_SQUARES.AWK |
# syntax: GAWK -f STEADY_SQUARES.AWK |
||
BEGIN { |
BEGIN { |
||
Line 55: | Line 55: | ||
exit(0) |
exit(0) |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 77: | Line 77: | ||
Compile with the ''Extended math'' option. |
Compile with the ''Extended math'' option. |
||
{{trans|C}} |
{{trans|C}} |
||
< |
<syntaxhighlight lang="basic"> |
||
REM Steady squares |
REM Steady squares |
||
FOR I = 1 TO 9999 |
FOR I = 1 TO 9999 |
||
Line 107: | Line 107: | ||
ENDIF |
ENDIF |
||
RETURN |
RETURN |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 121: | Line 121: | ||
==={{header|FreeBASIC}}=== |
==={{header|FreeBASIC}}=== |
||
< |
<syntaxhighlight lang="freebasic">function numdig( byval n as uinteger ) as uinteger |
||
'number of decimal digits in n |
'number of decimal digits in n |
||
dim as uinteger d=0 |
dim as uinteger d=0 |
||
Line 138: | Line 138: | ||
for i as uinteger = 1 to 10000 |
for i as uinteger = 1 to 10000 |
||
if is_steady_square(i) then print using "####^2 = ########";i;i^2 |
if is_steady_square(i) then print using "####^2 = ########";i;i^2 |
||
next i</ |
next i</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 152: | Line 152: | ||
==={{header|GW-BASIC}}=== |
==={{header|GW-BASIC}}=== |
||
< |
<syntaxhighlight lang="gwbasic">10 FOR N = 1 TO 10000 |
||
20 M$ = STR$(N) |
20 M$ = STR$(N) |
||
30 M2#=N*N |
30 M2#=N*N |
||
Line 159: | Line 159: | ||
60 A = LEN(M$) |
60 A = LEN(M$) |
||
70 IF RIGHT$(N2$,A)= M$ THEN PRINT M$,N2$ |
70 IF RIGHT$(N2$,A)= M$ THEN PRINT M$,N2$ |
||
80 NEXT N</ |
80 NEXT N</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 175: | Line 175: | ||
{{trans|C}} |
{{trans|C}} |
||
{{works with|Just BASIC|any}} |
{{works with|Just BASIC|any}} |
||
<syntaxhighlight lang="lb"> |
|||
<lang lb> |
|||
rem Steady squares |
rem Steady squares |
||
for i = 1 to 9999 |
for i = 1 to 9999 |
||
Line 193: | Line 193: | ||
isSteady = ((n * n) mod mask = n) |
isSteady = ((n * n) mod mask = n) |
||
end function |
end function |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 209: | Line 209: | ||
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. |
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="tinybasic">REM N = THE NUMBER TO BE SQUARED |
||
REM D = 10^THE NUMBER OF DIGITS IN N |
REM D = 10^THE NUMBER OF DIGITS IN N |
||
REM M = THE SQUARE OF N, MODULO D |
REM M = THE SQUARE OF N, MODULO D |
||
Line 229: | Line 229: | ||
LET N = N + 1 |
LET N = N + 1 |
||
IF N < 10000 THEN GOTO 10 |
IF N < 10000 THEN GOTO 10 |
||
END</ |
END</syntaxhighlight> |
||
{{out}}<pre> |
{{out}}<pre> |
||
Line 242: | Line 242: | ||
=={{header|C}}== |
=={{header|C}}== |
||
< |
<syntaxhighlight lang="c">#include <stdio.h> |
||
#include <stdbool.h> |
#include <stdbool.h> |
||
Line 259: | Line 259: | ||
printf("%4d^2 = %8d\n", i, i * i); |
printf("%4d^2 = %8d\n", i, i * i); |
||
return 0; |
return 0; |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> 1^2 = 1 |
<pre> 1^2 = 1 |
||
Line 271: | Line 271: | ||
=={{header|CLU}}== |
=={{header|CLU}}== |
||
< |
<syntaxhighlight lang="clu">n_digits = proc (n: int) returns (int) |
||
i: int := 0 |
i: int := 0 |
||
while n>0 do |
while n>0 do |
||
Line 294: | Line 294: | ||
stream$putl(po, "") |
stream$putl(po, "") |
||
end |
end |
||
end start_up</ |
end start_up</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> 1^2 = 1 |
<pre> 1^2 = 1 |
||
Line 306: | Line 306: | ||
=={{header|Draco}}== |
=={{header|Draco}}== |
||
< |
<syntaxhighlight lang="draco">proc nonrec steady(ulong n) bool: |
||
ulong mask; |
ulong mask; |
||
mask := 1; |
mask := 1; |
||
Line 320: | Line 320: | ||
fi |
fi |
||
od |
od |
||
corp</ |
corp</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> 1^2 = 1 |
<pre> 1^2 = 1 |
||
Line 335: | Line 335: | ||
Implements [http://www.rosettacode.org/wiki/Talk:Steady_Squares No Search Required]. |
Implements [http://www.rosettacode.org/wiki/Talk:Steady_Squares No Search Required]. |
||
large values may be produced using only integers. |
large values may be produced using only integers. |
||
< |
<syntaxhighlight lang="fsharp"> |
||
// Steady Squares. Nigel Galloway: December 21st., 2021 |
// 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) |
let fN g=let n=List.fold2(fun z n g->z+n*g) 0L g (g|>List.rev) in (n,g) |
||
Line 341: | Line 341: | ||
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)))} |
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,[])} |
seq{yield g0; yield! fG(g0*g0/10L)(0L,[])} |
||
</syntaxhighlight> |
|||
</lang> |
|||
===Some Examples=== |
===Some Examples=== |
||
< |
<syntaxhighlight lang="fsharp"> |
||
stdySq six|>Seq.take 80|>Seq.rev|>Seq.iter(printf "%d");printfn "" |
stdySq six|>Seq.take 80|>Seq.rev|>Seq.iter(printf "%d");printfn "" |
||
stdySq five|>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}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 353: | Line 353: | ||
</pre> |
</pre> |
||
;Confirming Phix's example for 999 digits (in 11 thousands of sec). |
;Confirming Phix's example for 999 digits (in 11 thousands of sec). |
||
< |
<syntaxhighlight lang="fsharp"> |
||
stdySq six|>Seq.skip 920|>Seq.take 79|>Seq.rev|>Seq.iter(printf "%d");printfn "..." |
stdySq six|>Seq.skip 920|>Seq.take 79|>Seq.rev|>Seq.iter(printf "%d");printfn "..." |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 362: | Line 362: | ||
</pre> |
</pre> |
||
;9999 digits |
;9999 digits |
||
< |
<syntaxhighlight lang="fsharp"> |
||
stdySq six|>Seq.skip 9920|>Seq.take 79|>Seq.rev|>Seq.iter(printf "%d");printfn "...";; |
stdySq six|>Seq.skip 9920|>Seq.take 79|>Seq.rev|>Seq.iter(printf "%d");printfn "...";; |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 371: | Line 371: | ||
</pre> |
</pre> |
||
;If you have 57secs to spare then do 99999 digits, I leave it to the faithless to prove that this a Steady Square. |
;If you have 57secs to spare then do 99999 digits, I leave it to the faithless to prove that this a Steady Square. |
||
< |
<syntaxhighlight lang="fsharp"> |
||
stdySq six|>Seq.skip 99920|>Seq.take 79|>Seq.rev|>Seq.iter(printf "%d");printfn "...";; |
stdySq six|>Seq.skip 99920|>Seq.take 79|>Seq.rev|>Seq.iter(printf "%d");printfn "...";; |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 383: | Line 383: | ||
Only checking numbers that end with 1, 5, and 6. See [[Talk:Steady_Squares]] for more details. |
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}} |
{{works with|Factor|0.99 2021-06-02}} |
||
< |
<syntaxhighlight lang="factor">USING: formatting kernel math math.functions |
||
math.functions.integer-logs prettyprint sequences |
math.functions.integer-logs prettyprint sequences |
||
tools.memory.private ; |
tools.memory.private ; |
||
Line 393: | Line 393: | ||
[ 10 * ] dip + dup steady? |
[ 10 * ] dip + dup steady? |
||
[ dup sq commas "%4d^2 = %s\n" printf ] [ drop ] if |
[ dup sq commas "%4d^2 = %s\n" printf ] [ drop ] if |
||
] cartesian-each</ |
] cartesian-each</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 407: | Line 407: | ||
=={{header|Fermat}}== |
=={{header|Fermat}}== |
||
< |
<syntaxhighlight lang="fermat">Func Isstead( n ) = |
||
m:=n; |
m:=n; |
||
d:=1; |
d:=1; |
||
Line 418: | Line 418: | ||
for i = 1 to 9999 do |
for i = 1 to 9999 do |
||
if Isstead(i) then !!(i,'^2 = ',i^2) fi; |
if Isstead(i) then !!(i,'^2 = ',i^2) fi; |
||
od;</ |
od;</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 434: | Line 434: | ||
{{trans|Wren}} |
{{trans|Wren}} |
||
{{libheader|Go-rcu}} |
{{libheader|Go-rcu}} |
||
< |
<syntaxhighlight lang="go">package main |
||
import ( |
import ( |
||
Line 466: | Line 466: | ||
} |
} |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 483: | Line 483: | ||
=={{header|Haskell}}== |
=={{header|Haskell}}== |
||
< |
<syntaxhighlight lang="haskell">import Control.Monad (join) |
||
import Data.List (isSuffixOf) |
import Data.List (isSuffixOf) |
||
Line 496: | Line 496: | ||
main = |
main = |
||
print $ |
print $ |
||
takeWhile (< 10000) $ filter p [0 ..]</ |
takeWhile (< 10000) $ filter p [0 ..]</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
<pre>[0,1,5,6,25,76,376,625,9376]</pre> |
<pre>[0,1,5,6,25,76,376,625,9376]</pre> |
||
Line 502: | Line 502: | ||
or retaining the string pair when the test succeeds: |
or retaining the string pair when the test succeeds: |
||
< |
<syntaxhighlight lang="haskell">import Control.Monad (join) |
||
import Data.Bifunctor (bimap) |
import Data.Bifunctor (bimap) |
||
import Data.List (isSuffixOf) |
import Data.List (isSuffixOf) |
||
Line 533: | Line 533: | ||
justifyRight :: Int -> Char -> String -> String |
justifyRight :: Int -> Char -> String -> String |
||
justifyRight n c = (drop . length) <*> (replicate n c <>)</ |
justifyRight n c = (drop . length) <*> (replicate n c <>)</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
<pre> 0 -> 0 |
<pre> 0 -> 0 |
||
Line 547: | Line 547: | ||
or obtaining the squares by addition, rather than multiplication: |
or obtaining the squares by addition, rather than multiplication: |
||
< |
<syntaxhighlight lang="haskell">import Control.Monad (join) |
||
import Data.Bifunctor (bimap) |
import Data.Bifunctor (bimap) |
||
import Data.List (isSuffixOf) |
import Data.List (isSuffixOf) |
||
Line 574: | Line 574: | ||
(scanl (+) 0 [1, 3 ..]) |
(scanl (+) 0 [1, 3 ..]) |
||
) |
) |
||
)</ |
)</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
<pre>0 -> 0 |
<pre>0 -> 0 |
||
Line 588: | Line 588: | ||
=={{header|J}}== |
=={{header|J}}== |
||
Implementation: < |
Implementation: <syntaxhighlight lang="j">issteady=: {{ Y-:N{.":*:y[N=.-#Y=.":y }}"0</syntaxhighlight>Task example:<syntaxhighlight lang="j"> I.issteady i.1e4 |
||
0 1 5 6 25 76 376 625 9376</ |
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). |
||
== {{header|JavaScript}} == |
== {{header|JavaScript}} == |
||
Line 595: | Line 595: | ||
{{trans|TypeScript}} |
{{trans|TypeScript}} |
||
{{trans|C}} |
{{trans|C}} |
||
< |
<syntaxhighlight lang="javascript">// Steady squares |
||
function steady(n) { |
function steady(n) { |
||
Line 608: | Line 608: | ||
if (steady(i)) |
if (steady(i)) |
||
console.log(i.toString().padStart(4, ' ') + "^2 = " + |
console.log(i.toString().padStart(4, ' ') + "^2 = " + |
||
(i * i).toString().padStart(8, ' '));</ |
(i * i).toString().padStart(8, ' '));</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> 1^2 = 1 |
<pre> 1^2 = 1 |
||
Line 621: | Line 621: | ||
=== Functional === |
=== Functional === |
||
< |
<syntaxhighlight lang="javascript">(() => { |
||
"use strict"; |
"use strict"; |
||
Line 678: | Line 678: | ||
// MAIN --- |
// MAIN --- |
||
return main(); |
return main(); |
||
})();</ |
})();</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
<pre>0, 1, 5, 6, 25, 76, 376, 625, 9376 |
<pre>0, 1, 5, 6, 25, 76, 376, 625, 9376 |
||
Line 695: | Line 695: | ||
{{works with|jq}} |
{{works with|jq}} |
||
'''Works with gojq, the Go implementation of jq''' |
'''Works with gojq, the Go implementation of jq''' |
||
< |
<syntaxhighlight lang="jq"># Input: an upper bound, or null for infinite |
||
def steady_squares: |
def steady_squares: |
||
range(0; . // infinite) |
range(0; . // infinite) |
||
Line 702: | Line 702: | ||
10000 |
10000 |
||
| steady_squares</ |
| steady_squares</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 717: | Line 717: | ||
=={{header|Julia}}== |
=={{header|Julia}}== |
||
< |
<syntaxhighlight 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] |
println(filter(issteadysquare, 1:10000)) # [1, 5, 6, 25, 76, 376, 625, 9376] |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|MAD}}== |
=={{header|MAD}}== |
||
< |
<syntaxhighlight lang="mad"> NORMAL MODE IS INTEGER |
||
VECTOR VALUES FMT = $I4,7H **2 = ,I8*$ |
VECTOR VALUES FMT = $I4,7H **2 = ,I8*$ |
||
THROUGH LOOP, FOR I=1, 1, I.G.10000 |
THROUGH LOOP, FOR I=1, 1, I.G.10000 |
||
Line 735: | Line 735: | ||
END OF CONDITIONAL |
END OF CONDITIONAL |
||
LOOP CONTINUE |
LOOP CONTINUE |
||
END OF PROGRAM</ |
END OF PROGRAM</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> 1**2 = 1 |
<pre> 1**2 = 1 |
||
Line 747: | Line 747: | ||
=={{header|Perl}}== |
=={{header|Perl}}== |
||
< |
<syntaxhighlight lang="perl">#!/usr/bin/perl |
||
use strict; # https://rosettacode.org/wiki/Steady_Squares |
use strict; # https://rosettacode.org/wiki/Steady_Squares |
||
use warnings; |
use warnings; |
||
($_ ** 2) =~ /$_$/ and printf "%5d %d\n", $_, $_ ** 2 for 1 .. 10000;</ |
($_ ** 2) =~ /$_$/ and printf "%5d %d\n", $_, $_ ** 2 for 1 .. 10000;</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 771: | Line 771: | ||
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> |
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. |
I stopped after 8 digits to avoid the need to fire up gmp. Finishes near-instantly, of course. |
||
<!--< |
<!--<syntaxhighlight lang="phix">(phixonline)--> |
||
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span> |
<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> |
<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 791: | Line 791: | ||
<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: #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> |
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span> |
||
<!--</ |
<!--</syntaxhighlight>--> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 813: | Line 813: | ||
=== mpz (super fast to 1000 digits) === |
=== 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. |
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. |
||
<!--< |
<!--<syntaxhighlight lang="phix">(phixonline)--> |
||
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span> |
<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> |
<span style="color: #008080;">include</span> <span style="color: #004080;">mpfr</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span> |
||
Line 850: | Line 850: | ||
<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: #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> |
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span> |
||
<!--</ |
<!--</syntaxhighlight>--> |
||
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. |
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}} |
{{out}} |
||
Line 886: | Line 886: | ||
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. |
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 === |
=== No Search Required using strings === |
||
<!--< |
<!--<syntaxhighlight lang="phix">(phixonline)--> |
||
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span> |
<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> |
<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 930: | Line 930: | ||
<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 < 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: #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 < 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> |
<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> |
||
<!--</ |
<!--</syntaxhighlight>--> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,001: | Line 1,001: | ||
=={{header|Python}}== |
=={{header|Python}}== |
||
===Procedural=== |
===Procedural=== |
||
< |
<syntaxhighlight lang="python">print("working...") |
||
print("Steady squares under 10.000 are:") |
print("Steady squares under 10.000 are:") |
||
limit = 10000 |
limit = 10000 |
||
Line 1,013: | Line 1,013: | ||
print(str(n) + " " + str(square)) |
print(str(n) + " " + str(square)) |
||
print("done...")</ |
print("done...")</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>working... |
<pre>working... |
||
Line 1,028: | Line 1,028: | ||
===Functional=== |
===Functional=== |
||
< |
<syntaxhighlight lang="python">'''Steady squares''' |
||
from itertools import chain |
from itertools import chain |
||
Line 1,080: | Line 1,080: | ||
# MAIN --- |
# MAIN --- |
||
if __name__ == '__main__': |
if __name__ == '__main__': |
||
main()</ |
main()</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
<pre>[1, 5, 6, 25, 76, 376, 625, 9376] |
<pre>[1, 5, 6, 25, 76, 376, 625, 9376] |
||
Line 1,095: | Line 1,095: | ||
Or, defining the squares as an additive accumulation: |
Or, defining the squares as an additive accumulation: |
||
< |
<syntaxhighlight lang="python">'''Steady Squares''' |
||
from itertools import accumulate, chain, count, takewhile |
from itertools import accumulate, chain, count, takewhile |
||
Line 1,120: | Line 1,120: | ||
# MAIN --- |
# MAIN --- |
||
if __name__ == '__main__': |
if __name__ == '__main__': |
||
main()</ |
main()</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
<pre>0 -> 0 |
<pre>0 -> 0 |
||
Line 1,133: | Line 1,133: | ||
=={{header|Raku}}== |
=={{header|Raku}}== |
||
<lang |
<syntaxhighlight lang="raku" line>.say for ({$++²}…*).kv.grep( {$^v.ends-with: $^k} )[1..10]</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>(1 1) |
<pre>(1 1) |
||
Line 1,147: | Line 1,147: | ||
=={{header|REXX}}== |
=={{header|REXX}}== |
||
< |
<syntaxhighlight lang="rexx">/* REXX */ |
||
Numeric Digits 50 |
Numeric Digits 50 |
||
Call time 'R' |
Call time 'R' |
||
Line 1,160: | Line 1,160: | ||
End |
End |
||
End |
End |
||
Say time('E')</ |
Say time('E')</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>Steady squares below 1000000000 |
<pre>Steady squares below 1000000000 |
||
Line 1,183: | Line 1,183: | ||
=={{header|Ring}}== |
=={{header|Ring}}== |
||
< |
<syntaxhighlight lang="ring"> |
||
see "working..." +nl |
see "working..." +nl |
||
see "Steady squatres under 10.000 are:" + nl |
see "Steady squatres under 10.000 are:" + nl |
||
Line 1,199: | Line 1,199: | ||
see "done..." +nl |
see "done..." +nl |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,217: | Line 1,217: | ||
== {{header|TypeScript}} == |
== {{header|TypeScript}} == |
||
{{trans|C}} |
{{trans|C}} |
||
< |
<syntaxhighlight lang="javascript">// Steady squares |
||
function steady(n: number): bool { |
function steady(n: number): bool { |
||
Line 1,231: | Line 1,231: | ||
console.log(i.toString().padStart(4, ' ') + "^2 = " + |
console.log(i.toString().padStart(4, ' ') + "^2 = " + |
||
(i * i).toString().padStart(8, ' ')); |
(i * i).toString().padStart(8, ' ')); |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,247: | Line 1,247: | ||
{{libheader|Wren-fmt}} |
{{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. |
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. |
||
< |
<syntaxhighlight lang="ecmascript">import "./fmt" for Fmt |
||
System.print("Steady squares under 10,000:") |
System.print("Steady squares under 10,000:") |
||
Line 1,255: | Line 1,255: | ||
var sq = i * i |
var sq = i * i |
||
if (sq.toString.endsWith(i.toString)) Fmt.print("$,5d -> $,10d", i, sq) |
if (sq.toString.endsWith(i.toString)) Fmt.print("$,5d -> $,10d", i, sq) |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,271: | Line 1,271: | ||
=={{header|XPL0}}== |
=={{header|XPL0}}== |
||
< |
<syntaxhighlight lang="xpl0">int N, P; |
||
[for N:= 0 to 10000-1 do |
[for N:= 0 to 10000-1 do |
||
[P:= 1; |
[P:= 1; |
||
Line 1,282: | Line 1,282: | ||
]; |
]; |
||
]; |
]; |
||
]</ |
]</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,298: | Line 1,298: | ||
=={{header|Yabasic}}== |
=={{header|Yabasic}}== |
||
< |
<syntaxhighlight lang="yabasic">// Rosetta Code problem: http://rosettacode.org/wiki/Steady_squares |
||
// by Galileo, 04/2022 |
// by Galileo, 04/2022 |
||
Line 1,304: | Line 1,304: | ||
r$ = str$(i^2, "%9.f") |
r$ = str$(i^2, "%9.f") |
||
if i = val(right$(r$, len(str$(i)))) print i, "\t=", r$ |
if i = val(right$(r$, len(str$(i)))) print i, "\t=", r$ |
||
next</ |
next</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>1 = 1 |
<pre>1 = 1 |
Revision as of 16:56, 28 August 2022
- Euler Project #284
- Task
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
ALGOL 68
Using the observation that the final digit must be 1, 5 or 6 (See Talk page).
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
- Output:
1^2 = 1 5^2 = 25 6^2 = 36 25^2 = 625 76^2 = 5776 376^2 = 141376 625^2 = 390625 9376^2 = 87909376
AWK
# syntax: GAWK -f STEADY_SQUARES.AWK
BEGIN {
start = 1
stop = 999999
for (i=start; i<=stop; i++) {
n = i ^ 2
if (n ~ (i "$")) {
printf("%6d^2 = %12d\n",i,n)
count++
}
}
printf("\nSteady squares %d-%d: %d\n",start,stop,count)
exit(0)
}
- Output:
1^2 = 1 5^2 = 25 6^2 = 36 25^2 = 625 76^2 = 5776 376^2 = 141376 625^2 = 390625 9376^2 = 87909376 90625^2 = 8212890625 109376^2 = 11963109376 890625^2 = 793212890625 Steady squares 1-999999: 11
BASIC
ASIC
Compile with the Extended math option.
REM Steady squares
FOR I = 1 TO 9999
N = I
GOSUB CheckIfSteady:
IF Steady <> 0 THEN
PRINT I;
PRINT " ^ 2 = ";
II& = I * I
PRINT II&
ENDIF
NEXT I
END
CheckIfSteady:
REM Result: Steady = 1 if N * N is steady; Steady = 0 otherwise.
Mask = 1
D = N
WHILE D <> 0
Mask = Mask * 10
D = D / 10
WEND
NNModMask& = N * N
NNModMask& = NNModMask& MOD Mask
IF NNModMask& = N THEN
Steady = 1
ELSE
Steady = 0
ENDIF
RETURN
- Output:
1 ^ 2 = 1 5 ^ 2 = 25 6 ^ 2 = 36 25 ^ 2 = 625 76 ^ 2 = 5776 376 ^ 2 = 141376 625 ^ 2 = 390625 9376 ^ 2 = 87909376
FreeBASIC
function numdig( byval n as uinteger ) as uinteger
'number of decimal digits in n
dim as uinteger d=0
while n
d+=1
n\=10
wend
return d
end function
function is_steady_square( n as const uinteger ) as boolean
dim as integer n2 = n^2
if n2 mod 10^numdig(n) = n then return true else return false
end function
for i as uinteger = 1 to 10000
if is_steady_square(i) then print using "####^2 = ########";i;i^2
next i
- Output:
1^2 = 1 5^2 = 25 6^2 = 36 25^2 = 625 76^2 = 5776 376^2 = 141376 625^2 = 390625 9376^2 = 87909376
GW-BASIC
10 FOR N = 1 TO 10000
20 M$ = STR$(N)
30 M2#=N*N
40 M$ = RIGHT$(M$,LEN(M$)-1)
50 N2$ = STR$(M2#)
60 A = LEN(M$)
70 IF RIGHT$(N2$,A)= M$ THEN PRINT M$,N2$
80 NEXT N
- Output:
1 1 5 25 6 36 25 625 76 5776 376 141376 625 390625 9376 87909376
Liberty BASIC
rem Steady squares
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
- Output:
1 ^ 2 = 1 5 ^ 2 = 25 6 ^ 2 = 36 25 ^ 2 = 625 76 ^ 2 = 5776 376 ^ 2 = 141376 625 ^ 2 = 390625 9376 ^ 2 = 87909376
Tiny 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.
REM N = THE NUMBER TO BE SQUARED
REM D = 10^THE NUMBER OF DIGITS IN N
REM M = THE SQUARE OF N, MODULO D
REM T = TEMP COPY OF N
LET N = 1
LET D = 10
10 IF N > 9 THEN LET D = 100
IF N > 99 THEN LET D = 1000
IF N > 999 THEN LET D = 10000
LET M = 0
LET T = N
20 LET M = M + N
LET M = M - (M/D)*D
LET T = T - 1
IF T > 0 THEN GOTO 20
rem PRINT N, " ", M
IF M = N THEN PRINT N
LET N = N + 1
IF N < 10000 THEN GOTO 10
END
- Output:
1 5 6 25 76 376 625
9376
C
#include <stdio.h>
#include <stdbool.h>
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);
return 0;
}
- Output:
1^2 = 1 5^2 = 25 6^2 = 36 25^2 = 625 76^2 = 5776 376^2 = 141376 625^2 = 390625 9376^2 = 87909376
CLU
n_digits = proc (n: int) returns (int)
i: int := 0
while n>0 do
i := i+1
n := n/10
end
return(i)
end n_digits
steady = proc (n: int) returns (bool)
sq: int := n ** 2
return (sq // 10**n_digits(n) = n)
end steady
start_up = proc ()
po: stream := stream$primary_output()
for i: int in int$from_to(1, 10000) do
if ~steady(i) then continue end
stream$putright(po, int$unparse(i), 4)
stream$puts(po, "^2 = ")
stream$putright(po, int$unparse(i**2), 8)
stream$putl(po, "")
end
end start_up
- Output:
1^2 = 1 5^2 = 25 6^2 = 36 25^2 = 625 76^2 = 5776 376^2 = 141376 625^2 = 390625 9376^2 = 87909376
Draco
proc nonrec steady(ulong n) bool:
ulong mask;
mask := 1;
while mask <= n do mask := mask * 10 od;
n*n % mask = n
corp
proc nonrec main() void:
word i;
for i from 1 upto 10000 do
if steady(i) then
writeln(i:4, "^2 = ", make(i,ulong)*i:8)
fi
od
corp
- Output:
1^2 = 1 5^2 = 25 6^2 = 36 25^2 = 625 76^2 = 5776 376^2 = 141376 625^2 = 390625 9376^2 = 87909376
F#
The Function
Implements No Search Required. large values may be produced using only integers.
// 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)
let five,six=(5L,[|0L..9L|]),(6L,[|0L;9L;8L;7L;6L;5L;4L;3L;2L;1L|])
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,[])}
Some Examples
stdySq six|>Seq.take 80|>Seq.rev|>Seq.iter(printf "%d");printfn ""
stdySq five|>Seq.take 80|>Seq.rev|>Seq.iter(printf "%d");printfn ""
- Output:
61490109937833490419136188999442576576769103890995893380022607743740081787109376 38509890062166509580863811000557423423230896109004106619977392256259918212890625
- Confirming Phix's example for 999 digits (in 11 thousands of sec).
stdySq six|>Seq.skip 920|>Seq.take 79|>Seq.rev|>Seq.iter(printf "%d");printfn "..."
- Output:
7218745998663099139651109156359761242340631780203738180821664795072958006751247... Real: 00:00:00.011
- 9999 digits
stdySq six|>Seq.skip 9920|>Seq.take 79|>Seq.rev|>Seq.iter(printf "%d");printfn "...";;
- Output:
8908826164991254342660560818535016604238201034937718562215376152130910068662033... Real: 00:00:00.330
- If you have 57secs to spare then do 99999 digits, I leave it to the faithless to prove that this a Steady Square.
stdySq six|>Seq.skip 99920|>Seq.take 79|>Seq.rev|>Seq.iter(printf "%d");printfn "...";;
- Output:
2755643458676224038154570844433833690960332159243668007360724907611570195135435... Real: 00:00:57.520
Factor
Only checking numbers that end with 1, 5, and 6. See Talk:Steady_Squares for more details.
USING: formatting kernel math math.functions
math.functions.integer-logs prettyprint sequences
tools.memory.private ;
: steady? ( n -- ? )
[ sq ] [ integer-log10 1 + 10^ mod ] [ = ] tri ;
1000 <iota> { 1 5 6 } [
[ 10 * ] dip + dup steady?
[ dup sq commas "%4d^2 = %s\n" printf ] [ drop ] if
] cartesian-each
- Output:
1^2 = 1 5^2 = 25 6^2 = 36 25^2 = 625 76^2 = 5,776 376^2 = 141,376 625^2 = 390,625 9376^2 = 87,909,376
Fermat
Func Isstead( n ) =
m:=n;
d:=1;
while m>0 do
d:=d*10;
m:=m\10;
od;
if n^2|d=n then Return(1) else Return(0) fi.;
for i = 1 to 9999 do
if Isstead(i) then !!(i,'^2 = ',i^2) fi;
od;
- Output:
1^2 = 1 5^2 = 25 6^2 = 36 25^2 = 625 76^2 = 5776 376^2 = 141376 625^2 = 390625 9376^2 = 87909376
Go
package main
import (
"fmt"
"rcu"
"strconv"
"strings"
)
func contains(list []int, s int) bool {
for _, e := range list {
if e == s {
return true
}
}
return false
}
func main() {
fmt.Println("Steady squares under 10,000:")
finalDigits := []int{1, 5, 6}
for i := 1; i < 10000; i++ {
if !contains(finalDigits, i%10) {
continue
}
sq := i * i
sqs := strconv.Itoa(sq)
is := strconv.Itoa(i)
if strings.HasSuffix(sqs, is) {
fmt.Printf("%5s -> %10s\n", rcu.Commatize(i), rcu.Commatize(sq))
}
}
}
- Output:
Steady squares under 10,000: 1 -> 1 5 -> 25 6 -> 36 25 -> 625 76 -> 5,776 376 -> 141,376 625 -> 390,625 9,376 -> 87,909,376
Haskell
import Control.Monad (join)
import Data.List (isSuffixOf)
--------------- NUMBERS WITH STEADY SQUARES --------------
p :: Int -> Bool
p = isSuffixOf . show <*> (show . join (*))
--------------------------- TEST -------------------------
main :: IO ()
main =
print $
takeWhile (< 10000) $ filter p [0 ..]
- Output:
[0,1,5,6,25,76,376,625,9376]
or retaining the string pair when the test succeeds:
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 <>)
- Output:
0 -> 0 1 -> 1 5 -> 25 6 -> 36 25 -> 625 76 -> 5776 376 -> 141376 625 -> 390625 9376 -> 87909376
or obtaining the squares by addition, rather than multiplication:
import Control.Monad (join)
import Data.Bifunctor (bimap)
import Data.List (isSuffixOf)
--------------- NUMBERS WITH STEADY SQUARES --------------
steadyPair :: Int -> Int -> [(Int, (String, String))]
steadyPair a b =
[ (a, ab)
| let ab = join bimap show (a, b),
uncurry isSuffixOf ab
]
--------------------------- TEST -------------------------
main :: IO ()
main =
putStrLn $
unlines
( uncurry ((<>) . (<> " -> ")) . snd
<$> takeWhile
((10000 >) . fst)
( concat $
zipWith
steadyPair
[0 ..]
(scanl (+) 0 [1, 3 ..])
)
)
- Output:
0 -> 0 1 -> 1 5 -> 25 6 -> 36 25 -> 625 76 -> 5776 376 -> 141376 625 -> 390625 9376 -> 87909376
J
Implementation:
issteady=: {{ Y-:N{.":*:y[N=.-#Y=.":y }}"0
Task example:
I.issteady i.1e4
0 1 5 6 25 76 376 625 9376
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).
JavaScript
Procedural
// Steady squares
function steady(n) {
// Result: true if n * n is steady; false otherwise.
var mask = 1;
for (var d = n; d != 0; d = Math.floor(d / 10))
mask *= 10;
return (n * n) % mask == n;
}
for (var i = 1; i < 10000; i++)
if (steady(i))
console.log(i.toString().padStart(4, ' ') + "^2 = " +
(i * i).toString().padStart(8, ' '));
- Output:
1^2 = 1 5^2 = 25 6^2 = 36 25^2 = 625 76^2 = 5776 376^2 = 141376 625^2 = 390625 9376^2 = 87909376
Functional
(() => {
"use strict";
// ----------------- STEADY SQUARES ------------------
// isSteady :: Int -> Bool
const isSteady = n =>
Boolean(steadyPair(n).length);
// steadyPair :: Int -> [(String, String)]
const steadyPair = n => {
// An empty list if n is not steady, otherwise a
// list containing a tuple of (n, n^2) strings.
const
s = `${n}`,
s2 = `${n ** 2}`;
return s2.endsWith(s) ? [
[s, s2]
] : [];
};
// ---------------------- TESTS ----------------------
const main = () => {
const
range = enumFromTo(0)(1E4),
pairs = range.flatMap(steadyPair),
[w, w2] = pairs[pairs.length - 1]
.map(x => x.length);
return [
range.filter(isSteady).join(", "),
pairs.map(([n, n2]) => {
const
steady = n.padStart(w, " "),
square = n2.padStart(w2, " ");
return `${steady} -> ${square}`;
})
.join("\n")
]
.join("\n\n");
};
// --------------------- GENERIC ---------------------
// enumFromTo :: Int -> Int -> [Int]
const enumFromTo = m =>
n => Array.from({
length: 1 + n - m
}, (_, i) => m + i);
// MAIN ---
return main();
})();
- Output:
0, 1, 5, 6, 25, 76, 376, 625, 9376 0 -> 0 1 -> 1 5 -> 25 6 -> 36 25 -> 625 76 -> 5776 376 -> 141376 625 -> 390625 9376 -> 87909376
jq
Works with gojq, the Go implementation of jq
# Input: an upper bound, or null for infinite
def steady_squares:
range(0; . // infinite)
| tostring as $i
| select( .*. | tostring | endswith($i));
10000
| steady_squares
- Output:
0 1 5 6 25 76 376 625 9376
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]
MAD
NORMAL MODE IS INTEGER
VECTOR VALUES FMT = $I4,7H **2 = ,I8*$
THROUGH LOOP, FOR I=1, 1, I.G.10000
THROUGH POW, FOR MASK=1, 0, MASK.G.I
POW MASK = MASK*10
SQ = I*I
WHENEVER SQ-SQ/MASK*MASK.E.I
PRINT FORMAT FMT, I, SQ
END OF CONDITIONAL
LOOP CONTINUE
END OF PROGRAM
- Output:
1**2 = 1 5**2 = 25 6**2 = 36 25**2 = 625 76**2 = 5776 376**2 = 141376 625**2 = 390625 9376**2 = 87909376
Perl
#!/usr/bin/perl
use strict; # https://rosettacode.org/wiki/Steady_Squares
use warnings;
($_ ** 2) =~ /$_$/ and printf "%5d %d\n", $_, $_ ** 2 for 1 .. 10000;
- Output:
1 1 5 25 6 36 25 625 76 5776 376 141376 625 390625 9376 87909376
Phix
A number n ending in 2,3,4,7,8, or 9 will have a square ending in 4,9,6,9,4 or 1 respectively.
Further a number ending in k 0s will have a square ending in 2*k 0s, and hence always fail, so all possible candidates must end in 1, 5, or 6.
Further, the square of any k-digit number n will end in the same k-1 digits as the square of the number formed from the last k-1 digits of n,
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.
I stopped after 8 digits to avoid the need to fire up gmp. Finishes near-instantly, of course.
with javascript_semantics sequence success = {1,5,6} -- (as above) atom p10 = 10 for digits=2 to 8 do for d=1 to 9 do for i=1 to length(success) do atom cand = d*p10+success[i] if remainder(cand*cand,p10*10)=cand then success &= cand end if end for end for p10 *= 10 end for printf(1,"%d such numbers < 100,000,000 found:\n",length(success)) for i=1 to length(success) do atom si = success[i] printf(1,"%,11d^2 = %,21d\n",{si,si*si}) end for
- Output:
15 such numbers < 100,000,000 found: 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 90,625^2 = 8,212,890,625 109,376^2 = 11,963,109,376 890,625^2 = 793,212,890,625 2,890,625^2 = 8,355,712,890,625 7,109,376^2 = 50,543,227,109,376 12,890,625^2 = 166,168,212,890,625 87,109,376^2 = 7,588,043,387,109,376
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.
with javascript_semantics include mpfr.e constant limit = 1000 sequence success = {"1","5","6"} -- (as above) sequence squared = {"1","25","36"} -- (kiss) integer count = 3 mpz ch5 = mpz_init(5), -- the 5-chain ch6 = mpz_init(6), -- the 6-chain p10 = mpz_init(10), {d10,sqr,r10,t10,cand} = mpz_inits(5), ch for digits=2 to limit-1 do for d=1 to 9 do ch = ch5 mpz_mul_si(d10,p10,d) mpz_mul_si(t10,p10,10) for chain=5 to 6 do mpz_add(cand,d10,ch) mpz_mul(sqr,cand,cand) mpz_fdiv_r(r10,sqr,t10) if mpz_cmp(cand,r10)=0 then count += 1 if digits<=12 or digits>=limit-3 then success = append(success,shorten(mpz_get_str(cand))) squared = append(squared,shorten(mpz_get_str(sqr))) end if mpz_set(ch,cand) end if ch = ch6 end for end for mpz_mul_si(p10,p10,10) end for printf(1,"%d steady squares < 1e%d found:\n",{count,limit}) for i=1 to length(success) do printf(1,"%13s^2 = %25s\n",{success[i],squared[i]}) end for
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.
- Output:
1783 steady squares < 1e1000 found: 1^2 = 1 5^2 = 25 6^2 = 36 25^2 = 625 76^2 = 5776 376^2 = 141376 625^2 = 390625 9376^2 = 87909376 90625^2 = 8212890625 109376^2 = 11963109376 890625^2 = 793212890625 2890625^2 = 8355712890625 7109376^2 = 50543227109376 12890625^2 = 166168212890625 87109376^2 = 7588043387109376 212890625^2 = 45322418212890625 787109376^2 = 619541169787109376 1787109376^2 = 3193759921787109376 8212890625^2 = 67451572418212890625 18212890625^2 = 331709384918212890625 81787109376^2 = 6689131260081787109376 918212890625^2 = 843114912509918212890625 18745998663099139651...07743740081787109376 (997 digits)^2 = 35141246587691473110...07743740081787109376 (1,993 digits) 81254001336900860348...92256259918212890625 (997 digits)^2 = 66022127332570868008...92256259918212890625 (1,994 digits) 21874599866309913965...07743740081787109376 (998 digits)^2 = 47849811931116570591...07743740081787109376 (1,995 digits) 78125400133690086034...92256259918212890625 (998 digits)^2 = 61035781460491829128...92256259918212890625 (1,996 digits) 27812540013369008603...92256259918212890625 (999 digits)^2 = 77353738199525217326...92256259918212890625 (1,997 digits) 72187459986630991396...07743740081787109376 (999 digits)^2 = 52110293793214504525...07743740081787109376 (1,998 digits)
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 ch = ch5
and ch = ch6
lines.
No Search Required using strings
with javascript_semantics atom t0 = time() constant limit = 9999 sequence fivesix = {"5","6"} -- (held backwards) for chain=5 to 6 do string f56 = fivesix[chain-4] integer d0 = f56[1]-'0', d = 0, n = floor(d0*d0/10), dn = iff(chain=6?10-n:n) f56 &= dn+'0' for digit=2 to limit-1 do n = floor((n+d+2*dn*d0)/10) d = 0 for j=2 to digit do d += (f56[j]-'0')*(f56[-j+1]-'0') end for dn = remainder(n+d,10) if chain=6 and dn then dn=10-dn end if f56 &= dn+'0' end for fivesix[chain-4] = f56 end for integer count = 1 printf(1,"%13s\n",{"1"}) for d=1 to limit do sequence r = {} for j=1 to 2 do string fj = fivesix[j] if fj[d]!='0' then count += 1 if d<=12 then r &= {sprintf("%13s",{reverse(fj[1..d])})} elsif d=999 or d=9999 then r &= {sprintf("%s...%s (%d digits)",{reverse(fj[d-19..d]),reverse(fj[1..20]),d})} end if end if end for if length(r)>1 and r[2]<r[1] then r = reverse(r) end if for i=1 to length(r) do printf(1,"%s\n",{r[i]}) end for end for printf(1,"%d steady squares < 1e%d found\n",{count,limit+1}) ?elapsed(time()-t0)
- Output:
1 5 6 25 76 376 625 9376 90625 109376 890625 2890625 7109376 12890625 87109376 212890625 787109376 1787109376 8212890625 18212890625 81787109376 918212890625 27812540013369008603...92256259918212890625 (999 digits) 72187459986630991396...07743740081787109376 (999 digits) 10911738350087456573...92256259918212890625 (9999 digits) 89088261649912543426...07743740081787109376 (9999 digits) 18069 steady squares < 1e10000 found "4.0s"
Unfortunately it is not particularly fast, 7mins on a 10 year old i3 for 99,999 digits, with results
that match F#. Then again, I suppose it is a near-perfect candidate for my (far future) plans to
boost performance in version 2... Perhaps more for my future benefit than anyone else's, if we replace the for j=2 to digit do
loop with:
#ilASM{ mov esi,[f56] mov edx,[digit] mov ecx,1 shl esi,2 sub edx,1 xor eax,eax xor edi,edi @@: mov al,[esi+ecx] mov bl,[esi+edx] sub al,'0' sub bl,'0' mul bl add edi,eax xor eax,eax sub edx,1 add ecx,1 cmp edx,1 jge @b mov [d],edi xor ebx,ebx }
we get the above plus
27556434586762240381...07743740081787109376 (99999 digits) 72443565413237759618...92256259918212890625 (99999 digits) 179886 steady squares < 1e100000 found "12.2s"
Which is a whopping 35-fold speedup, so obviously all I need to do is make the compiler emit similarly efficient code...
Python
Procedural
print("working...")
print("Steady squares under 10.000 are:")
limit = 10000
for n in range(1,limit):
nstr = str(n)
nlen = len(nstr)
square = str(pow(n,2))
rn = square[-nlen:]
if nstr == rn:
print(str(n) + " " + str(square))
print("done...")
- Output:
working... Steady squares under 10.000 are: 1 1 5 25 6 36 25 625 76 5776 376 141376 625 390625 9376 87909376 done...
Functional
'''Steady squares'''
from itertools import chain
# steadyPair :: Int -> [(String, String)]
def steadyPair(x):
'''An empty list if x^2 is not suffixed, in decimal,
by the decimal digits of x. Otherwise a list
containing a tuple of the decimal strings of (x, x^2)
'''
s, s2 = str(x), str(x**2)
return [(s, s2)] if s2.endswith(s) else []
# ------------------------ TESTS -------------------------
# main :: IO ()
def main():
'''Roots of numbers with steady squares up to 10000
'''
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)])
print()
print(
'\n'.join([
f'{s.rjust(w, " ")} -> {s2.rjust(w2, " ")}'
for (s, s2) in xs
])
)
# ----------------------- GENERIC ------------------------
# concatMap :: (a -> [b]) -> [a] -> [b]
def concatMap(f):
'''A concatenated list over which a function has been
mapped.
The list monad can be derived by using a function f
which wraps its output in a list, (using an empty
list to represent computational failure).
'''
def go(xs):
return list(chain.from_iterable(map(f, xs)))
return go
# MAIN ---
if __name__ == '__main__':
main()
- Output:
[1, 5, 6, 25, 76, 376, 625, 9376] 1 -> 1 5 -> 25 6 -> 36 25 -> 625 76 -> 5776 376 -> 141376 625 -> 390625 9376 -> 87909376
Or, defining the squares as an additive accumulation:
'''Steady Squares'''
from itertools import accumulate, chain, count, takewhile
from operator import add
def main():
'''Numbers up to 10000 which have steady squares'''
print(
'\n'.join(
f'{a} -> {b}' for (a, b) in takewhile(
lambda ab: 10000 > ab[0],
enumerate(
accumulate(
chain([0], count(1, 2)),
add
)
)
) if str(b).endswith(str(a))
)
)
# MAIN ---
if __name__ == '__main__':
main()
- Output:
0 -> 0 1 -> 1 5 -> 25 6 -> 36 25 -> 625 76 -> 5776 376 -> 141376 625 -> 390625 9376 -> 87909376
Raku
.say for ({$++²}…*).kv.grep( {$^v.ends-with: $^k} )[1..10]
- Output:
(1 1) (5 25) (6 36) (25 625) (76 5776) (376 141376) (625 390625) (9376 87909376) (90625 8212890625) (109376 11963109376)
REXX
/* REXX */
Numeric Digits 50
Call time 'R'
n=1000000000
Say 'Steady squares below' n
Do i=1 To n
c=right(i,1)
If pos(c,'156')>0 Then Do
i2=i*i
If right(i2,length(i))=i Then
Say right(i,length(n)) i2
End
End
Say time('E')
- Output:
Steady squares below 1000000000 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 12890625 166168212890625 87109376 7588043387109376 212890625 45322418212890625 787109376 619541169787109376 468.422000
Ring
see "working..." +nl
see "Steady squatres under 10.000 are:" + nl
limit = 10000
for n = 1 to limit
nstr = string(n)
len = len(nstr)
square = pow(n,2)
rn = right(string(square),len)
if nstr = rn
see "" + n + " -> " + square + nl
ok
next
see "done..." +nl
- Output:
working... Steady numbers under 10.000 are: 1 -> 1 5 -> 25 6 -> 36 25 -> 625 76 -> 5776 376 -> 141376 625 -> 390625 9376 -> 87909376 done...
TypeScript
// Steady squares
function steady(n: number): bool {
// Result: true if n * n is steady; false otherwise.
var mask = 1;
for (var d = n; d != 0; d = Math.floor(d / 10))
mask *= 10;
return (n * n) % mask == n;
}
for (var i = 1; i < 10000; i++)
if (steady(i))
console.log(i.toString().padStart(4, ' ') + "^2 = " +
(i * i).toString().padStart(8, ' '));
- Output:
1^2 = 1 5^2 = 25 6^2 = 36 25^2 = 625 76^2 = 5776 376^2 = 141376 625^2 = 390625 9376^2 = 87909376
Wren
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.
import "./fmt" for Fmt
System.print("Steady squares under 10,000:")
var finalDigits = [1, 5, 6]
for (i in 1..9999) {
if (!finalDigits.contains(i % 10)) continue
var sq = i * i
if (sq.toString.endsWith(i.toString)) Fmt.print("$,5d -> $,10d", i, sq)
}
- Output:
Steady squares under 10,000: 1 -> 1 5 -> 25 6 -> 36 25 -> 625 76 -> 5,776 376 -> 141,376 625 -> 390,625 9,376 -> 87,909,376
XPL0
int N, P;
[for N:= 0 to 10000-1 do
[P:= 1;
repeat P:= P*10 until P>N;
if rem(N*N/P) = N then
[IntOut(0, N);
Text(0, "^^2 = ");
IntOut(0, N*N);
CrLf(0);
];
];
]
- Output:
0^2 = 0 1^2 = 1 5^2 = 25 6^2 = 36 25^2 = 625 76^2 = 5776 376^2 = 141376 625^2 = 390625 9376^2 = 87909376
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
- Output:
1 = 1 5 = 25 6 = 36 25 = 625 76 = 5776 376 = 141376 625 = 390625 9376 = 87909376 ---Program done, press RETURN---