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
    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
    Mar 11, 2021 at 8:51
  • \$\begingroup\$ May we output as a string? \$\endgroup\$
    – user100690
    Mar 17, 2021 at 16:18
  • \$\begingroup\$ @ophact IO is flexible. \$\endgroup\$
    – FlipTack
    Mar 18, 2021 at 13:14
  • \$\begingroup\$ Any OEIS link for this? \$\endgroup\$
    – Wasif
    Mar 21, 2021 at 8:14

64 Answers 64

2
\$\begingroup\$

Japt -mh, 9 bytes

T=Â4î1wT²

Try it

T=Â4î1wT²     :Implicit map of range [0,input)
T=            :Assign to variable T (initially 0)
  Â           :Bitwise NOT of bitwise NOT of (i.e., cast to an integer)
   4î         :Mould to length 4 string
     1w       :  Maximum of 1 and
       T²     :  T squared
              :Implicit output of final result

No Flags, 12 10 bytes

1-indexed, returning a string

@4îX*X}g1ì

Try it

@4îX*X}g1ì     :Implicit input of input of integer U
@              :Function taking an integer X as argument
 4îX*X         :  Mould X*X to length 4
      }        :End function
       g       :Repeatedly take the last element of the following array, pass it through that function, push the result and return the Uth element
        1ì     :  Convert 1 to digit array
\$\endgroup\$
1
\$\begingroup\$

CJam, 15 bytes

'14*ri{i2#s4<}*

Uses 0-based indexing.

Try it online!

\$\endgroup\$
1
\$\begingroup\$

Perl 6, 36 bytes

{(1111,{+$_².substr(0,4)}...*)[$_]}

Explanation:

{                                 } # bare block lambda
  1111,                  ...        # sequence generator
                            *       # without a limit
       {                }           # lambda used to generate the next value
         $_²                        # start by squaring the previous value
            .substr(0,4)            # take only the first four digits
        +                           # make it numeric ( not necessary )
 (                           )[$_]  # return the requested value

Test:

say {(1111,{+$_².substr(0,4)}...*)[$_]}( 1,8,15,20,80 X- 1 ).perl
# (1111, 6840, 7584, 1425, 4717)
\$\endgroup\$
1
\$\begingroup\$

GNU Awk, 41 bytes

Pretty straightforward since you can easily mix math and string manipulations.

{for(x=1111;--$1;x=substr(x*x,1,4));}$1=x

Accepts zero or more positive numbers n (1-indexed), one number per line, on stdin. Outputs results xn, one result per line, on stdout.

Sample input/output:

% awk -f sqrseq.awk
1
1111
8
6840
15
7584
20
1425
80
4717
%
\$\endgroup\$
1
\$\begingroup\$

Matlab, 79, 78 Bytes

function a=s(n)
if n<2;a=1111; else f=s(n-1);a=fix(f^2/10^(3+(f>1e7^.5)));end

Test cases:

s(79) = 2172
s(49) = 8059
s(6)  = 2876

Not an amazing solution. I'm sure there must be a better way to truncate to 4 digits but I don't know today.

Edit: Shaved a byte by setting 0.5 -> .5

\$\endgroup\$
1
\$\begingroup\$

Java 8, 77 93 74 71 69 78 bytes

int n=1111;int m=1;while(x>m++){n=Integer.parseInt((n*n+"").substring(0,4));}

x->{int n=1111;int m=1;while(x>m++){n=Integer.parseInt((n*n+"").substring(0,4))‌​;}return n;}

x->{int n=1111;for(;--x>0;){n=Integer.parseInt((n*n+"").substring(0,4));}}

x->{long n=1111;for(;--x>0;){n=Long.valueOf((n*n+"").substring(0,4));}}

x->{long n=1111;for(;--x>0;)n=Long.valueOf((n*n+"").substring(0,4));return n;}

Each repetition makes n the first 4 characters of n*n.

Try Java online!

Post history:

  • 77 bytes: initial code (incomplete)

  • +16 bytes, by Olivier Grégoire: completed code by making it a Lambda function.

  • -19 bytes: replace while with for cycle.

  • -4 bytes: used longs instead of ints

  • -2 bytes, by Roman Gräf: removed unnecessary brackets

  • +9 bytes, missing return statement

Thanks to @OlivierGrégoire and @RomanGräf for pointing out some issues!

