Die Herausforderung
Implementieren Sie die Tetration (auch Power Tower oder Hyperexponentiation genannt) mit der geringsten Anzahl von Zeichen.
Die Bedingungen
- Verwenden Sie nicht das ‚Power‘ Bediener oder ihre Äquivalente (wie zum Beispiel
pow(x,y)
,x^y
,x**y
, etc.) - Eingabe erfolgt als:
x y
(durch ein Leerzeichen getrennt) x
wird von sich ausy
mal potenziert.- Ihre Methode muss mindestens in der Lage sein zu berechnen
4 3
(4 mal für sich selbst potenziert)
Die Wertung
- Die niedrigste Punktzahl gewinnt: ( Anzahl der Charaktere)
- Bonusabzug, wenn Sie den Multiplikationsoperator nicht verwenden (-5 Punkte).
- Keine Geschwindigkeits- / Speicheranforderungen. Nimm so lange du willst.
Beispiele
x, 0 -> 1
2, 2 -> 2^2 = 4
2, 4 -> 2^(2^(2^2)) = 65536
4, 3 -> 4^(4^4) = 4^256 = 13407807929942597099574024998205846127479365820592393377723561443721764030073546976801874298166903427690031858186486050853753882811946569946433649006084096
Offen für Vorschläge / Änderungen / Fragen
*
ist Multiplikation in einigen Kontexten, aber es ist auch der einfache Schleifenoperator:{block}N*
entspricht dem C-Stilfor(i=0;i<N;i++){block}
. Der schwierige Randfall ist die String- / Array-Multiplikation ('a'3*
give'aaa'
), aber es ist unwahrscheinlich, dass dies ein Problem darstellt, da ein Array von4***3
Elementen den RAM überläuft.x 0
=> 1. Meine ursprüngliche Lösung hat diesen Fall nicht behandelt.Antworten:
J, Punktzahl ist 7 (12 Zeichen - 5 Punkte zur Vermeidung der Multiplikation)
+/@$/@$~/@$~
Verwendung:
Nur ein paar verschachtelte Falten:
*/@$~/@$~
^/@$~
wo$~
Array erstellt wird,/
eine Fold-Funktion.quelle
pad
mean here? Sorry, English is not my mother tongue.@$~
in the conjunction?/
, but yes. you're just folding as many times as needed over the nested folding function.Haskell,
8785 - 5 == 8082Uses neither of exponentiation, multiplication or addition (!), just list operations. Demonstration:
...
ahm... you didn't say anything about performance or memory, did you? But given enough billions of years and some petabytes of RAM, this would still yield the correct result (genericLength can use a bigInt to count the length of the list).
quelle
GolfScript,
1518 charsYes, one of the
*
s is a multiplication operator (exercise: which one?) so I don't qualify for the 5 char bonus. Still, it's just barely shorter than Peter's solution.This earlier 15-char version is otherwise the same, but produces no output when the second argument is 0. Thanks to r.e.s. for spotting the bug.
quelle
"2 3" ~])*{[]+*{*}*}*
.;
to remove the actual input string that the interpreter puts on the stack at start-up. Or just prepend a[
to the code: both;"2 3" ~])*{[]+*{*}*}*
and"2 3" [~])*{[]+*{*}*}*
work fine for me.ruby golfscript.rb my_script.gs
on the command line, without knowing that it causes something ("", apparently) to be on the stack before the script is run -- which sometimes works, sometimes not. (Also, withecho 2 3 | ruby golfscript.rb my_script.gs
, your program does work as-given.)J,
161912 charactersor as a verb (17 characters):
usage:
or taking input from keyboard (
242720 characters):with thanks to FUZxxl for pointing out my stupidity. :-)
Explanation:
J is read from right to left, so using
2 4
:/
is used to insert the verb$~
between each pair of items in the list.$~
takes the left item and shapes it$
using the right item (the~
reverses the arguments) - so this would be equivalent to4 $ 2
which gives you a list of2
s which is four items long2 2 2 2
.Now we append 1 to the list
1,~
and then do the same thing again;/
insert a verb*/@$~
between each pair of items in the list. This verb starts in the same way$~
but this time it/
inserts a*
between each item of the newly generated list. The@
just makes sure that the*/@$~
works as one verb instead of two. This gives2
multiplied by itself enough times to be equivalent to2^4
.J's vocabulary page - I find solving problems with J fun just because of the different way it sometimes does things.
Adding one further iteration to remove the
*
operator has 2 problemsIt comes out at 17 characters (+/@$~/,@$~/1,~$~/
) which, even with the -5 bonus, is too long4 3
quelle
^/]$[
which creates the list2 2 2 2
and sticks the exponentiation operator between them. What this is doing is going a step further and doing the exponentiation by repeated multiplication.GolfScript (24 chars - 5 = 19 points)
is insanely slow.
(or 20 chars)
is much faster.
quelle
Python, 70
This uses nested
eval
calls, eventually producing a string"a*a*a*a...*a"
which gets evaluated. Almost half of the score is wasted on getting the arguments... though I've noticed that a few other solutions don't bother with that.quelle
input()
or useeval(raw_input())
Cheersexec"eval('a*'*"*b+'1'+"+'1')"*b
Scala:110
ungolfed:
explanation:
plus, mul, high(:=pow), tetration all work in the same manner. The common pattern can be extracted as recursive method, which takes two BigInts and a basic function:
The underlines are placeholder for something which gets called in this sequence, for example the addition plus(a,b)=(a+b); therefore (+) is a function which takes two arguments and adds them (a+b).
unfortunately, I get issues with the stack size. It works for small values for 4 (for example: 2) or if I reduce the depth for one step:
The original code is 112 characters and would score, if valid, 107. Maybe I find out how to increase the stack.
The expanded algorithm can be transformed to tailrecursive calls:
The tailrecursive call is longer than the original method, but didn't raise a stackoverflow in the long version - however it doesn't yield a result in reasonable time. t(2,4) is fine, but t(3,3) already was stopped by me after 5 min. However, it is very elegant, isn't it?
And now the same as above: use stinky multiplication (we even profit while rejecting the bonus of 5, because we save 7 characters: win=4 chars:)
invocation:
runtime: 1ms.
quelle
Br**nfuck, 128-5=123 bytes
Input is in the form of characters with code points of the numbers desired as inputs. Output is the same.
An explanation is
coming when I have the timebelow. Do I get bonus points for not using exponentiation, multiplication, OR even addition?This works (tested) for
x 0
,0 x
,x 1
,1 x
,x 2
,2 3
, and2 4
. I tried3 3
, but it ran for several hours without finishing (in my Java implementation—probably not optimal) (EDIT: in @Timwi's EsotericIDE [It's great! Y'all should try it] as well. No luck.). In theory, this works up to the cell size of the specific implementation.quelle
Python, 161 - 5 (no * operator) = 156
invoke:
quelle
4***3
?!m
function withm=lambda x,y:sum(x for _ in r(y))
Perl, 61 chars
here's a bizarre one
usage:
quelle
Mathematica,
4033This doesn't quite conform to the rules but it is not in contention for the shortest code anyway, and I hope that it will be of interest to someone.
This builds a "tetration" function when it is run, but the arguments must be given in reverse order. Example:
quelle
Fold[g, 1, #2~Table~{#}] &[3, 4]
will produceg[g[g[1, 4], 4], 4]
for instance.m[Times]
producesFold[Times, 1, Table[#2, {#1}]] &
, which is a power function:m[Times][5, x]
--->x^5
; the same method is used for this new power function to produce a tetration function. Logically one could start withPlus
but that fails almost immediately.t[h_, n_] := Sum[h, {i, n}]
. Then runm[m@t][3, 4]
.Sum[h, n]
.)Haskell:
5851 chars, with or without multiplication.Ungolfed:
Shorter definition comes from inlining “bump”, and defining a custom version of “iterate”. Unfortunately the result is impossibly inefficient, but starting with (*) instead of (+) gives decent speed. In
ghci
:quelle
Ruby
6659 charactersquelle
1
) when the second input number is0
; rather,e(x,0)
returns the value ofx
.Python, 112 chars
The numbers should be the 1st and 2nd argument:
python this.py 4 3
**
operator not used.*
used. It's quite trivial to implement, exactly like**
, but costs more than 5 chars.quelle
*
implementation, I believe the recursion depth would be too large for4 3
.C,
11710599 charsEDIT: Merged the two functions
p
andr
into one, saving some chars.Of 99 chars, 52 do the actual calculation (including variable definitions). The other 47 are for handling input and output.
BUG: Badly handles powers of 0 (e.g.This isn't a bug, I forgot that0 2
). Should find a minimum cost fix.0 2
is undefined.Successfully handles
4 3
, and even gives an exact result. However, can be inaccurate for some smaller numbers.Prints the number with a trailing
.000000
.quelle
Factor, 187 characters
Before golf:
I did not remove the multiplication operator
*
. If I did so, then I would need to add some logic expressing that the sum of an empty sequence is 0, not 1. This extra logic would cost more than the -5 bonus.Rule breaker, 124 + 10 = 134 characters
This program has a lower score, but the exponentiation operator
^
breaks the rules. The rules say "(# of characters) + (10 * (# of 'power' operators))", so I applied the +10 penalty. However, the rules also say "Don't use the 'power' operator", so any program taking this penalty does break the rules. Therefore, this program of 134 characters is not a correct answer, and I must present my longer program of 187 characters as my answer.quelle
Haskell 110 - 5 = 105
Tetration Peano Style. This is the most insanely slow solution possible, just a warning, but also avoids even addition.
This relies on you having the patience to type out Peano numbers (and won't show the answer, If you actually want to run it, add these few lines (90 chars):
quelle
Ruby,
47 4645t=->x,n{r=x;2.upto(n){r=([x]*r).inject :*};r}
quelle
Lua: 133 chars, multiplication-less
I was originally going to use string repetition hacks to do fake multiplication, but it likes to fail on large values. I could possibly use dynamic compilation and loadstring to make it smaller, but it's getting late here... I need sleep.
Entering "4 3" into stdin outputs:
quelle
VBA, 90 Chars
*Perhaps the no multiplication bonus is not good enough. I think the no multiplication answer is much more interesting, but this is code golf, so it's not the best. Here's an answer without
*
, and a better (shorter, and better scoring) answer with it:90 chars, no power operators, uses multiplication = 90
116 chars, no power operators, no multiplication bonus (-5) = 111
NOTE: VBA has issues printing the number when the result is very large (i.e.
4, 3
), but it does calculate correctly, so if, for example, you wanted to USE that number, you would be good to go. Also, even BIGGER numbers overflow (i.e.3, 4
).quelle
Perl 6, 32 bytes
Try it online!
(1, { [*] a xx $_ } ... *)
is a lazy sequence that generates the power tower, each element being the a list which consists of the first input parametera
replicated (xx
) a number of times equal to the previous element ($_
), that list then being reduced with multiplication ([*]
). From that sequence we simply pluck out theb
-th element.quelle
Lambda calculus, 10-5
(using Church encoding and De Bruijn indeces)
λλ(1λ13)λ1
Explanation
Without De Bruijn indeces:
λa,b.(b λc.ca)λc.c
:If you define
exp_a(x)=a^x
this program definesa↑↑b=exp_a^b(1)
where^b
denotes function itteration.I'm not sure if this is allowed because
ca
is technically equivalent toa^c
how ever it is not a real built-in and only a side effect of the way integers are encoded in lambda calculus.quelle
Javascript: 116 chars
t('4 3') Outputs:
quelle
Python
(111)(113) no *6***3 - 36k digits))
Upd: Have to add initial value, to fit t(X,0)=1
quelle
Haskell: 88-5 chars without multiplication, 59 chars with multiplication
Without multiplication:
There are probably ways that I could golf that down a little.
With multiplication:
And finally, the ungolfed program:
This is probably the simplest way to do this problem, which is defining multiplication as repeated addition, exponentiation as repeated multiplication, and tetration as repeated exponentiation.
quelle
Racket 58 (no *)
quelle
Common Lisp, 85 chars
I tried doing the multiplications through repeated addition, but it was way more than 5 characters. Same thing with macrolets, the declarations were not worth the gains.
Another solution, inspired by boothby's python solution. It's 1 character less than the above solution.
quelle
Python 3 – 68
(including the 10-point penalty for the power operator)
quelle
Yabasic, 71 bytes
A function that takes input
a
andb
as a space delimited string.Try it online!
quelle
R, 71 - 5 = 66 bytes
Try it online!
-5 for avoiding *, which was harder than I expected. It explodes really fast and won't work (unless it had more memory) but it satisfies all necessary criteria.
quelle