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
caird coinheringaahing
50.8k11 gold badges133 silver badges363 bronze badges
asked Dec 2, 2016 at 18:53
\$\endgroup\$
5
  • 2
    \$\begingroup\$ Here's a related link :) \$\endgroup\$ 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\$ Commented Mar 11, 2021 at 8:51
  • \$\begingroup\$ May we output as a string? \$\endgroup\$ Commented Mar 17, 2021 at 16:18
  • \$\begingroup\$ @ophact IO is flexible. \$\endgroup\$ Commented Mar 18, 2021 at 13:14
  • \$\begingroup\$ Any OEIS link for this? \$\endgroup\$ Commented Mar 21, 2021 at 8:14

64 Answers 64

1
2 3
25
\$\begingroup\$

JavaScript (ES7), (削除) 44 (削除ここまで) (削除) 43 (削除ここまで) 36 bytes

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

This is a great example of abusing type coercion: ** converts both its arguments to numbers, and + converts both its arguments to strings unless they're both numbers. This means that f(n)**2+f first converts f(n) to a number and squares it, then concatenates the result with the string representation of f. We can then use .slice to retrieve the first 4 chars of the string.

Here are a few alternate approaches that don't use strings:

f=(n,x=1111)=>x<1e4?--n?f(n,x*x):x:f(n,x/10|0)
f=n=>--n?(x=f(n))*x/(x>3162?1e4:1e3)|0:1111

Test snippet

let f=n=>--n?(Math.pow(f(n),2)+f).slice(0,4):1111
<input id=I type="number" step="1" min="1" value="1"><button onclick="console.log(f(I.value))">Run</button>

Note: this uses Math.pow because ** isn't supported in all browsers.

answered Dec 2, 2016 at 19:10
\$\endgroup\$
1
  • \$\begingroup\$ If we can output as a string, then n=>n?(''+f(n-1)**2).slice(0,4):1111 should work for 35 bytes \$\endgroup\$ Commented Mar 17, 2021 at 16:20
13
\$\begingroup\$

05AB1E, (削除) 8 (削除ここまで) 7 bytes

Code:

$Fn×ばつ

Explanation:

$ # Push 1 and the input
 F # Input times do...
 n # Square the number
 ×ばつ # Repeat that string 4 times
 4£ # Take the first four characters
 # Output the last computed number

Uses the CP-1252 encoding. Try it online!

answered Dec 2, 2016 at 18:59
\$\endgroup\$
2
  • 7
    \$\begingroup\$ Beat me by 20 seconds :(. \$\endgroup\$ Commented Dec 2, 2016 at 19:01
  • \$\begingroup\$ ×4£ can be now for -2 bytes. \$\endgroup\$ Commented Nov 23, 2022 at 8:27
7
\$\begingroup\$

Python 2, (削除) 51 (削除ここまで) (削除) 46 (削除ここまで) 44 Bytes

(削除) I'd like to get rid of the clunky if if possible, but I think an exec could be shorter.. (削除ここまで) Turns out for the moment that exec is shorter. Wrong again! The recursive function returns. This is one-indexed.

f=lambda n:1111*(n<2)or int(`f(n-1)**2`[:4])

An aleternative 46-byte solution with exec:

s=1111;exec's=int(`s*s`[:4]);'*input();print s

An alternative 49-byte recursive solution:

f=lambda n,s=1111:s*0**n or f(n-1,int(`s*2`[:4]))

Thanks to Flp.Tkc for saving a byte by reminding me that squaring doesn't need exponentiation :)

answered Dec 2, 2016 at 19:01
\$\endgroup\$
3
  • \$\begingroup\$ Another 46 bytes solution: f=lambda n:1111if n<2else int(`f(n-1)**2`[:4]) \$\endgroup\$ Commented Dec 2, 2016 at 19:36
  • \$\begingroup\$ @daHugLenny that can actually be 45: repl.it/EejD \$\endgroup\$ Commented Dec 2, 2016 at 19:47
  • 2
    \$\begingroup\$ @Flp.Tkc And that can actually be 44 ;) \$\endgroup\$ Commented Dec 5, 2016 at 14:00