Wait, Java beats... (drumroll) Clojure and Matlab here! A big applause to Java please!

\$\endgroup\$
19
  • 2
    \$\begingroup\$ This answer is incomplete. x isn't declared. This should be a function or full program. Not a code snippet. \$\endgroup\$ Dec 2, 2016 at 22:04
  • \$\begingroup\$ @NonlinearFruit I was going for the function. Seems I missed this out. Do you mean I should just replace x with a number? \$\endgroup\$
    – user60199
    Dec 3, 2016 at 7:21
  • 1
    \$\begingroup\$ What @NonlinearFruit said is that your answer, with your current code, sould be: x->{int n=1111;int m=1;while(x>m++){n=Integer.parseInt((n*n+"").substring(0,4));}return n;} (for a total byte count of 91). This is because snippets aren't allowed: only functions or full programs. \$\endgroup\$ Dec 3, 2016 at 15:02
  • \$\begingroup\$ @OlivierGrégoire Isn't that 93 bytes? And thanks for pointing out lambda funcions. \$\endgroup\$
    – user60199
    Dec 3, 2016 at 15:26
  • \$\begingroup\$ You're right, it's 93 bytes, I must have checked from a previous, defect version. However, all I did was wrapping so that your program would be a valid entry. Now you can golf the hell out of it! For instance, here's a golfed version of your program for only 75 bytes: x->{Long n=1111;for(;--x>0;)n=n.valueOf((n*n+"").substring(0,4));return n;}, with several techniques used (used Long to be able to use Long.valueOf with less bytes, it's not recommended in normal programming, but totally in golfing; removed m as it's unnecessary if we decrease x instead, removed unneeded braces) \$\endgroup\$ Dec 3, 2016 at 15:37
1
\$\begingroup\$

Perl, 36 bytes

A different approach from the other Perl solution, leading to slightly shorter code. No command-line arguments are needed (other than the usual version selection argument, -M5.010, which doesn't count against the byte count), meaning that this is the same amount of code but with fewer penalties, giving a better overall score.

say+eval'($&*$&||1x4)=~/(....)/;'x<>

We create a loop Underload-style via repeating and eval-ing a string; I experimented with starting the string in the middle, but starting it at the start turns out to be shortest. We multiply $& (the result of the last regex match) by itself to square it; if the result's zero, we use 1x4 (i.e. 1111; Perl has an operator for repeating things, including digits of a number) instead of the result. Then we regex the first four characters. The whole thing runs in list context due to being inside say, thus the final result of the eval will be the contents of the parentheses of the final match.

\$\endgroup\$
1
\$\begingroup\$

Java, 79 67 66 64 bytes

  • Version 2.2/64 bytes:

Thanks to @Oliver Grégoire.

int a(int i){i=i<2?1111:a(--i);for(i*=i;i>1e4;)i/=10;return i;}
  • Version 2.1/66 bytes:

Thanks to @ETHProduction.

long a(long i){i=i<2?1111:a(--i);for(i*=i;i>1e4;)i/=10;return i;}
  • Version 2.0/67 bytes:

Replaced substring and stuff with the idea from @Xanderhall

long a(long i){i=i<2?1111:a(--i);i*=i;for(;i>1e4;)i/=10;return i;}
  • Version 1.0/79 bytes:

Although there are shorter solutions I wanted to post one recursive:). And I am the shortest "real" function:). Edit: Seems like I am the shortest now:)))

long a(long i){i=i<2?1111:a(--i);return Long.valueOf((i*i+"").substring(0,4));}
\$\endgroup\$
4
  • \$\begingroup\$ Can you do for(i*=i;i>1e4;)i/=10;? That would save a byte. \$\endgroup\$ Dec 3, 2016 at 19:50
  • \$\begingroup\$ Hmmm... Regarding your claim about the shortest Java function, this function would like to have some words ;-) \$\endgroup\$ Dec 4, 2016 at 0:02
  • \$\begingroup\$ Hmmm, thinking about it, why do you even use longs? You can kill two bytes by using ints. \$\endgroup\$ Dec 4, 2016 at 0:57
  • \$\begingroup\$ I missed that when I updated to 2.0 \$\endgroup\$ Dec 4, 2016 at 5:52
1
\$\begingroup\$

Java 8, 82 59 bytes

Saved 23 bytes thanks to help from commenters @adrianmp and @OlivierGrégoire

