# The Squaring Sequence

Each term in the squaring sequence, xn, is created by taking xn-1, squaring it, and removing all but the first four digits.

The sequence always begins with x1 = 1111. Squaring this yields 1234321, so x2 = 1234

The first few terms are:

1111
1234
1522
2316
5363
...


# The Challenge

Your task is to, given a non-negative integer n, calculate xn. 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


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

• You can save some bytes by using x*=x; instead of Math.pow. – adrianmp Dec 2 '16 at 20:36
• and put that whole stuff in for loops instead of while loops. – Olivier Grégoire Dec 3 '16 at 14:41
• 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 ;) – Olivier Grégoire Dec 3 '16 at 14:54
• 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 – Xanderhall Dec 5 '16 at 13:01

## 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
A=                       And assign to A$] END FOR ?A Print the latest value of A$, end


Verified for all test cases.

# 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
%


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

@
iget #0
(
genc@
join "" tk 4 ^ #0 2
) 1111


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

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

• Please note that there's already a python answer here. – FlipTack Dec 3 '16 at 13:56
• @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 – sonrad10 Dec 3 '16 at 14:05
• 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. – FlipTack Dec 3 '16 at 14:09
• @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 – sonrad10 Dec 3 '16 at 14:17

# Minkolang v0.15, 4340 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


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

• 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;} – ETHproductions Dec 4 '16 at 4:36

# 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
)


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

# RProgN, 19 Bytes Non-Competing

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

Non-Competing because a lot of the sugar that this uses was added after this challenge was created.

## 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!

# 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



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