20
\$\begingroup\$

Task - The title pretty much sums it up: raise an integer x to power x, where 0<x.

Restrictions:

  • Use of exponentiation, exp(), ln(), and any other powers-related language built-ins, like pow(), x^x, x**x is forbidden.
  • You can assume that the given integer fits the limits of the programming language of your choice.

Test cases:

Input | Output
---------------
2     | 4
3     | 27
5     | 3125
6     | 46656
10    | 10000000000

This is , so the shortest program in bytes wins.

\$\endgroup\$
  • \$\begingroup\$ Can we accept input as a string? \$\endgroup\$ – Shaggy May 9 '17 at 22:32
  • \$\begingroup\$ I have made an edit to this, hoping it will be reopened. I deleted rule 3 and instead stated that it should be a full program, as the OP probably intended \$\endgroup\$ – Mr. Xcoder May 10 '17 at 10:03
  • \$\begingroup\$ Much better, @Mr.Xcoder but I suggest removing (or rewording) the second restriction. Does "not a function" exclude JS from participating? I'd also suggest, for the purposes of the challenge, that we should have to handle 0 and that the expected output be specified (0 or 1 or either). Finally, having to handle negative integers would be a nice addition to the challenge. \$\endgroup\$ – Shaggy May 10 '17 at 10:07
  • \$\begingroup\$ @Shaggy added js back in... calculated 0^0 on the apple calculator and it returned 1. Maybe 1 should be the chosen value, because Python also returns 1 for 0^0. However, Foundation+ Swift returns 0 \$\endgroup\$ – Mr. Xcoder May 10 '17 at 10:08
  • 1
    \$\begingroup\$ @Mr.Xcoder, I've removed the "restriction" that we need not handle 0 and instead specified that 0<x in the lead-in. I also removed the restriction that code shouldn't throw errors; that should go without saying. Feel free to roll back if necessary. \$\endgroup\$ – Shaggy May 10 '17 at 11:14

72 Answers 72

16
\$\begingroup\$

Python, 25 bytes

lambda n:eval('1'+'*n'*n)

Try it online!

| improve this answer | |
\$\endgroup\$
15
\$\begingroup\$

APL (Dyalog), 4 bytes

For xx, takes x as left argument and x as right argument.

×/⍴⍨

Try all cases online!

×/ product of

⍴⍨ arg copies arg

And here here is one that handles negative integers too:

×/|⍴|*×

Try all cases!

×/ the product of

| absolute value

repetitions of

| the absolute value

* to the power of

× the signum

The built-in Power primitive is:

x*y
| improve this answer | |
\$\endgroup\$
10
\$\begingroup\$

Mathematica, 16 bytes

I've got two solutions at this byte count:

1##&@@#~Table~#&

Here, #~Table~# creates a list of n copies of n. Then the List head is replaced by 1##& which multiplies all its arguments together.