n->{int x=1111;while(--n>0)for(x*=x;x>1e4;x/=10);return x;}

Each iteration, we square the number, then loop and shrink it by factors of 10 until it's a 4 digit number. Repeat this process n times and return.

\$\endgroup\$
4
  • 2
    \$\begingroup\$ You can save some bytes by using x*=x; instead of Math.pow. \$\endgroup\$
    – adrianmp
    Dec 2, 2016 at 20:36
  • \$\begingroup\$ and put that whole stuff in for loops instead of while loops. \$\endgroup\$ Dec 3, 2016 at 14:41
  • \$\begingroup\$ Taking your algorithm and fixing a lot, I get 60 bytes: n->{int x=1111;for(;--n>0;)for(x*=x;x>1e4;x/=10);return x;}. I removed the y since we can decrease n, I used for loops, removed the braces and the biggest winner is what @adrianmp said, of course. Oh, and I made the problem 1-indexed, just like in the question, instead of 0-indexed as in your answer ;) \$\endgroup\$ Dec 3, 2016 at 14:54
  • \$\begingroup\$ you know, I honestly forgot that squaring a number was just x*x. I'm too used to the exponentiation operator in PHP ** and using Math.pow in Java. Also, my choice of while loops is usually if it doesn't change the byte count, like the first for loop \$\endgroup\$
    – Xanderhall
    Dec 5, 2016 at 13:01
1
\$\begingroup\$

Husk, 11 bytes

¡öd↑4d□1111

Try it online!

\$\endgroup\$
1
\$\begingroup\$

Stax, 8 bytes

å\S∩♪öH╠

Run and debug it

\$\endgroup\$
1
\$\begingroup\$

JavaScript, 35 bytes

n=>n?(''+f(n-1)**2).slice(0,4):1111

Zero-indexed. Outputs a string if n >= 0 and the number 1111 if n == 0.

\$\endgroup\$
1
\$\begingroup\$

><> (Fish), 59 bytes

1e4f*+f*+$v /a,:1%-11!.|
:*:$v!?:-1<$^?)+*f+*f+*f2e6a
 ;n$<

Try it

enter image description here

Explanation

Red loop repeatedly squares. Blue subloop divides by 10 while the value is greater than or equal to 10000.

1e4 is 1111 encoded as base 15. Then repeated f*+ sums it.

a6e2 is 10000 encoded as base 15.

I'm not sure if my base 15 encoding is optimal. Maybe some string encoding with base 255 would be better? But then how to properly add the elements? Hmm this could be a challenge.

\$\endgroup\$
1
  • 1
    \$\begingroup\$ Could you perhaps save some bytes by encoding the a6e2 as U+2710"✐"? \$\endgroup\$
    – emirps
    Dec 8, 2022 at 0:59
1
\$\begingroup\$

MathGolf, 8 bytes

1kƲ░4<i

Try it online.

Explanation:

1         # Push 1
 k        # Push the input-integer
  Æ       # Pop and loop that many times, using 5 characters as inner code-block:
   ²      #  Square the current integer
    ░     #  Convert it to a string
     4<   #  Pop and leave the first 4 characters/digits
       i  #  Convert it back to an integer
          # (after the loop, the entire stack is joined together and output implicitly)
\$\endgroup\$
1
\$\begingroup\$

Go, 79 bytes

func f(n int)int{i,a:=0,1111
for;i<n;i++{for s:=a*a;s>999;s/=10{a=s}}
return a}

Attempt This Online!

\$\endgroup\$
1
\$\begingroup\$

Thunno 2, 8 bytes

