The Squaring Sequence

29

3

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

FlipTack

Posted 2016-12-02T18:53:53.703

Reputation: 13 242

2

Here's a related link :)

– FlipTack – 2016-12-02T18:56:50.287

Answers

11

05AB1E, 8 7 bytes

Code:

$Fn4×4£

Explanation:

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

Uses the CP-1252 encoding. Try it online!

Adnan

Posted 2016-12-02T18:53:53.703

Reputation: 41 965

3Beat me by 20 seconds :(. – Magic Octopus Urn – 2016-12-02T19:01:03.640

24

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.

ETHproductions

Posted 2016-12-02T18:53:53.703

Reputation: 47 880

6

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

Kade

Posted 2016-12-02T18:53:53.703

Reputation: 7 463

Another 46 bytes solution: f=lambda n:1111if n<2else int(`f(n-1)**2`[:4]) – acrolith – 2016-12-02T19:36:00.467

@daHugLenny that can actually be 45: https://repl.it/EejD

– FlipTack – 2016-12-02T19:47:43.383

1@Flp.Tkc And that can actually be 44 ;) – Kade – 2016-12-05T14:00:29.747

6

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         

nimi

Posted 2016-12-02T18:53:53.703

Reputation: 34 639

6

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

Greg Martin

Posted 2016-12-02T18:53:53.703

Reputation: 13 940

5

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

James

Posted 2016-12-02T18:53:53.703

Reputation: 54 537

5

Jelly, 12 9 bytes

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

²Dṁ4Ḍ
1Ç¡

Ungolfing

Helper link
²       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.

Sherlock9

Posted 2016-12-02T18:53:53.703

Reputation: 11 664

This saves 3 bytes with 1-based indexing. – Dennis – 2016-12-02T19:31:38.273

Uh, I don't think you can use 1 instead of ⁽¡n. – Erik the Outgolfer – 2018-01-28T10:35:29.877

@EriktheOutgolfer How come? – Sherlock9 – 2018-01-28T16:09:11.993

@Sherlock9 Oh, you seem to 1-index this sequence? Hm, looks like the code is a bit tricky to understand... – Erik the Outgolfer – 2018-01-28T16:18:53.177

4

Perl, 37 bytes

36 bytes of code + -p flag.

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

To run it:

perl -pe '$\=1x4;$\=substr$\*$\,0,4while--$_}{' <<< 80

Dada

Posted 2016-12-02T18:53:53.703

Reputation: 8 279

4

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.

wubs

Posted 2016-12-02T18:53:53.703

Reputation: 363

4

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.

Jonathan Allan

Posted 2016-12-02T18:53:53.703

Reputation: 67 804

Good one, ninja'd me by one byte! – FlipTack – 2016-12-02T20:51:51.043

I just looked for your answer and then realised you wrote the challenge! Nice job. – Jonathan Allan – 2016-12-02T20:56:13.470

1Nice 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]). – xnor – 2016-12-02T21:51:56.083

@xnor very neat! – Jonathan Allan – 2016-12-02T22:03:48.247

1"Crossed out 44 still looks like 44 :(" – FlipTack – 2016-12-02T22:23:36.847

1@Flp.Tkc not as much as it does without the &nbsp;s! – Jonathan Allan – 2016-12-02T22:25:33.153

3

Groovy, 49 bytes

{x=1111;(it-1).times{x="${x**2}"[0..3] as int};x}

Magic Octopus Urn

Posted 2016-12-02T18:53:53.703

Reputation: 19 422

3

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.

Xanderhall

Posted 2016-12-02T18:53:53.703

Reputation: 1 236

You could save 3 bytes by using $argv[1]-- as the loop counter. – user59178 – 2016-12-05T09:36:12.027

3

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

James

Posted 2016-12-02T18:53:53.703

Reputation: 54 537

2You can use U (square, for numeric input) insted of t* – Luis Mendo – 2016-12-02T20:12:17.007

1@LuisMendo Thanks for reminding of the function I recommended! :P – James – 2016-12-02T21:21:48.413

3

Pyke, 10 bytes

