Steady squares

From Rosetta Code
Revision as of 09:57, 21 December 2021 by Thebigh (talk | contribs) (add FreeBASIC)
Steady squares is a draft programming task. It is not yet considered ready to be promoted as a complete task, for reasons that should be found in its talk page.
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

FreeBASIC

<lang 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</lang>

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

Python

<lang python> 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...") </lang>

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...

Ring

<lang 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 </lang>

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...

Wren

Library: 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 0, 1, 5 or 6. <lang ecmascript>import "./fmt" for Fmt

System.print("Steady squares under 10,000:") var finalDigits = [0, 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)

}</lang>

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