Nest[n#&,1,n=#]&

This simply stores the input in n and then multiplies 1 by n, n times.

| improve this answer | |
\$\endgroup\$
  • 1
    \$\begingroup\$ #~Product~{#}& \$\endgroup\$ – alephalpha May 12 '17 at 13:14
  • 1
    \$\begingroup\$ @alephalpha ah, good point. You can post that as a separate answer. \$\endgroup\$ – Martin Ender May 12 '17 at 13:31
6
\$\begingroup\$

JavaScript (ES6), 33 28 25 24 bytes

n=>g=(x=n)=>--x?n*g(x):n

Try It

f=
n=>g=(x=n)=>--x?n*g(x):n
o.innerText=f(i.value=3)()
i.oninput=_=>o.innerText=f(+i.value)()
<input id=i min=1 type=number><pre id=o>


History

25 bytes

f=(n,x=n)=>--x?n*f(n,x):n

28 bytes

n=>eval(1+("*"+n).repeat(n))

33 bytes

n=>eval(Array(n).fill(n).join`*`)
| improve this answer | |
\$\endgroup\$
5
\$\begingroup\$

Pure bash, 43

echo $[$1<2?1:$[$1<2?2:$1]#`printf 1%0$1d`]

Try it online.

Not sure if this is bending the rules too much - I'm not using any of the listed banned builtins, but I am using base conversion.

  • printf 1%0$1d outputs a 1 followed by n 0s
  • $[b#a] is an arithmetic expansion to treat a as a base b number, which gives the required result. Unfortunately base <2 does not work, so the extra ?: bits handle input n=1.

Maximum input is 15, because bash uses signed 64-bit integers (up to 231-1).

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ Same problem as I had, this doesn't work for x=1. Nonetheless, very interesting approach. \$\endgroup\$ – Maxim Mikhaylov May 10 '17 at 18:25
  • \$\begingroup\$ @MaxLawnboy Thanks for pointing that out - that sadly bloated my answer. Perhaps I can figure out another shorter version... \$\endgroup\$ – Digital Trauma May 10 '17 at 19:39
  • \$\begingroup\$ Cool stuff. Always wished to learn bash, but always been too lazy for it =) \$\endgroup\$ – user69099 May 12 '17 at 23:26
5
\$\begingroup\$

Standard ML, 42 bytes

fn x=>foldl op*1(List.tabulate(x,fn y=>x))

Try it online!

Explanation:

fn y => x                 (* An anonymous function that always returns the inputted value *)
List.tabulate(x, fn y=>x) (* Create a list of size x where each item is x *)
foldl op* 1               (* Compute the product of the entire list *)    
| improve this answer | |
\$\endgroup\$
  • 1
    \$\begingroup\$ Welcome to PPCG! \$\endgroup\$ – Martin Ender May 11 '17 at 19:20
  • 1
    \$\begingroup\$ TIO has MLton now. tio.run/nexus/… \$\endgroup\$ – Dennis May 13 '17 at 17:01
  • \$\begingroup\$ Oh that's awesome! Thanks! \$\endgroup\$ – musicman523 May 13 '17 at 17:30
4
\$\begingroup\$

Alice, 13 bytes

/o
\i@/.&.t&*

Try it online!

Explanation

/o
\i@/...

This is a framework for programs that read and write decimal integers and operate entirely in Cardinal mode (so programs for most arithmetic problems).

.    Duplicate n.
&.   Make n copies of n.
t    Decrement the top copy to n-1.
&*   Multiply the top two values on the stack n-1 times, computing n^n.
| improve this answer | |
\$\endgroup\$
4
\$\begingroup\$

R, 22 bytes

reads x from stdin.

prod(rep(x<-scan(),x))

generates a list of x copies of x, then computes the product of the elements of that list. When x=0, the rep returns numeric(0), which is a numeric vector of length 0, but the prod of that is 1, so 0^0=1 by this method, which is consistent with R's builtin exponentiation, so that's pretty neat.

Try it online!

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ Dang, I find a challenge where I am positive I've come up with an excellent solution exactly like this and you've beat me. And beat me by 3 years! I've barely been on Code Golf for a year now! \$\endgroup\$ – Sumner18 Sep 25 at 15:19
3
\$\begingroup\$

Jelly, 3 bytes

ẋ⁸P

Try it online!

How?

ẋ⁸P - Main link: x             e.g. 4
 ⁸  - link's left argument, x       4
ẋ   - repeat left right times       [4,4,4,4]
  P - product                       256
| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ Darn, I wanted to do this. :P \$\endgroup\$ – HyperNeutrino May 9 '17 at 22:49
  • \$\begingroup\$ @Jonathan Allan is it 3 bytes, or 3 wide-characters? let us view source code hex dump, please, to make correct decision on actual code bytesize. ;-) and make the corrections \$\endgroup\$ – user69099 May 12 '17 at 23:20
  • 2
    \$\begingroup\$ @xakepp35 Jelly uses a SBCS and the bytes link in the header points to it. The program with hexdump F7 88 50 works as intended. \$\endgroup\$ – Dennis May 12 '17 at 23:48
  • \$\begingroup\$ @Dennis thanks for reply! i could not ever imagine such a language before =) \$\endgroup\$ – user69099 May 13 '17 at 0:17
