# Golf the xᵗʰ root of x

While bored in high-school (when I was half my current age...), I found that $$\f(x) = x^{x^{-1}}\$$ had some interesting properties, including e.g. that the maximum $$\f\$$ for $$\0 ≤ x\$$ is $$\f(e)\$$, and that the binding energy per nucleon of an isotope can be approximated as $$\6 × f(x ÷ 21)\$$...

Anyway, write the shortest function or program that calculates the xth root of x for any number in your language's domain.

## Examples cases

### For all languages

     -1   >       -1
¯0.2   >    -3125
¯0.5   >        4
0.5   >     0.25
1   >        1
2   >    1.414
e   >    1.444
3   >    1.442
100   >    1.047
10000   >    1.001


### For languages that handle complex numbers

   -2   >        -0.7071i
i   >            4.81
2i   >    2.063-0.745i
1+2i   >   1.820-0.1834i
2+2i   >   1.575-0.1003i


### For languages that handle infinities

-1/∞   >   0    (or ∞ or ̃∞)
0   >   0    (or 1 or ∞)
1/∞   >   0
∞   >   1
-∞   >   1


### For languages that handle both infinities and complex numbers

 -∞-2i   >   1      (or ̃∞)


 ̃∞ denotes directed infinity.

• Here is a Wolfram Alpha plot for positive real x. If you omit the x limits in the query, Wolfram Alpha will include negative values of x where the function value depends on a choice of "branch" for the complex logarithm (or for a similar complex function). Feb 24, 2016 at 14:36
• What about for languages that do not handle power of decimals? Mar 31, 2016 at 3:24
• @KennyLau Feel free to post with a note that says so, especially if the algorithm would work, had the language supported it.
Mar 31, 2016 at 5:37

# TI-BASIC, 3 bytes

Ans×√Ans


TI-BASIC uses tokens, so Ans and ×√ are both one byte.

### Explanation

Ans is the easiest way to give input; it is the result of the last expression. ×√ is a function for the x'th root of x, so for example 5×√32 is 2.

• As far as I am aware ans would count as hardcoding inputs into variables and does not seem to be an accepted input method for code-golf. In that case, please make a full program or a function. Feb 24, 2016 at 9:14
• @flawr I can see what you're saying but it seems it's always been done like this. Maybe it warrants a meta post? Feb 24, 2016 at 16:08
• Ans is STDIN/STDOUT for TI-Basic. Feb 24, 2016 at 22:43
• stdin and stdout are text streams, usually for interactive text input and output. Ans is not interactive, unlike some other functions in TI-BASIC, which are interactive. Feb 25, 2016 at 5:21
• @flawr The reason Ans is usually accepted is because its value is set by any expression (expressions are separated by :). Therefore something like 1337:prgmXTHROOT would input 1337, which looks a lot like input via CLAs in a normal language. Mar 5, 2016 at 5:06

# Jelly, 2 bytes

*İ


Try it online!

### How it works

*İ    Main link. Input: n

İ    Inverse; yield 1÷n.
*     Power (fork); compute n ** (1÷n).

• Jelly doesn't have a stack. A dyad follow by a monad in a monadic chain behaves like APL's forks. Feb 23, 2016 at 4:46
• No, J's ^% is a hook (which do not exist in Dyalog APL), not a fork. Jelly and APL code is difficult to compare since Jelly is left-to-right. The nearest equivalent would be ÷*⊢ (also a fork), which computes (1/x)**x because of the different direction. Since Jelly's atoms aren't overloaded (they are either monadic or dyadic, but never both), there can be monadic 1,2,1- and 2,1-forks. Feb 23, 2016 at 4:58
• Thanks for the clarification. Naturally, I'm quite intrigued by Jelly (which I still think should be named ȷ or something similar.)
Feb 23, 2016 at 5:07

# Javascript (ES2016), 11 bytes

x=>x**(1/x)


I rarely ever use ES7 over ES6.

• x=>x**x**-1 also works, again for 11 bytes.
– Neil
Feb 23, 2016 at 8:51
• All hail the new exponentiation operator! Feb 23, 2016 at 21:33

## Python 3, 17 bytes

lambda x:x**(1/x)


Self-explanatory

• I quite like lambda x:x**x**-1, but it's not shorter. Feb 23, 2016 at 6:32
• @Seeq Your expression is the same length, but it has the advantage of working in both Python 2 and 3. Feb 23, 2016 at 17:54
• Python 2's shortest is lambda x:x**x**-1, so it is the same in 2 and 3. Feb 23, 2016 at 21:31
• I couldn't find this answer for ages and was really annoyed when I did.
– user63571
Feb 5, 2017 at 21:09

# Haskell, 12 11 bytes

Thanks @LambdaFairy for doing some magic:

(**)<*>(1/)


My old version:

\x->x**(1/x)

• (**)<*>(1/) is 11 bytes. Feb 24, 2016 at 1:32
• @LambdaFairy Thanks! Do you mind explaining? It looks like you are doing some magic with partially applied functions but as I am quite new to Haskell I do not really understand how this works=) Feb 24, 2016 at 9:02
• This uses the fact that a 1-argument function can be considered an applicative functor (the "reader monad"). The <*> operator takes an applicative that produces a function, and an applicative that produces a value, and applies the function to the value. So in this case, a mind-bending way to apply a 2-argument function to a 1-argument function. Feb 24, 2016 at 16:43
• The function <*> takes 3 arguments, two functions f and g and an argument x. It is defined as (<*>) f g x = f x (g x), i.e. it applies f to x and g x. Here it's partially applied to f and g leaving out x, where f = (**) and g = (1/) (another partially applied function (a section) that calculates the reciprocal value of it's argument). So ( (**)<*>(1/) ) x is (**) x ((1/) x) or written in infix: x ** ((1/) x) and with the section resolved: x ** (1/x). -- Note: <*> is used in function context here and behaves differently in other contexts.
– nimi
Feb 24, 2016 at 16:52
• @nimi So it's the equivalent of the S combinator i.e. S(**)(1/)?
– Neil
Mar 2, 2016 at 13:03

# J, 2 bytes

^%


### How it works

^%  Monadic verb. Argument: y

%  Inverse; yield 1÷y.
^   Power (hook); compute y ** (1÷y).

• I was gonna write this answer. I'm too slow at this. Mar 19, 2017 at 22:02
• @Bijan Over a year too slow, it seems. :P Mar 19, 2017 at 22:21
• I see, I've only been golfing for a week now. Mar 19, 2017 at 22:37

## Pyth, 3 bytes

@QQ


Trivial challenge, trivial solution...

### (noncompeting, 1 byte)

@


This uses the implicit input feature present in a version of Pyth that postdates this challenge.

• Does this solution predate the feature of implicit input? Apr 7, 2016 at 23:39
• @KennyLau Yes, by a long time. But I've edited the one-byte solution in anyway. Apr 8, 2016 at 4:40

# JavaScript ES6, 18 bytes

n=>Math.pow(n,1/n)


## Java 8, 18 bytes

n->Math.pow(n,1/n)


Java isn't in last place?!?!

Test with the following:

import java.lang.Math;

public class Main {
public static void main (String[] args) {
Test test = n->Math.pow(n,1/n);
System.out.println(test.xthRoot(6.0));
}
}

interface Test {
double xthRoot(double x);
}

• It's the fact that it's a function Feb 29, 2016 at 21:30

# R, 19 17 bytes

function(x)x^x^-1


-2 bytes thanks to @Flounderer

• Why not x^(1/x) ? Edit: x^x^-1 seems to work too. Feb 23, 2016 at 20:10
• That's a snippet, and apparently people don't like snippets. Feb 29, 2016 at 21:28
• @CatsAreFluffy it is the definition of a function.
– mnel
Feb 29, 2016 at 21:30

# Java, 41 bytes

float f(float n){return Math.pow(n,1/n);}