«¥[s{²4ɱ

Attempt This Online!

0-indexed.

Explanation

«¥[s{²4ɱ  # Implicit input
«¥[       # Push compressed integer 1111
   s{     # Repeat input number of times:
     ²    #  Square top of stack
      4ɱ  #  Take the first four characters
          # Implicit output
\$\endgroup\$
1
\$\begingroup\$

Julia 1.0, 42 bytes

!x=parse(Int,("$(1(x<2||!~-x)^2)"^4)[1:4])

Try it online!

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

QBIC, 43 41 bytes

#1111|:[a-1|f=!A! A=$LEFT$|(!f*f/z$,5)]?A

Way too much going on in here... Time to implement Substring in QBIC.

Explanation:

#1111|                     Define string constant A$ as '1111'
:                          Get CMD line param for N, called 'a'
[a-1|                      FOR 'b' = 1 to 'a'-1
  f=!A!                    Make 'f' be A$ cast to num

             f*f/z         Square 'f', and since we only want the first 4 digits,
                           divide it by 10 (z=10). This prevents that QBASIC 
                           switches to E^ notation because f^2 is too large
    $LEFT$|(!       $|,5)  Cast it to string, take the first 5 positions (QBASIC 
                           adds a leading space on cast-to-num...)
  A=                       And assign to A$
]                          END FOR
?A                         Print the latest value of A$, end

Verified for all test cases.

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

Wonder, 28 bytes

@:^#0(genc@><""tk4^#0 2)1111

Usage:

(@:^#0(genc@><""tk4^#0 2)1111)79

Simply gets the n th item from an infinite list of squaring sequence numbers. Zero-indexed.

More readable:

@
  iget #0
    (
      genc@
        join "" tk 4 ^ #0 2
    ) 1111
\$\endgroup\$
0
\$\begingroup\$

Pip, 13 bytes

Lao:(o*o)@<4o

1-indexed. Takes input as a command-line argument. Try it online!

Explanation

Same algorithm as most of the 1-indexed golflang answers.

               Implicit: a is 1st cmdline arg; o is 1
La             Loop a times:
  o:             Assign this expression to o:
         @<4     Leftmost four characters of
    (o*o)        o squared (parens necessary for precedence)
            o  Print final value of o

The first step, from 1 to 1111, works without any explicit string repetition: string slicing in Pip repeats the string as necessary until the slice index is valid. So "leftmost four characters of 1" gives 1111.

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

Python 3, 67 Bytes

Indexed at 1

a=1111
for _ in range(int(input())-1):a=str(int(a)**2)[:4]
print(a)

I was originally going to do this as a list comprehension, but I realised that I couldn't receive the last item in the list in order to square it.

\$\endgroup\$
4
  • \$\begingroup\$ Please note that there's already a python answer here. \$\endgroup\$
    – FlipTack
    Dec 3, 2016 at 13:56
  • \$\begingroup\$ @Flp.Tkc I realise that, but both that one and [this one][1] are using python 2, whereas this is python 3, which, i believe, counts as a separate language to the python 2 language, due to slightly different syntax rules. [1]: codegolf.stackexchange.com/a/101964/53336 \$\endgroup\$
    – AvahW
    Dec 3, 2016 at 14:05
  • \$\begingroup\$ Yes, they're different languages, but there's no point posting a python 3 solution when the python 2 one could just be trivially modified. \$\endgroup\$
    – FlipTack
    Dec 3, 2016 at 14:09
  • \$\begingroup\$ @Flp.Tkc I agree that the Python 2 answers could be modified easily to create a Python 3 answer, but A) This is python, so none of these answers are going to come close to winning (The smallest amount of Bytes that i've seen so far is 7). B) Before posting this answer I didn't look through the current answers, because I do these challenges just to keep my skills up, and I don't want to be influenced by other peoples answers, so I hadn't noticed there were already python answers here \$\endgroup\$
    – AvahW
    Dec 3, 2016 at 14:17
0
\$\begingroup\$

Minkolang v0.15, 43 40 33 bytes

'1111'nd?C[2;6ZrI4-[x]r6$Z]N.CxN.

0-indexed

Try it online! (for n=2)

Explanation

'1111'                            push this number
      n                           push input as number
       d                          duplicate
        ?                         check if it is 0:

If input is 0: (the reason 0 has to be handled specially is that otherwise Minkolang gets confused with the for-loops and 0iterations that you get an error)

         C                        start comment
           ... C                  end comment
                x                 delete value at top of stack (ie 0)
                 N.               output as number and end program

If input is > 0:

         C                        gets jumped over (since input is true)
          [               ]       start for-loop with the input as the number of iterations
           2;                      pushes 2, and raises the number by 2 (ie squares it)
             6Z                    converts number to string
               r                   reverses it
                I4-                pushes the length of the stack (ie the string value of the number) and subtracts it by 4 (so we now how many of the string to discard of)
                   [x]             discard the top of the stack by that many times
                      r            reverses stack
                       6$Z         converts it to a number
                                   for-loop ends
                           N.     output stack as number and end program
\$\endgroup\$
0
\$\begingroup\$

C, 53 52 bytes

a;s(n){return n?(a=s(n-1))*a/(a>3162?1e4:1e3):1111;}

Zero based. First timer - This is a recursive variation on the earlier solution (expressed in the same way), as requested.

\$\endgroup\$
2
  • \$\begingroup\$ Welcome to PPCG! Can you remove the outermost parentheses to save a byte? a;s(n){return n?(a=s(n-1))*a/(a>3162?1e4:1e3):1111;} \$\endgroup\$ Dec 4, 2016 at 4:36
  • \$\begingroup\$ you can make it one indexed for -2 bytes \$\endgroup\$
    – c--
    Jul 25, 2022 at 3:10
0
\$\begingroup\$

Scala, 44 bytes

Stream.iterate(1111)(n=>n*n+"" take 4 toInt)

This is an expression which evaluates to a Stream[Int], which is an infinte sequence of integers. In scala, Stream[A] extends (Int => A), which means that a Stream is a function from an index to the element at that index.

Explantion:

Stream.iterate( //create an infinite Sequence,
    1111        //starting with 1111,
  )(            //by calculating the next element with the following function:
    n=>
      n*n       //square the previous element
      +""       //convert it to a string
      take 4    //take the first 4 characters and drop the rest
      toInt     //convert the string back to an int
  )
\$\endgroup\$
0
\$\begingroup\$

Swift, 80 Bytes

func s(i:Int)->Int{var c=1111;for _ in 0..<i{c*=c;while c>9999{c/=10}};return c}

Ungolfed

func squaringSequence(index: Int) -> Int {
    var currentNum = 1111

    for _ in 0 ..< index {
        currentNum *= currentNum

        while currentNum > 9999 {
            currentNum /= 10
        }
    }

    return currentNum
}

Due to the pretty-verbose nature of string manipulation in Swift, in which converting an Int to a String, getting the first four characters, and converting back might look something like this:

let str = String(num);
num = Int(str[str.startIndex ..< str.index(str.startIndex, offsetBy: 4)])!

I'm opting to get the first four digits by dividing by 10 as needed.

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

Retina, 77 bytes

Sequence is zero-indexed. Doesn't work for n > 1 in TIO because of memory constraints. Byte count assumes ISO 8859-1 encoding.

$
¶1111
{`(?!0¶).+
$*
(?<=1¶(1*))1(?=(1*))
1$1$2
^1

M%`1
}`(\d{4}).*$
$1
0¶

Try it online

Explanation:

$                           # Append a newline and the starting number
¶1111
{`(?!0¶).+                  # Begin loop. If counter is not zero, convert numbers to unary
$*
(?<=1¶(1*))1(?=(1*))        # If the counter >= 1, replace each digit with entire number
1$1$2                       #   (This squares the number)
^1                          # Counter -= 1

M%`1                        # Convert each line's numbers back to decimal
}`(\d{4}).*$                # Keep only first four digits. End loop
$1
0¶                          # Remove the counter

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

Clojure, 70 bytes

#(first(drop %(iterate(fn[i](read-string(subs(str(* i i))0 4)))1111)))

Zero-based indexing. Iterates a function which returns first 4 characters of the string representation of the squared integer value.

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

C++ (clang), 52 bytes

void s(int&n){n=--n?s(n),n*n/1e3/(n<3163?:10):1111;}

Port of Lynn's C answer using recursion, is 1 indexed and returns via out parameter.

Try it online!

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

brev, 66 bytes

(fn(eif x(strse*((fn(* x x))(f(- x 1)))"^...."(m 0)0)1111))

There's no square unless I import the math lib so (fn(* x x)) had to do. Using a regex to yank the first four digits. This is zero-indexed.

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

RProgN, 19 Bytes

~{2^''.4m14¢}\*1\C

RProgN continues to be amazing average! Although it easily passes the score of verbose languages, it still chokes in comparison to other golfier languages.

Explained

~{2^''.4m14¢}\*1\C  # Main link
~                    # Zero Space Segment
 {          }       # Define anonymous function
  2^                # Square the top of the stack
    ''.             # Convert to a string.
       4m           # Repeated 4 times.
         14¢        # Push back only the first 4 letters.
             \*     # Multiplied by the implicit input, Creating another anonymous function that calls this one n times.
               1\C  # Push 1 to the stack, and call the chained function.

Try it Online!

\$\endgroup\$

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.