3
\$\begingroup\$

Cubix, 19 bytes

..@OI:1*s;pu!vqW|($

Try it online!

Step by Step

Expands out onto a cube with side length 2

    . .
    @ O
I : 1 * s ; p u
! v q W | ( $ .
    . .
    . .
  • I:1 Takes the input, duplicates it and pushs 1. This sets up the stack with a counter, multiplier and result.
  • *s; Multiples the TOS, swaps the result with previous and remove previous.
  • pu Bring the counter item to the TOS. U-turn. This use to be a lane change, but needed to shave a byte.
  • |($ This was done to save a byte. When hit it skips the decrement. reflects, decrements the counter and skips the no op wrapping around the cube.
  • !vqW Test the counter. If truthy skip the redirect, put the counter on BOS, change lane back onto the multiplier. Otherwise redirect.
  • |sO@ this is the end sequence redirected to from counter test. Goes past the horizontal reflect, swaps the TOS bringing result to the TOS, ouput and halt.
| improve this answer | |
\$\endgroup\$
3
\$\begingroup\$

05AB1E, 3 bytes

.DP

Try it online! or Try all examples

.D  # pop a,b    push b copies of a 
    # 05AB1E implicitly takes from input if there aren't enough values on the stack
    # For input 5, this gives us the array: [5,5,5,5,5]
  P # Take the product of that array
    # Implicit print
| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ Looks like you enjoyed .D. First time I've seen it used. \$\endgroup\$ – Magic Octopus Urn May 11 '17 at 19:36
  • \$\begingroup\$ ah, i dont get what is happening here.. seems to be too exotic and no explanation on how that works. =( \$\endgroup\$ – user69099 May 12 '17 at 23:28
  • \$\begingroup\$ @xakepp35 Does that help? \$\endgroup\$ – Riley May 12 '17 at 23:32
  • \$\begingroup\$ .D can be и for -1 (probably a builtin that wasn't available before?) \$\endgroup\$ – Kevin Cruijssen Sep 25 at 14:53
3
\$\begingroup\$

x86_64 machine language for Linux, 14 11 10 bytes

0:   6a 01                   pushq  $0x1
2:   58                      pop    %rax
3:   89 f9                   mov    %edi,%ecx
5:   f7 ef                   imul   %edi
7:   e2 fc                   loop   5
9:   c3                      retq

To Try it online!, compile and run the following C program.

const char h[]="\x6a\1\x58\x89\xf9\xf7\xef\xe2\xfc\xc3";

int main(){
  for( int i = 1; i < 4; i++ ) {
    printf( "%d %d\n", i, ((int(*)())h)(i) );
  }
}
| improve this answer | |
\$\endgroup\$
2
\$\begingroup\$

Ruby, 20 18 bytes

-2 bytes because the spec changed and I no longer need an exponent argument.

->x{eval [x]*x*?*}

Try it online!

| improve this answer | |
\$\endgroup\$
2
\$\begingroup\$

Stacked, 10 bytes

{!1[n*]n*}

Try it online!

Two-argument exponentiation for the same size:

{%1[x*]y*}

Both are functions. Repeats a function that multiplies 1 by n n times.

| improve this answer | |
\$\endgroup\$
2
\$\begingroup\$

Scala, 32 26 bytes

n=>List.fill(n)(n).product

Try it online! (Added conversion to long in the TIO so it wouldn't overflow on n=10.)

| improve this answer | |
\$\endgroup\$
2
\$\begingroup\$

Haskell, 24 23 21 bytes

f y=product$y<$[1..y]

Try it online!

  • Saved 1 byte, thanks to Laikoni
  • Saved 2 bytes, thanks to nimi
| improve this answer | |
\$\endgroup\$
  • 1
    \$\begingroup\$ f y=foldr1(*)$y<$[1..y] is a byte shorter. \$\endgroup\$ – Laikoni May 11 '17 at 14:19
  • 1
    \$\begingroup\$ product$y<$[1..y] \$\endgroup\$ – nimi May 16 '17 at 5:27
  • \$\begingroup\$ Not sure how I managed to forget about product, thanks! :D \$\endgroup\$ – sudee May 16 '17 at 7:53
2
\$\begingroup\$

Japt, 4 bytes

ÆUÃ×

Try it online!

Explanation

ÆUÃ×       // implicit: U = input integer
Uo{U} r*1  // ungolfed

Uo{ }      // create array [0, U) and map each value to...
   U       //   the input value
      r*1  // reduce with multiplication, starting at 1          
           // implicit output of result
| improve this answer | |
\$\endgroup\$
2
\$\begingroup\$

x86 machine code (Linux), 18 bytes

31 c0 ff c0 31 db 39 df 74 07 0f af c7 ff c3 eb f5 c3

It expects a C declaration as follows extern int XpowX(int).

Disassembled

XpowX:
  # edi : input register
  # ebx : counter
  # eax : result register
  xor  %eax, %eax    # result  = 0
  inc  %eax          # result += 1
  xor  %ebx, %ebx    # counter = 0
  loop:
    cmp  %ebx, %edi  # if (counter == input)
    je   done        #   return result
    imul %edi, %eax  # result  *= input
    inc        %ebx  # counter += 1
    jmp   loop
  done:
    ret
| improve this answer | |
\$\endgroup\$
2
\$\begingroup\$

Flurry, 16 bytes

<>{{}}<<>()>{}{}

Run example

$ ./flurry -nin -c "<>{{}}<<>()>{}{}" 4
256
$ ./flurry -nin -c "<>{{}}<<>()>{}{}" 5
3125

Multiply n n times to 1. The lambda expression is n (\x. \y. n (x y)) I where \y. n (x y) or n ∘ x is the product of Church numeral of n and x, and its SKIB-transformation is as follows:

n (\x. \y. n (x y)) I
S I (\n. \x. \y. n (x y)) n I
S I (\n. \x. S (K n) x) n I
S I (\n. S (K n)) n I
S I (S ∘ K) n I

So the direct translation of this expression into Flurry gives the code above.

Expanding the S in front gives n ((S ∘ K) n) I, which does not change bytes:

({})[<<>()>{}]{}

If direct exponentiation is allowed, it is 6 bytes: ({}){} (pop n, push n, pop n; evaluates to n n), because n m evaluates to m^n when n and m are Church numerals.

| improve this answer | |
\$\endgroup\$
2
\$\begingroup\$

Arn, 8 bytes

xõPÑ_=>$

Explained

Unpacked: *v{_}\1=>

    \        Fold...
*            ...with multiplication after...
v{           ...mapping with key of v...
  _          ...by replacing with input
}            End map
      1      Literal one
        =>   inclusive range to...
          _  ...input, implied
| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ Wow, nice language! I like how the source code is compressed from a readable notation. \$\endgroup\$ – user96495 Aug 13 at 13:09
  • \$\begingroup\$ Thanks! Glad you like it :) \$\endgroup\$ – ZippyMagician Aug 13 at 13:44
2
\$\begingroup\$

Rust, 37 bytes

|x|(|mut y|{for _ in 1..x{y*=x}y})(x)

Try it online

This might be able to be shortened once bindings_after_at stabilizes by using |mut y@x| instead.

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ 26 bytes: |x|(1..x).fold(1,|a,_|a*x) \$\endgroup\$ – madlaina Aug 14 at 15:14
  • \$\begingroup\$ @madlaina Feel free to post that as your own solution! It works differently than mine does and is certainly a lot shorter. \$\endgroup\$ – TehPers Aug 14 at 16:31
2
\$\begingroup\$

1+, 29 27 25 24 bytes

1."1##/"\*\1+\"/^"/<1+#:

This was already shockingly short, given how messy it is to create a halting loop... I did a poor job on stack manipulation, so it can probably be improved.

Special notes on 25 -> 24

Remember that you're programming in brainfuck. It's tempting to avoid confusion and tedium by thinking in terms of higher-level abstractions as much as possible, rather than thinking in brainfuck. This can buy enough control to make a working program, usually at the cost of such inefficiencies as: -excessive pointer movement, sometimes as simple as ">+<->" and sometimes less apparent; often a result of doing things in an intuitively appealing order. -- Daniel B. Cristofani

This applies to 1+ as well. I designed this program with pseudo-code, which results in two consecutive /s - cuz there are only three elements on the stack, replacing it with \ saves one byte.

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Brachylog, 6 bytes

g;?j₎×

Try it online!

Explanation

          Example input: 5
g         Group: [5]
 ;?       Pair with the Input: [[5], 5]
   j₎     Juxtapose [5] 5 times: [5, 5, 5, 5, 5]
     ×    Multiply
| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

CJam, 7 bytes

ri_a*:*

Try it online!

Explanation

ri       e# Read an int from input
  _      e# Duplicate it
   a*    e# Put the copy in the array and repeat it that many times
     :*  e# Take the product of the array
| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Perl 6, 13 bytes

{[*] $_ xx$_}

$_ xx $_ evaluates to a list of $_ copies of $_ ($_ being the argument to the anonymous function), and then [*] reduces that list with multiplication.

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

CJam, 6 bytes

ri_m*,

Try it online!

ri       e# Read integer
  _      e# Duplicate
   m*    e# Cartesian power. The first argument is interpreted as a range
     ,   e# Number of elements. Implicitly display
| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Clojure, 22

#(apply *(repeat % %))

:)

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Röda, 17 bytes

{product([_]*_1)}

Try it online!

It's an anonymous function that takes it's input from the stream.

Explanation:

{product([_]*_1)}
{               } /* An anonymous function */
         [_]      /* An array containing the input value */
            *_1   /* repeated times the input value */
 product(      )  /* Product of all values in the array */
| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

dc, 24 23 26 22 bytes

This is my first attempt writing a recursive macro in dc. I am sure it is a sub-optimal solution which can be improved a lot.

dsr1+[lrr1-d1<F*]dsFxp

Try it online!

Edit: Thanks eush77! -4 bytes.

| improve this answer | |
\$\endgroup\$
  • 1
    \$\begingroup\$ Does not work for x=1. \$\endgroup\$ – eush77 May 10 '17 at 17:57
  • \$\begingroup\$ You can shave off two bytes by replacing lr sequences at the end with two ds at the beginning. \$\endgroup\$ – eush77 May 10 '17 at 18:29
  • \$\begingroup\$ Actually, you don't need that. Just increment the top of the stack before calling for the first time. This way you will end up with x copies of x on the stack (and 1 of course), and x multiplications thereafter. So the ending can just be plain dsFxp. \$\endgroup\$ – eush77 May 10 '17 at 18:35
  • \$\begingroup\$ @eush77 I was about to say that removing second lr wouldn't work here. It's my first time golfing in a stack-based language, so it feels very unusual. Thanks for your help! \$\endgroup\$ – Maxim Mikhaylov May 10 '17 at 18:46
1
\$\begingroup\$

Batch, 58 bytes

@set n=1
@for /l %%i in (1,1,%1)do @set/an*=%1
@echo %n%

Only works for single-digit inputs due to 32-bit arithmetic.

| improve this answer | |
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy