16
\$\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

60 Answers 60

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
\$\endgroup\$
13
\$\begingroup\$

Python, 25 bytes

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

Try it online!

\$\endgroup\$
9
\$\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.

\$\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
5
\$\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`*`)
\$\endgroup\$
4
\$\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).

\$\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
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.
\$\endgroup\$
4
\$\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 *)    
\$\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
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
\$\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
  • 1
    \$\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.
\$\endgroup\$
3
\$\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!

\$\endgroup\$
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) );
  }
}
\$\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!

\$\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.

\$\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.)

\$\endgroup\$
2
\$\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
\$\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
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
\$\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
\$\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
\$\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
\$\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
\$\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.

\$\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
\$\endgroup\$
1
\$\begingroup\$

Clojure, 22

#(apply *(repeat % %))

:)

\$\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 */
\$\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.

\$\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.

\$\endgroup\$
1
\$\begingroup\$

brainf*ck, 148 bytes

,[->+>+<<]>>[-<<+>>]++++++++[<------<------>>-]<[->>+>>+<<<<]>>[-<<+>>]>>-[-<<<<<[>[>+>+<<-]>>[<<+>>-]<<<-]>>[-<<+>>]>>>]<<<++++++++[-<<++++++>>]<<.

Try it online!

No built-ins ;)

How it works

,                                       - get ascii input
[->+>+<<]                               - duplicate input
>>[-<<+>>]                              - shift inputs left to start
++++++++[<------<------>>-]             - convert ascii into input numbers
<[->>+>>+<<<<]                          - get loop intervals (same as input #)
>>[-<<+>>]                              - shift input back again
>>-[-<<<<<[>[>+>+<<-]>>[<<+>>-]<<<-]>>  - iterated addition (multiplication)
[-<<+>>]>>>                             - Shift output back into input
]<<<++++++++[-<<++++++>>]<<.            - convert final output to ascii

In a nutshell, this works by multiplying x (the input) by itself x times. (a.k.a. iterating iterated addition). The net result is x^x.

I/O

The program takes a single ASCII input, and processes it as it's ASCII index minus 48. The minus 48 is to normalize inputs of actual numbers (4 becomes 52 -> 52-48 -> 4). To input a number higher than 9, use the next corrosponging ASCII character (: -> 58-48 -> 10). The program ouputs in a similar fashion.

Test I/O

INPUT > PROCESSED INPUT >> OUTPUT > TRANSLATED OUTPUT
1 > 1 >> 1 > 1
2 > 2 >> 4 > 4
3 > 3 >> K > 27

Since there are no printable ASCII characters after an input of 3, it can only print numbers in theory. Though, you can check all inputs do in fact work on visualizers such as this.

\$\endgroup\$
1
\$\begingroup\$

MATLAB/Octave, 23 bytes

@(n)(prod(n*ones(n,1)))
\$\endgroup\$
1
\$\begingroup\$

Python, 32 bytes

f=lambda g,z=1:z>g or g*f(g,z+1)

Try it online!

\$\endgroup\$
  • \$\begingroup\$ Welcome to PPCG! You don't need to count the f= part, so you can shorten your submission to 30 bytes. \$\endgroup\$ – Steadybox Jul 9 '17 at 22:32
  • \$\begingroup\$ @Steadybox The f= part does need to be counted, because it's recursive, so it relies upon the function being named f in order to work properly \$\endgroup\$ – musicman523 Jul 10 '17 at 2:06
  • \$\begingroup\$ @musicman523 Yes, you are right. \$\endgroup\$ – Steadybox Jul 10 '17 at 2:23
1
\$\begingroup\$

Common Lisp, 59 42 40 bytes

(lambda(x)(apply'*(fill(make-list x)x)))

Try it online!

\$\endgroup\$

Your Answer

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