Jeder Term in der Quadrierungssequenz, x n , wird erstellt, indem x n-1 genommen , quadriert und alle bis auf die ersten vier Ziffern entfernt werden.
Die Folge beginnt immer mit x 1 = 1111 . Quadrieren ergibt 1234321, also x 2 = 1234
Die ersten Begriffe sind:
1111
1234
1522
2316
5363
...
Die Herausforderung
Ihre Aufgabe ist es, bei einer nicht negativen ganzen Zahl n x n zu berechnen . Sie können ein vollständiges Programm einreichen, das E / A ausführt, oder eine Funktion, die n als Parameter verwendet.
Ihre Lösung kann null oder eins sein, solange Sie angeben, welche.
Da alle Begriffe in dieser Sequenz kürzer als 5 Stellen sind, sollte auch Ihr Code so kurz wie möglich sein. Es gelten Standard- Code-Golf- Regelungslücken.
Möge der beste Golfer gewinnen!
Testfälle
Hinweis: Diese sind 1-indiziert.
1 -> 1111
8 -> 6840
15 -> 7584
20 -> 1425
80 -> 4717
Antworten:
05AB1E ,
87 BytesCode:
Erläuterung:
Verwendet die CP-1252- Codierung. Probieren Sie es online!
quelle
JavaScript (ES7),
444336 bytesThis 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 thatf(n)**2+f
first convertsf(n)
to a number and squares it, then concatenates the result with the string representation off
. 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:
Test snippet
Show code snippet
Note: this uses
Math.pow
because**
isn't supported in all browsers.quelle
Haskell, 40 bytes
It's a 0-based sequence. Usage example:
((iterate(read.take 4.show.(^2))1111)!!) 79
->4717
.How it works:
quelle
Mathematica, 48 bytes
Unnamed function taking an integer argument; 0-indexed. Uses four three-byte characters
⌊⌊⌋⌋
: Mathematica uses eitherFloor[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
quelle
Python 2,
514644 BytesWrong again! The recursive function returns. This is one-indexed.I'd like to get rid of the clunkyTurns out for the moment thatif
if possible, but I think anexec
could be shorter..exec
is shorter.An aleternative 46-byte solution with
exec
:An alternative 49-byte recursive solution:
Thanks to Flp.Tkc for saving a byte by reminding me that squaring doesn't need exponentiation :)
quelle
f=lambda n:1111if n<2else int(`f(n-1)**2`[:4])
V, 19 bytes
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:
And here is a readable version:
Explanation:
quelle
Jelly,
129 bytes-3 bytes thanks to Dennis using 1-based indexing and the
ṁ
mold/reshape atom. Golfing suggestions welcome! Try it online!Ungolfing
quelle
1
instead of⁽¡n
.Perl, 37 bytes
36 bytes of code +
-p
flag.To run it:
quelle
Powershell,
7355 bytesHuge 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-1Explanation and exploded code:
Some notes:
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.[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.quelle
Python 2,
4441 bytes-3 bytes thanks to xnor (use an integer division to avoid
and
)repl.it
1-based recursive function.
When
n>1
the integer division,1/n
, results in0
, then0*1111=0
which is falsey, so the right of theor
is evaluated, which takes the first four characters of the representation of the square of then-1
th result; this is then cast to anint
.When
n=1
the integer division,1/n
, results in1
, then1*1111=1111
, which is truthy, and theint
1111
cast to anint
is1111
.quelle
int
outside. If you 1-index, you can do the base case shorter withg=lambda n:int(1/n*1111or`g(n-1)**2`[:4])
.
s!Groovy, 49 bytes
quelle
Pyke, 10 bytes
Try it here!
quelle
MATL,
14, 13 bytesTry it online!
Explanation:
quelle
U
(square, for numeric input) insted oft*
R,
58565553 bytesTakes
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
andx>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
quelle
3334
(or perhaps3333
)?3333^2 = 11108889
so would yield1110
, and .... as im checking this I see3334
would work :| . Not sure why I didn't check that anymore.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.quelle
PHP,
5552 bytesSaved 3 bytes thanks to @user59178
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.
quelle
$argv[1]--
as the loop counter.Brachylog, 18 bytes
Try it online!
This answer is 0-indexed.
Explanation
quelle
C, 56 bytes
One-indexed.
quelle
Clojure, 76 bytes
First Clojure golf (seems like a nice language). This is 1-indexed.
Will explain the code later.
quelle
C#,
6460 bytesSaved 4 bytes by following Olivier Grégoire's comment on a Java answer!
Previous version (64 bytes):
Full program with ungolfed method and test cases:
quelle
n-->1
Ruby, 47 bytes
First golf! Saves bytes with
-n
option (but still count as 1! :)).0-indexed. To run it:
quelle
Pyth,
1312 bytesThanks to @Jakube for -1 byte
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
quelle
*GG
instead of^G2<space>
CJam, 15 bytes
Uses 0-based indexing.
Try it online!
quelle
Batch, 82 bytes
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.
quelle
Perl 6, 36 bytes
Explanation:
Test:
quelle
Matlab,
79, 78 BytesTest cases:
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
quelle
Java 8,
779374716978 bytesEach repetition makes
n
the first 4 characters ofn*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
withfor
cycle.-4 bytes: used
long
s instead ofint
s-2 bytes, by Roman Gräf: removed unnecessary brackets
+9 bytes, missing
return
statementThanks 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!
quelle
x
isn't declared. This should be a function or full program. Not a code snippet.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.x->{Long n=1111;for(;--x>0;)n=n.valueOf((n*n+"").substring(0,4));return n;}
, with several techniques used (usedLong
to be able to useLong.valueOf
with less bytes, it's not recommended in normal programming, but totally in golfing; removedm
as it's unnecessary if we decreasex
instead, removed unneeded braces)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.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 use1x4
(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 insidesay
, thus the final result of theeval
will be the contents of the parentheses of the final match.quelle
Java,
79676664 bytesThanks to @Oliver Grégoire.
Thanks to @ETHProduction.
Replaced substring and stuff with the idea from @Xanderhall
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:)))
quelle
for(i*=i;i>1e4;)i/=10;
? That would save a byte.long
s? You can kill two bytes by usingint
s.Pushy,
2620 bytesGive arguments on the commandline:
$ pushy sqseq.pshy 79
.Nicely formatted, with explanation:
quelle