# Raise integer x to power x, without exponentiation built-ins

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.

• Can we accept input as a string? Commented May 9, 2017 at 22:32
• 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 Commented May 10, 2017 at 10:03
• 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. Commented May 10, 2017 at 10:07
• @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 Commented May 10, 2017 at 10:08
• @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. Commented May 10, 2017 at 11:14

# Python, 25 bytes

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


Try it online!

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

×/|⍴|÷1⌊|×⊢


Try all cases!

×/ the product of

| absolute value

⍴repetitions of

| the absolute value

÷ divided by

1⌊ the Lesser of 1 and

| the absolute value

× times

⊢ the argument

The built-in Power primitive is:

x*y

• In the one for negative numbers you used power Commented Mar 24, 2023 at 16:22
• @Joao-3 Thanks. Fixed both that and the wrong result. Was just an extra thing, anyway.
Commented Mar 26, 2023 at 18:39
• When you forget that multiplication is not asterisk... Commented Mar 26, 2023 at 22:33

## 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.

• #~Product~{#}& Commented May 12, 2017 at 13:14
• @alephalpha ah, good point. You can post that as a separate answer. Commented May 12, 2017 at 13:31

# 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!

• 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! Commented Sep 25, 2020 at 15:19

# JavaScript (ES6), 332825 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*)


# Regex 🐇 (ECMAScript+(?^*)RME), 13 bytes

^(x(?^*x+))*$ Takes its input in unary, as a string of x characters whose length represents the number. Returns its output as the number of ways the regex can match. (The rabbit emoji indicates this output method. It can yield outputs bigger than the input, and is really good at multiplying.) Try it on replit.com This version uses molecular lookinto, a new feature in RegexMathEngine. The basic form (?^*...) matches the expression inside it against the entire input string. (With a parameter, it evaluates it against the contents of a backreference, e.g. (?^5*...) to look into \5.) On every iteration of the outer loop, there are $$\n\$$ possible matching states of the inner loop, and at the end of $$\n\$$ iterations, the match is complete. In a complete match, each iteration can independently be at any one of $$\n\$$ states, so there are $$\n^n\$$ total possible matches. Changing the * at the end to + would make it give a result of $$\0\$$ for $$\n=0\$$. ^ # tail = N = input number ( x # tail -= 1 (?^* # Non-atomic lookinto - starts with tail = N x+ # Create a choice between N possibilities ) )*$         # Loop as many times as possible, minimum 0. This will loop N times,
# because it subtracts 1 from tail on each iteration. The minimum of
# 0 iterations gives a correct result of 1 for N==0.


The constant-power $$\n^k\$$ version of this can be seen in Quartic Summation, for which there is also a method that doesn't require non-atomic lookaround. It might be impossible to implement $$\n^n\$$ without non-atomic lookaround, due to it being impossible to create $$\m\$$ number of choices (with the value $$\m\$$ being accessed via a backreference) without the guarantee of having $$\O(m)\$$ avaiable space.

The constant-base $$\k^n\$$ version of this would be e.g. ^((.+)*)+ or ^(x(||))*$ for $$\3^n\$$. # Regex 🐇 (PCRE2 v10.35+), 26 bytes ^(x((?<*(?*^x+|(?2)).)))*$


Attempt This Online!

This solution uses non-atomic recursion, lookahead, and lookbehind to emulate non-atomic variable-length lookbehind. The algorithm used is the same as that of the 13 byte version.

^                           # tail = N = input number
(
x                       # tail -= 1
(                       # Define subroutine (?2)
(?<*                # Non-atomic lookbehind
(?*             # Non-atomic lookahead
^           # If we've reached tail==0, then:
x+          # create a choice between N possibilities.
|
(?2)        # Otherwise, recursively call (?2).
)
.               # tail += 1 (Go back 1 character at a time)
)
)
)*$# Loop as many times as possible, minimum 0. This # will loop N times, because it subtracts 1 from # tail on each iteration. The minimum of 0 iterations # gives a correct result of 1 for N==0.  The equivalent in a hypothetical engine with real (not emulated) non-atomic variable-length lookbehind would be ^(x(?<*^x+.*))*$ (16 bytes).

## Regex 🐇 (PCRE2 v10.35+ without lookbehind), 59 bytes

^(?=(x*)\1(x?))(((?*x+(?!\1)()?|\2+$))x(?(?=\2\1)(?4)))*\1$


Attempt This Online!

This demonstrates this to be possible without the use of lookbehind or recursion. It works by emulating operation on $$\n\$$ within the space of $$\n/2\$$, using one of those halves as a counter for the outer loop, and the other half for the inner loop.

(I wrote this version on July 29, and am finally posting it now.)