Not exactly competitive because Java, but why not?

• Welcome to PPCG! I think you might be missing a return type on this function. Feb 23, 2016 at 18:28
• Oops, got sloppy. A Java 8 answer already beat this one of course... Feb 23, 2016 at 23:18

# MATL, 5 bytes

t-1^^


Try it online!

t       % implicit input x, duplicate
-1     % push -1
^    % power (raise x to -1): gives 1/x
^   % power (raise x to 1/x). Implicit display


# Mathematica, 874 7 bytes

#^#^-1&


More builtin-only answers, and now even shorter! Nope. By definition, the next answer should be 13 bytes. (Fibonacci!) The pattern is still broken. :(

• #^#^-1& saves 1 byte. Feb 23, 2016 at 15:16
• NOW it is golfed.
Feb 23, 2016 at 23:16
• NOW it is golfed. Mar 10, 2016 at 2:43
• When Mthmtca is released, we are going to rule this board. Mar 16, 2016 at 3:48
• Surely just Surd isn't valid as it requires two arguments? Jun 7, 2016 at 14:16

# Perl 5, 10 bytes

9 bytes plus 1 for -p

$_**=1/$_


# Ruby, 15 Bytes

a=->n{n**n**-1}


Ungolfed:

-> is the stabby lambda operator where a=->n is equivalent to a = lambda {|n|}

# NARS APL, 2 bytes

√⍨


NARS supports the √ function, which gives the ⍺-th root of ⍵. Applying commute (⍨) gives a function that, when used monadically, applies its argument to both sides of the given function. Therefore √⍨ xx √ x.

### Other APLs, 3 bytes

⊢*÷


This is a function train, i.e. (F G H) x(F x) G H x. Monadic ⊢ is identity, dyadic * is power, and monadic ÷ is inverse. Therefore, ⊢*÷ is x raised to 1/x.

# Python 2 - 56 bytes

The first actual answer, if I'm correct. Uses Newton's method.

n=x=input();exec"x-=(x**n-n)/(1.*n*x**-~n);"*999;print x

• Functions are okay. Feb 24, 2016 at 1:18

# CJam, 6 bytes

rd_W##


Try it online!

### How it works

rd     e# Read a double D from STDIN and push it on the stack.
_    e# Push a copy of D.
W   e# Push -1.
#  e# Compute D ** -1.
# e# Compute D ** (D ** -1).


# dc, 125 bytes

15k?ddsk1-A 5^*sw1sn0[A 5^ln+_1^+ln1+dsnlw!<y]syr1<y1lk/*sz[si1[li*li1-dsi0<p]spli0<p]so0dsw[lzlw^lwlox/+lw1+dswA 2^!<b]dsbxp


Unlike the other dc answer, this works for all real $$\x\$$ greater than or equal to $$\1 (\$$1 ≤ x$). Accurate to 4-5 places after the decimal. I would have included a TIO link here, but for some reason this throws a segmentation fault with the version there (dc 1.3) whereas it does not with my local version (dc 1.3.95). ### Explanation As dc does not support raising numbers to non-integer exponents to calculate $$\x^\frac1x\$$, this takes advantage of the fact that: $$x^\frac1x = e^\frac{\ln x}x$$ So, to calculate $$\\ln(x)\$$, this also takes advantage of the fact that: $$\int \frac1x dx = \ln(x) + c$$ whose definite integral from $$\1\$$ to $$\b = x\$$ is numerically-approximated in increments of $$\10^{-5}\$$ using the following summation formula: $$\int_1^b \frac1x dx = \sum_{i=1}^{10^{5}(b-1)} \frac 1 {10^5 + i}$$ The resulting sum is then multiplied by $$\\frac1x\$$ to get $$\\frac{\ln(x)}x\$$. $$\e^{\frac{\ln(x)}x}\$$ is then finally calculated using the $$\e^x\$$ Maclaurin Series to 100 terms as follows: $$e^x=\sum^{10^2}_{n=0}\frac{x^n}{n!}$$ This results in our relatively accurate output of $$\x^\frac1x\$$. • +1 This has got to be one of the best dc answers out there. I'm bookmarking this! Mar 19, 2017 at 20:43 • @KritixiLithos Thank you! I appreciate the kind words. :) Mar 19, 2017 at 20:47 • This is why we love this site (sorry Jelly people). – user7467 Apr 30, 2021 at 10:06 ## Seriously, 5 bytes ,;ì@^  Try it online! Explanation: ,;ì@^ ,; input, dupe ì@ 1/x, swap ^ pow  # Pylons, 5 bytes. ideAe  How it works. i # Get command line input. d # Duplicate the top of the stack. e # Raise the top of the stack to the power of the second to the top element of the stack. A # Push -1 to the stack (pre initialized variable). e # Raise the top of the stack to the power of the second to the top element of the stack. # Implicitly print the stack.  # Japt, 3 bytes UqU  Test it online! Very simple: U is the input integer, and q is the root function on numbers. ## C++, 48 bytes #include<math.h> [](auto x){return pow(x,1./x);}  The second line defines an anonymous lambda function. It can be used by assigning it to a function pointer and calling it, or just calling it directly. Try it online • Does ^ not work in C++ as it does in C? Feb 23, 2016 at 23:18 • @minerguy31: ^ is bitwise xor in C (and C++). Feb 23, 2016 at 23:19 # Milky Way 1.6.5, 5 bytes '1'/h  ### Explanation '  Push input 1  Push the integer literal '  Push input /  Divide the STOS by the TOS h  Push the STOS to the power of the TOS  x**(1/x) ### Usage $ ./mw <path-to-code> -i <input-integer>


## O, 6 bytes

j.1\/^


No online link because the online IDE doesn't work (specifically, exponentiation is broken)

Explanation:

j.1\/^
j.      push two copies of input
1\/   push 1/input (always float division)
^  push pow(input, 1/input)

• oh hey you did it yay
Mar 19, 2016 at 4:20

# 𝔼𝕊𝕄𝕚𝕟, 5 chars / 7 bytes

Мű⁽ïï


Try it here (Firefox only).

Trivial.

## Pyke (commit 29), 6 bytes

D1_R^^


Explanation:

D      - duplicate top
1_    - load -1
R   - rotate
^  - ^**^
^ - ^**^

• Can haz link pls?
– cat
Feb 24, 2016 at 17:33
• Oh, I thought you meant there's no implementation available. Yes, the interpreter doesn't have to be hosted, just a link to the repo / source (or docs) will suffice
– cat
Feb 24, 2016 at 17:36

# C# - 1843 41 bytes

float a(float x){return Math.Pow(x,1/x);}


-2 byes thanks to @VoteToClose

Try it out

Note:

First actual attempt at golfing - I know I could do this better.

• Welcome to the crowd! It is exactly because of newcomers that I make trivial challenges like this.
Feb 24, 2016 at 19:29
• Fixed. Thanks for informing me about this Feb 25, 2016 at 15:40
• @crayzeedude No problem at all. Nice job and again, welcome to PPCG! Feb 25, 2016 at 18:00
• Does C# have float? Feb 27, 2016 at 0:31
• Indeed it does. Feb 27, 2016 at 18:29

## C, 23 bytes

#define p(a)pow(a,1./a)


This defines a macro function p which evaluates to the ath root of a.

Thanks to Dennis for reminding me that gcc doesn't require math.h to be included.

Thanks to @EʀɪᴋᴛʜᴇGᴏʟғᴇʀ for reminding me that the space after the first ) is not needed.

Try it online

• With GCC, you don't need to include math.h. Mar 10, 2016 at 3:04
• -1 byte: #define p(a)pow(a,1./a) Jun 14, 2016 at 8:37

# PHP 5.6, 3230 29 bytes

function($x){echo$x**(1/$x);}  or function($x){echo$x**$x**-1;}
`

30->29, thank you Dennis!