38
\$\begingroup\$

Each term in the squaring sequence, \$x_n\$, is created by taking \$x_{n-1}\$, squaring it, and removing all but the first four digits.

The sequence always begins with \$x_1 = 1111\$. Squaring this yields \$1234321\$, so \$x_2 = 1234\$

The first few terms are:

1111
1234
1522
2316
5363
...

The Challenge

Your task is to, given a non-negative integer \$n\$, calculate \$x_n\$. You may submit a full program which performs I/O, or a function which takes \$n\$ as a parameter.

Your solution can be zero or one indexed, as long as you specify which.

Because all the terms in this sequence are shorter than 5 digits, your code should be as short as possible too. Standard loopholes apply.

May the best golfer win!


Test Cases

Note: These are 1-indexed.

1   -> 1111
8   -> 6840
15  -> 7584
20  -> 1425
80  -> 4717
\$\endgroup\$
5
  • 2
    \$\begingroup\$ Here's a related link :) \$\endgroup\$
    – FlipTack
    Commented Dec 2, 2016 at 18:56
  • 1
    \$\begingroup\$ This sequence could find use as a pseudo-random number generator (although it's not very secure). \$\endgroup\$
    – user100690
    Commented Mar 11, 2021 at 8:51
  • \$\begingroup\$ May we output as a string? \$\endgroup\$
    – user100690
    Commented Mar 17, 2021 at 16:18
  • \$\begingroup\$ @ophact IO is flexible. \$\endgroup\$
    – FlipTack
    Commented Mar 18, 2021 at 13:14
  • \$\begingroup\$ Any OEIS link for this? \$\endgroup\$
    – Wasif
    Commented Mar 21, 2021 at 8:14

64 Answers 64

1 2
3
0
\$\begingroup\$

J-uby, 28 bytes

0-indexed.

(~:**&2|S|~:[]&4&0|Z)+[1111]

Attempt This Online!

Explanation

(~:** & 2 | S | ~:[] & 4 & 0 | Z) + [1111]

(                               ) + [1111]  # Iterate n times starting with initial value 1111
 ~:** & 2 |                                 #   Square, then
            S |                             #   Convert to string, then
                ~:[] & 4 & 0 |              #   Get first 4 characters, then
                               Z            #   Convert to int
\$\endgroup\$
0
\$\begingroup\$

q, 26 bytes

{"J"$4#string x*x}/[;1111]

k, 18 bytes

{.:4#$x*x}/[;1111]
\$\endgroup\$
0
\$\begingroup\$

Python 3, 76 bytes

x=1111
n=int(input())
for y in range(n-1):
    x=int(str(x**2)[:4])
print(x)

Try it online!

\$\endgroup\$
0
\$\begingroup\$

><>, 40 36 bytes

"e"b*>$1-:@?!n:*v
%1:,av?  (*"dd":<-

Try it online!

Explanation

                   # we call the input n
"e"b*              # initialize number as 1111
     >$1-:@?!n     # calculate n-1, if 0 then print number
              :*v  # else, square and move to row 2
     v?  (*"dd":<- # if number is less than 10000, move to row 2
%1:,a              # else divide by 10 and mod away the decimals to get an int
\$\endgroup\$
1 2
3

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.