1RVX`4*4<b

Try it here!

Blue

Posted 2016-12-02T18:53:53.703

Reputation: 26 661

3

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

JAD

Posted 2016-12-02T18:53:53.703

Reputation: 2 898

This is so notrivial. Brilliant! – Andreï Kostyrka – 2016-12-03T02:02:54.540

1Nice one! What would happen if you started with 3334 (or perhaps 3333)? – ETHproductions – 2016-12-03T02:16:14.283

@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. – JAD – 2016-12-03T09:44:53.290

3

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;}}

Maltysen

Posted 2016-12-02T18:53:53.703

Reputation: 25 023

2

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

Fatalize

Posted 2016-12-02T18:53:53.703

Reputation: 32 976

2

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

adrianmp

Posted 2016-12-02T18:53:53.703

Reputation: 1 592

1+1 for the dark goes-to-operator n-->1 – Karl Napf – 2016-12-03T00:43:09.040

2

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

TheBikingViking

Posted 2016-12-02T18:53:53.703

Reputation: 3 674

1*GG instead of ^G2<space> – Jakube – 2016-12-04T20:30:06.603

2

C, 56 bytes

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

One-indexed.

Lynn

Posted 2016-12-02T18:53:53.703

Reputation: 55 648

1I have a feeling that you can go for recursion... – Mukul Kumar – 2016-12-03T09:05:23.797

2

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.

clismique

Posted 2016-12-02T18:53:53.703

Reputation: 6 600

2

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

ghivert

Posted 2016-12-02T18:53:53.703

Reputation: 21

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!

– James – 2016-12-03T18:26:08.443

Thanks! Didn't know the rules, answer changed! – ghivert – 2016-12-03T18:29:41.337

1

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.

Xanderhall

Posted 2016-12-02T18:53:53.703

Reputation: 1 236

2You can save some bytes by using x*=x; instead of Math.pow. – adrianmp – 2016-12-02T20:36:08.557

and put that whole stuff in for loops instead of while loops. – Olivier Grégoire – 2016-12-03T14:41:57.597

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 – 2016-12-03T14:54:53.433

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 – 2016-12-05T13:01:34.450

1

CJam, 15 bytes

'14*ri{i2#s4<}*

Uses 0-based indexing.

Try it online!

Martin Ender

Posted 2016-12-02T18:53:53.703

Reputation: 184 808

1

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.

Neil

Posted 2016-12-02T18:53:53.703

Reputation: 95 035

I think you can leave out the space after @for. – YourDeathIsComing – 2016-12-05T13:20:17.247

@YourDeathIsComing 'for' is not recognised as an internal or external command, operable program or batch file. – Neil – 2016-12-05T13:34:36.970

1

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!

RudolfJelin

Posted 2016-12-02T18:53:53.703

Reputation: 853

2This answer is incomplete. x isn't declared. This should be a function or full program. Not a code snippet. – NonlinearFruit – 2016-12-02T22:04:26.523

@NonlinearFruit I was going for the function. Seems I missed this out. Do you mean I should just replace x with a number? – RudolfJelin – 2016-12-03T07:21:50.177

1What @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. – Olivier Grégoire – 2016-12-03T15:02:27.870

@OlivierGrégoire Isn't that 93 bytes? And thanks for pointing out lambda funcions. – RudolfJelin – 2016-12-03T15:26:29.423

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) – Olivier Grégoire – 2016-12-03T15:37:42.207

@OlivierGrégoire I didn't read your comment as the program wouldn't be mine, but rather yours. I'll try to golf it myself first. – RudolfJelin – 2016-12-03T15:52:54.560

@OlivierGrégoire I'm done golfing. Now when I see your code, I don't think it works: n=n.valueOf throws an error; I used n=Long.valueOf instead. Also, return n; throws an error, and the program works without it. – RudolfJelin – 2016-12-03T17:16:11.650

You can remove the brackets around n=Long.... Also you probably should add a return or the n would be useless. – Roman Gräf – 2016-12-03T18:41:41.137

@RomanGräf it seems to work without it. But thanks for the tips! – RudolfJelin – 2016-12-03T18:45:14.743

Yes but how do get the result back? – Roman Gräf – 2016-12-03T18:46:01.987

@RomanGräf You mean print it? I just put a System.out.println later. – RudolfJelin – 2016-12-03T18:47:52.970

I don't see your point. If you add the System.out.print() call in the function you have to add that to the byte count. – Roman Gräf – 2016-12-03T18:54:41.730

@RomanGräf It's not in the function, it's where the function is called – RudolfJelin – 2016-12-03T19:03:21.017

Then you need a return – Roman Gräf – 2016-12-03T19:04:02.190

@RomanGräf you mean x->{long n=1111;for(;--x>0;)n=Long.valueOf((n*n+"").substring(0,4));return n}? It seems to work for me without it. – RudolfJelin – 2016-12-03T19:13:01.607

Lets say you want to assign long i=... to SquareSequence[n]. How would ... look like? – Roman Gräf – 2016-12-03T19:41:04.877

@RudolfL.Jelínek You are right, I made 1 mistake in my suggestion: Long n=1111L: I should have appended L (for 1 more byte than advertized). The rest is OK and works fine. Also, make sure to use Long and not long. – Olivier Grégoire – 2016-12-03T23:41:48.273

Also, to be complete, it's still your code: I haven't changed your algorithm for a bit. Same for the other Java answer which I got down to 60 bytes. I didn't do the main algorithm, so it's not my solution either. I only optimized the presentation of the algorithm itself, just like I suggested for your solution. I don't consider either of suggestions mine.

– Olivier Grégoire – 2016-12-03T23:56:58.010

@OlivierGrégoire You could post that golfed-down code as your own answer, get a few upvotes, and leave my partial answer as is. You didn't. Thanks. – RudolfJelin – 2016-12-04T10:44:16.827

1

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)

Brad Gilbert b2gills

Posted 2016-12-02T18:53:53.703

Reputation: 12 713

1

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

Owen Morgan

Posted 2016-12-02T18:53:53.703

Reputation: 221

1

Pushy, 26 20 bytes

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

Give arguments on the commandline: $ pushy sqseq.pshy 79.

Nicely formatted, with explanation:

            % 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

FlipTack

Posted 2016-12-02T18:53:53.703

Reputation: 13 242

1

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));}

Roman Gräf

Posted 2016-12-02T18:53:53.703

Reputation: 2 915

Can you do for(i*=i;i>1e4;)i/=10;? That would save a byte. – ETHproductions – 2016-12-03T19:50:50.380

Hmmm... Regarding your claim about the shortest Java function, this function would like to have some words ;-)

– Olivier Grégoire – 2016-12-04T00:02:33.207

Hmmm, thinking about it, why do you even use longs? You can kill two bytes by using ints. – Olivier Grégoire – 2016-12-04T00:57:47.307

I missed that when I updated to 2.0 – Roman Gräf – 2016-12-04T05:52:02.217

1

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.

user62131

Posted 2016-12-02T18:53:53.703

Reputation:

0

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.

steenbergh

Posted 2016-12-02T18:53:53.703

Reputation: 7 772

0

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
%

Ruud Helderman

Posted 2016-12-02T18:53:53.703

Reputation: 571

0

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

Mama Fun Roll

Posted 2016-12-02T18:53:53.703

Reputation: 7 234

0

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.

DLosc

Posted 2016-12-02T18:53:53.703

Reputation: 21 213

0

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

user41805

Posted 2016-12-02T18:53:53.703

Reputation: 16 320

0

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.

sonrad10

Posted 2016-12-02T18:53:53.703

Reputation: 535

Please note that there's already a python answer here.

– FlipTack – 2016-12-03T13:56:43.557

@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]: http://codegolf.stackexchange.com/a/101964/53336

– sonrad10 – 2016-12-03T14:05:57.690

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 – 2016-12-03T14:09:44.940

@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 – 2016-12-03T14:17:04.983

0

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.

Jay Anderson

Posted 2016-12-02T18:53:53.703

Reputation: 71

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 – 2016-12-04T04:36:29.480

0

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
  )

corvus_192

Posted 2016-12-02T18:53:53.703

Reputation: 1 889

0

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.

username tbd

Posted 2016-12-02T18:53:53.703

Reputation: 161

0

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!

ATaco

Posted 2016-12-02T18:53:53.703

Reputation: 7 898

0

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

mbomb007

Posted 2016-12-02T18:53:53.703

Reputation: 21 944

0

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.

NikoNyrh

Posted 2016-12-02T18:53:53.703

Reputation: 2 361