^                         # Anchor to start; tail = N = input number
(?=(x*)\1(x?))            # \1 = floor(N / 2); \2 = N % 2
(
(                     # Define subroutine (?4):
(?*
x+(?!\1)      # Add \1 to possibility count
()?           # Double the possibility count of the above
|
\2+$# If \2==1, add 1 to possibility count ) ) x # tail -= 1 (?(?=\2\1) # If tail ≥ \2 + \1: (?4) # Call subroutine (?4), to multiply its possibility # count with the above ) )* # For every possible iteration count, from 0 to the # maximum, add the above to the possibility count \1$                       # Assert tail == \1


## Regex 🐇 (ECMAScript+(?*)RME / PCRE2 v10.35+), 81 bytes

^(?=(x*)\1(x?))((?*x+(?!\1)(|)|\2+$)x((?=\2\1)(?*x+(?!\1)(|)|\2+$)|(?!\2\1)))*\1$ Try it on replit.com - RegexMathEngine Attempt This Online! - PCRE2 v10.40+ This is a port of the 59 byte version. Basic ECMAScript lacks not only lookbehind, but subroutine calls and conditionals as well. The only feature added to basic ECMAScript is (?*...), molecular lookahead (a.k.a. non-atomic lookahead). Note that (|) must be used instead of ()? due to ECMAScript's no-empty-optional rule. (I wrote this version on July 29, and am finally posting it now.) ^ # Anchor to start; tail = N = input number (?=(x*)\1(x?)) # \1 = floor(N / 2); \2 = N % 2 ( (?* # Define "subroutine": x+(?!\1) # Add \1 to possibility count (|) # Double the possibility count of the above | \2+$              # If \2==1, add 1 to possibility count
)
x                     # tail -= 1
# Multiply the above possibility count with the following:
(                     # Emulated conditional, upon whether tail ≥ \2 + \1
(?=\2\1)          # If yes:
# Call "subroutine" (duplicates it, since this regex flavor lacks
# subroutine calls) to multiply with the above possibility count
(?*
x+(?!\1)
(|)
|
\2+$) | (?!\2\1) # If no: Use possibility multiplier of 1 ) )* # For every possible iteration count, from 0 to the # maximum, add the above to the possibility count \1$                       # Assert tail == \1


# Pure bash, 43

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


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

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

# 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 *)

• Welcome to PPCG! Commented May 11, 2017 at 19:20
• TIO has MLton now. tio.run/nexus/… Commented May 13, 2017 at 17:01
• Oh that's awesome! Thanks! Commented May 13, 2017 at 17:30

## 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.


# Nibbles, 3 2.5 bytes (6 5 nibbles)

*^$_  Attempt This Online! Returns the correct answer of $$\1\$$ for an input of $$\0\$$, as it is generally accepted that $$\0^0=1\$$ (even though this challenge doesn't require it, and several of the other answers take advantage of this and return $$\0\$$, or loop infinitely, for an input of $$\0\$$). The ASCII representation uses ^, but in this context it's a Replicate operator, not exponentiation. Explanation, shown with example input of 7: *^$_
_     # Input coerced to a list: [7]
$# Input: 7 ^ # Replicate: [7, 7, 7, 7, 7, 7, 7] * # Product (returns 1 for an empty list): 823543  The builtin is just 0.5 bytes (1 nibble): ^  Attempt This Online! • Input-coerced-to-a-list is clever. Well done. And it's great to have more nibbles competition... Commented Mar 27, 2023 at 7:26 • @DominicvanEssen Thanks! It was your answer that inspired me to try. (And I didn't realize _ could do that until I started using p. The documentation was a bit unclear on that.) Commented Mar 27, 2023 at 15:53 # Uiua, 4 bytes /×▽.  Try it!  ▽. # list of N Ns /× # product  Note: can also do /×↯. # 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  • Darn, I wanted to do this. :P Commented May 9, 2017 at 22:49 • @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 – user69099 Commented May 12, 2017 at 23:20 • @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. Commented May 12, 2017 at 23:48 • @Dennis thanks for reply! i could not ever imagine such a language before =) – user69099 Commented May 13, 2017 at 0:17 # 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.

# 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!

# 05AB1E, 3 bytes

.DP

.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

• Looks like you enjoyed .D. First time I've seen it used. Commented May 11, 2017 at 19:36
• ah, i dont get what is happening here.. seems to be too exotic and no explanation on how that works. =(
– user69099
Commented May 12, 2017 at 23:28
• @xakepp35 Does that help? Commented May 12, 2017 at 23:32
• .D can be и for -1 (probably a builtin that wasn't available before?) Commented Sep 25, 2020 at 14:53

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. # 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

• Wow, nice language! I like how the source code is compressed from a readable notation.
– user96495
Commented Aug 13, 2020 at 13:09
• Thanks! Glad you like it :) Commented Aug 13, 2020 at 13:44

# 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.

• 26 bytes: |x|(1..x).fold(1,|a,_|a*x) Commented Aug 14, 2020 at 15:14
• @madlaina Feel free to post that as your own solution! It works differently than mine does and is certainly a lot shorter. Commented Aug 14, 2020 at 16:31

# Perl 5 + -p, 17 bytes

$_=eval"$_*"x\$_.1


Try it online!

# 1+, 292725 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.

# ThunnoD, $$\5\log_{256}(96)\approx\$$ 4.12 bytes

ZOA*P


Attempt This Online!

Note: the built-in solution would have been just one character: ^ or @ (either would work).

#### Explanation

ZOA*P # Implicit input
ZO    # Wrap the input in a list
A*  # Repeat it input times
P # Take the product of this list
# Implicit output


# Fortran (GFortran), 73 bytes

integer(selected_int_kind(32))::n


Uses a larger integer type because the implicit integer type overflows doing 10**10. This solution can compute results up to 170141183460469231731687303715884105727.
We make an inline anonymous array of ns : [(n,j=1,n)], take the product(), and print` the result.