6
\$\begingroup\$

Haskell, 40 bytes

((iterate(read.take 4.show.(^2))1111)!!)

It's a 0-based sequence. Usage example: ((iterate(read.take 4.show.(^2))1111)!!) 79 -> 4717.

How it works:

iterate ( ) 1111 -- repeatedly apply a function starting
 -- with 1111 and collect the results in a list
 -- the function is
 (^2) -- square
 show -- turn into string
 take 4 -- take the first 4 chars
 read -- turn back to number
 !! -- finally pick the nth element from the list 
answered Dec 2, 2016 at 19:10
\$\endgroup\$
6
\$\begingroup\$

Perl, 37 bytes

36 bytes of code + -p flag.

$\=1x4;$\=substr$\*$,0,4円while--$_}{

To run it:

perl -pe '$\=1x4;$\=substr$\*$,0,4円while--$_}{' <<< 80
answered Dec 2, 2016 at 19:14
\$\endgroup\$
6
\$\begingroup\$

V, 19 bytes

4é1Àñ|C="*"
5|D

Try it online!

This uses 0-based indexing.

Of course, since numbers aren't exactly V's forte, this isn't very golfy. However, it does show one nice advantage V has over vim. You can run a macro 0 times, which is not possible in vim since '0' is a command not a count.

This contains many unprintable characters, so here is a hexdump:

0000000: 34e9 31c0 f17c 4312 3d12 222a 1222 0a1b 4.1..|C.=."*."..
0000010: 357c 44 5|D

And here is a readable version:

4é1Àñ|C<C-r>=<C-r>"*<C-r>"
<esc>5|D

Explanation:

4 " 4 times:
 é1 " Insert a '1'
 Àñ " Arg1 times:
 | " Move to the first character on this line
 C " Delete this whole line and enter insert mode
 <C-r>= " Insert the following evaluated as vimscript:
 <C-r>" " Insert what we just deleted
 * " Times
 <C-r>" " What we just deleted
<esc> " Escape to normal mode
 5| " Move to the fifth column on this line
 D " And delete until the end of this line
 " The second 'ñ' is added implicitly
answered Dec 2, 2016 at 19:12
\$\endgroup\$
6
\$\begingroup\$

Mathematica, 48 bytes

Nest[⌊10^(3-⌊t=2Log[10,#]⌋+t)⌋&,1111,#]&

Unnamed function taking an integer argument; 0-indexed. Uses four three-byte characters ⌊⌊⌋⌋: Mathematica uses either Floor[x] or ⌊x⌋ to round a real number down to an integer, and the latter is generally one fewer byte. The command names in Mathematica for converting integers to strings are too long, so instead we do a mathematical calculation to find the first four digits of x^2: we take the base-10 logarithm of x^2, subtract its integer part, raise 10 back to that power, and multiply by 1000 and round down.

tl;dr: logarithms ftw

answered Dec 2, 2016 at 20:12
\$\endgroup\$
6
\$\begingroup\$

Jelly, (削除) 12 (削除ここまで) 9 bytes

-3 bytes thanks to Dennis using 1-based indexing and the mold/reshape atom. Golfing suggestions welcome! Try it online!

2Dṁ4Ḍ
1Ç¡

Ungolfing

Helper link
2 Square.
 D Integer to decimal (a list of digits).
 ṁ4 Mold/reshape list_of_digits to be 4 digits long.
 Ḍ Decimal to integer.
Main link: implicit left argument n
1 Start with the nilad 1.
 Ç¡ Call the helper link n times.
answered Dec 2, 2016 at 19:24
\$\endgroup\$
4
  • \$\begingroup\$ This saves 3 bytes with 1-based indexing. \$\endgroup\$ Commented Dec 2, 2016 at 19:31
  • \$\begingroup\$ Uh, I don't think you can use 1 instead of (¡n. \$\endgroup\$ Commented Jan 28, 2018 at 10:35
  • \$\begingroup\$ @EriktheOutgolfer How come? \$\endgroup\$ Commented Jan 28, 2018 at 16:09
  • \$\begingroup\$ @Sherlock9 Oh, you seem to 1-index this sequence? Hm, looks like the code is a bit tricky to understand... \$\endgroup\$ Commented Jan 28, 2018 at 16:18
5
+100
\$\begingroup\$

APL (Dyalog Extended), 13 bytes

-2 (changing the input method) thanks to @Razetime

{⍎4⍴⍕⍵*2}⍣⎕⊢1

Explanation:

{⍎4⍴⍕⍵*2}⍣⎕⊢1 ⍝ apply the dfn input times
 1 ⍝ .. with initial argument 1
 ⍵*2 ⍝ current value squared
 ⍎4⍴⍕ ⍝ take first 4 digits

Try it online!

answered Dec 20, 2020 at 19:27
\$\endgroup\$
1
  • 1
    \$\begingroup\$ -2 \$\endgroup\$ Commented Dec 22, 2020 at 9:36
4
\$\begingroup\$

Powershell, (削除) 73 (削除ここまで) 55 bytes

Huge thanks to TimmyD for shaving off 18 bytes!

Code:

for($A=1111;$args[0]---1;$A=-join"$(+$A*$A)"[0..3]){}$A

(削除) $A=1111;1..($n=2)|%{[string]$B=[math]::pow($A,2);$A=$B.substring(0,4)};$A (削除ここまで)

$n is n in xn-1

Explanation and exploded code:

$A=1111 #starting number
$n=4 #n in formula
for($i=0; $i -lt $n;$i++) #loop n times
{
 [string]$B=[math]::pow($A,2) #create a new string $B and set it to $A raised to the power of 2
 $A=$B.substring(0,4) #set $A to the first 4 characters of $B
}
$A #print $A

Some notes:

  • Powershell lets you assign variables in the same statements where you reference them. For example, 1..($n=4)|% will set $n to 4 and then start a loop that runs $n times. 1 can be changed to any integer and it will loop $n-[your integer]+1 times.
  • The default data type when using [math]:: in Powershell is a double. In the code above, we have to explicitly cast $B to a string so that we can call .substring() on it because there is no .substring() function for doubles in Powershell.
answered Dec 2, 2016 at 19:17
\$\endgroup\$
0
4
\$\begingroup\$

Python 2, (削除) 44 (削除ここまで) 41 bytes

-3 bytes thanks to xnor (use an integer division to avoid and)

f=lambda n:int(1/n*1111or`f(n-1)**2`[:4])

repl.it

1-based recursive function.

When n>1 the integer division, 1/n, results in 0, then 0*1111=0 which is falsey, so the right of the or is evaluated, which takes the first four characters of the representation of the square of the n-1th result; this is then cast to an int.

When n=1 the integer division, 1/n, results in 1, then 1*1111=1111, which is truthy, and the int 1111 cast to an int is 1111.

answered Dec 2, 2016 at 20:49
\$\endgroup\$
6
  • \$\begingroup\$ Good one, ninja'd me by one byte! \$\endgroup\$ Commented Dec 2, 2016 at 20:51
  • \$\begingroup\$ I just looked for your answer and then realised you wrote the challenge! Nice job. \$\endgroup\$ Commented Dec 2, 2016 at 20:56
  • 1
    \$\begingroup\$ Nice idea with taking the int outside. If you 1-index, you can do the base case shorter with g=lambda n:int(1/n*1111or`g(n-1)**2`[:4]). \$\endgroup\$ Commented Dec 2, 2016 at 21:51
  • 2
    \$\begingroup\$ "Crossed out 44 still looks like 44 :(" \$\endgroup\$ Commented Dec 2, 2016 at 22:23
  • 2
    \$\begingroup\$ @Flp.Tkc not as much as it does without the &nbsp;s! \$\endgroup\$ Commented Dec 2, 2016 at 22:25
3
\$\begingroup\$

Groovy, 49 bytes

{x=1111;(it-1).times{x="${x**2}"[0..3] as int};x}
answered Dec 2, 2016 at 19:06
\$\endgroup\$
3
\$\begingroup\$

Pyke, 10 bytes

1RVX`4*4<b

Try it here!

answered Dec 2, 2016 at 19:23
\$\endgroup\$
3
\$\begingroup\$

MATL, (削除) 14 (削除ここまで), 13 bytes

1111G:"UV4:)U

Try it online!

Explanation:

1111 % Push 1111
 G % Push input
 :" % Input times:
 U % Square the top of the stack
 V % Convert it to a string
 4:) % Take the first four digits
 U % Convert it back to a number
 % Implictly display
answered Dec 2, 2016 at 19:18
\$\endgroup\$
2
  • 2
    \$\begingroup\$ You can use U (square, for numeric input) insted of t* \$\endgroup\$ Commented Dec 2, 2016 at 20:12
  • 1
    \$\begingroup\$ @LuisMendo Thanks for reminding of the function I recommended! :P \$\endgroup\$ Commented Dec 2, 2016 at 21:21
3
\$\begingroup\$

R, (削除) 58 (削除ここまで) (削除) 56 (削除ここまで) (削除) 55 (削除ここまで) 53 bytes

x=3334;for(e in N<-scan():1)x=x^2%/%10^(3+(x>3162));x

Takes N from stdin. 3334 is practically X_0, which is needed because the for-loop needs to be executed at least once (it would be longer to skip).

R really is a terrible language for taking the first four digits of a number, but since the number of cases are limited, we only have to worry about the squares of x<3163 and x>3162, the former yield a 6 digit number, the latter a 7 digit number.

The rest is pretty straightforward, %/% divides and ignores the remainder. x is printed to stdout.

Saved 2 bytes thanks to @ETHproductions

answered Dec 2, 2016 at 22:02
\$\endgroup\$
3
  • \$\begingroup\$ This is so notrivial. Brilliant! \$\endgroup\$ Commented Dec 3, 2016 at 2:02
  • 1
    \$\begingroup\$ Nice one! What would happen if you started with 3334 (or perhaps 3333)? \$\endgroup\$ Commented Dec 3, 2016 at 2:16
  • \$\begingroup\$ @ETHproductions 3333^2 = 11108889 so would yield 1110, and .... as im checking this I see 3334 would work :| . Not sure why I didn't check that anymore. \$\endgroup\$ Commented Dec 3, 2016 at 9:44
3
\$\begingroup\$

Javagony - 153 bytes

Javagony is a restricted version of Java, that doesn't allow any control flow except recursion and try-catch, no for loops, while loops, or if's. Coding in it is a pretty fun exercise, but frustrating. Not that regular Java isn't nearly as frustrating by itself.

int a(int i){return a(i-1,1111);}int a(int i,int n){try{int x=1/i;return a(i-1,Integer.parseInt((n*n+"").substring(0,4)));}catch(Exception e){return n;}}
answered Dec 4, 2016 at 20:05
\$\endgroup\$
3
\$\begingroup\$

PHP, (削除) 55 (削除ここまで) 52 bytes

Saved 3 bytes thanks to @user59178

for($i=1111;$argv[1]--;)$i=substr($i**2,0,4);echo$i;

Run from command line, zero-indexed.

Thanks for not caring about what type my variables are, PHP! Here we simply square the number and trim off everything past the first 4 digits, casually alternating between number and string without a care in the world.

answered Dec 2, 2016 at 19:11
\$\endgroup\$
1
  • \$\begingroup\$ You could save 3 bytes by using $argv[1]-- as the loop counter. \$\endgroup\$ Commented Dec 5, 2016 at 9:36
3
\$\begingroup\$

cQuents, 14 bytes

=1111:(ZZ)[:4]

Try it online!

1-indexed.

Explanation

=1111 first term is 1111
 : given n, output nth term, otherwise output full sequence
 each term equals
 (ZZ) previous term * previous term
 [:4] [:4] (python slicing)
answered Jul 24, 2022 at 5:41
\$\endgroup\$
1
  • \$\begingroup\$ Really nice showcase of this language's abilities! \$\endgroup\$ Commented Aug 25, 2022 at 18:18
3
\$\begingroup\$

Pushy, 20 bytes

1111@:2esL4-:.;Kjk;#

Try it online!

Note this is 1-indexed.

 % Implicit: N is on stack
1111@ % Push 1111, and then reverse stack to get [1111, n]
: % N times do: (this consumes N)
 2e % Square last term
 s % Split into individual digits
 L4-:.; % Get stack length -4, pop that many times
 Kj % Join remaining digits (Uses flag "K" for whole stack)
 k % Set "K" flag to false, so operations only affect last item
; % End loop. 
# % Output final calculated term
answered Dec 3, 2016 at 16:58
\$\endgroup\$
2
\$\begingroup\$

Brachylog, 18 bytes

,1111:?:{^@[.l4,}i

Try it online!

This answer is 0-indexed.

Explanation

,1111:?:{ }i Iteratively call Input times the predicate in brackets starting with
 input 1111:
 ^ Square
 @[. Output is a prefix of the square
 .l4, Its length is 4
answered Dec 2, 2016 at 19:18
\$\endgroup\$
2
\$\begingroup\$

Batch, 82 bytes

@set n=1111
@for /l %%i in (1,1,%1)do @set/an*=n&call set n=%%n:~0,4%%
@echo %n%

Like Perl, integers are strings, but unlike Perl I can only take the substring of a variable, and taking substrings inside a loop is somewhat awkward.

answered Dec 2, 2016 at 20:08
\$\endgroup\$
2
  • \$\begingroup\$ I think you can leave out the space after @for. \$\endgroup\$ Commented Dec 5, 2016 at 13:20
  • \$\begingroup\$ @YourDeathIsComing 'for' is not recognised as an internal or external command, operable program or batch file. \$\endgroup\$ Commented Dec 5, 2016 at 13:34
2
\$\begingroup\$

C, 56 bytes

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

One-indexed.

answered Dec 3, 2016 at 0:34
\$\endgroup\$
1
  • 1
    \$\begingroup\$ I have a feeling that you can go for recursion... \$\endgroup\$ Commented Dec 3, 2016 at 9:05
2
\$\begingroup\$

Clojure, 76 bytes

(defn s[n](if(= n 1)1111(read-string(subs(str(*(s(dec n))(s(dec n))))0 4))))

First Clojure golf (seems like a nice language). This is 1-indexed.

Will explain the code later.

answered Dec 3, 2016 at 1:57
\$\endgroup\$
2
\$\begingroup\$

C#, (削除) 64 (削除ここまで) 60 bytes

Saved 4 bytes by following Olivier Grégoire's comment on a Java answer!

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

Previous version (64 bytes):

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

Full program with ungolfed method and test cases:

using System;
namespace SquaringSequence
{
 class Program
 {
 static void Main(string[] args)
 {
 Func<int, int> f = n =>
 {
 int x = 1111;
 while (n-- > 1)
 {
 x *= x;
 while (x > 9999)
 x /= 10;
 }
 return x;
 };
 // test cases:
 Console.WriteLine(f(1)); // 1111
 Console.WriteLine(f(8)); // 6840
 Console.WriteLine(f(15)); // 7584
 Console.WriteLine(f(20)); // 1425
 Console.WriteLine(f(80)); // 4717
 }
 }
}
answered Dec 2, 2016 at 19:34
\$\endgroup\$
0
2
\$\begingroup\$

Ruby, 47 bytes

First golf! Saves bytes with -n option (but still count as 1! :)).

a=1111;$_.to_i.times{a="#{a*a}"[0,4].to_i};p a

0-indexed. To run it:

ruby -ne 'a=1111;$_.to_i.times{a="#{a*a}"[0,4].to_i};p a' <<< 80
answered Dec 3, 2016 at 18:17
\$\endgroup\$
2
  • \$\begingroup\$ Welcome to the site, and nice first answer! One nitpick though, technically this is 47 bytes because of our policy of counting command line flags towards the byte count. Other than that, it looks good to me! \$\endgroup\$ Commented Dec 3, 2016 at 18:26
  • \$\begingroup\$ Thanks! Didn't know the rules, answer changed! \$\endgroup\$ Commented Dec 3, 2016 at 18:29
2
\$\begingroup\$

Pyth, (削除) 13 (削除ここまで) 12 bytes

Thanks to @Jakube for -1 byte

us<*4`*GG4Q1

A program that takes input of a 1-indexed integer and prints the result.

Test suite

This uses a similar approach to @Adnan's answer.

How it works

us<*4`*GG4Q1 Program. Input: Q
u Q1 Execute the following Q times, starting at 1, with variable G:
 *GG Yield G*G
 ` Convert to string
 *4 Repeat 4 times
 < 4 Yield first 4 characters
 s Convert to integer
 Implicitly print
answered Dec 2, 2016 at 21:54
\$\endgroup\$
1
  • 1
    \$\begingroup\$ *GG instead of ^G2<space> \$\endgroup\$ Commented Dec 4, 2016 at 20:30
2
\$\begingroup\$

GolfScript, 15 bytes

~1111\{.*`4<~}*

Try it online!

0-indexed

~ # Parse n to a number
 1111 # Push 1111
 \{ }* # Execute this block n times
 .* # Square the number
 ` # Parse it to a string
 4< # Get the first 4 digits
 ~ # Parse it back to a number
answered Oct 10, 2020 at 17:38
\$\endgroup\$
2
  • \$\begingroup\$ Nice answer. Is it not possible to take integer input directly? \$\endgroup\$ Commented Oct 11, 2020 at 4:44
  • 1
    \$\begingroup\$ @Razetime No, in the input and output section of golfscript.com/golfscript/tutorial.html , it says: "all input from stdin is read first and placed as a string onto the stack". But this site also doesn't mention that the numbers can be complex, so maybe there is a way. If there is, it cannot be shorter than ~. \$\endgroup\$ Commented Oct 11, 2020 at 14:51
2
+100
\$\begingroup\$

Vyxal, (削除) 6 (削除ここまで) 5 bytes

Ṫ(24Ẏ

Try it online, or verify all test cases.

Explanation:

Ṫ # Pop, push 1 then the input
 ( # [Input] times:
 2 # Square
 4Ẏ # Get the first 4 digits
answered Jul 24, 2022 at 2:50
\$\endgroup\$
5
2
\$\begingroup\$

TI-Basic, 31 bytes

Input N
1111
For(I,2,N
int(Ans2/10^(-3+int(log(Ans2
End
Ans

1-indexed input. - represents the negative symbol.

answered Nov 20, 2022 at 19:19
\$\endgroup\$
2
\$\begingroup\$

Excel VBA, 42 bytes

v=1111:For i=2To[A1]:v=Left(v^2,4):Next:?v

Input is in cell A1 of the active sheet. Code is run in the immediate window. Output is to the immediate window. Here's the result for 80 as an input:

Result

answered Nov 21, 2022 at 14:15
\$\endgroup\$
1
2 3

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.