Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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.

share|improve this question
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). – Jeppe Stig Nielsen Feb 24 at 14:36
What about for languages that do not handle power of decimals? – Leaky Nun Mar 31 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. – Adám Mar 31 at 5:37

56 Answers 56

TI-BASIC, 3 bytes


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


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.

share|improve this answer
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. – flawr Feb 24 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? – NinjaBearMonkey Feb 24 at 16:08
Ans is STDIN/STDOUT for TI-Basic. – Timtech Feb 24 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. – Olathe Feb 25 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. – lirtosiast Mar 5 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).
share|improve this answer
Jelly doesn't have a stack. A dyad follow by a monad in a monadic chain behaves like APL's forks. – Dennis Feb 23 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. – Dennis Feb 23 at 4:58
Thanks for the clarification. Naturally, I'm quite intrigued by Jelly (which I still think should be named ȷ or something similar.) – Adám Feb 23 at 5:07

Javascript (ES2016), 11 bytes


I rarely ever use ES7 over ES6.

share|improve this answer
x=>x**x**-1 also works, again for 11 bytes. – Neil Feb 23 at 8:51
All hail the new exponentiation operator! – mbomb007 Feb 23 at 21:33

Python 3, 17 bytes

lambda x:x**(1/x)


share|improve this answer
I quite like lambda x:x**x**-1, but it's not shorter. – Seeq Feb 23 at 6:32
@Seeq Your expression is the same length, but it has the advantage of working in both Python 2 and 3. – mathmandan Feb 23 at 17:54
Python 2's shortest is lambda x:x**x**-1, so it is the same in 2 and 3. – mbomb007 Feb 23 at 21:31
Fails for integer input > 1. Example. – agtoever Feb 24 at 20:53
@agtoever That's Python 2. This answer specifically states Python 3. – Mego Feb 24 at 21:01

J, 2 bytes


Try it with J.js.

How it works

^%  Monadic verb. Argument: y

 %  Inverse; yield 1÷y.
^   Power (hook); compute y ** (1÷y).
share|improve this answer
How do you create the links to J.js? – Adám Feb 24 at 19:59
[text](link). Also, just writing the link will link to it. – VoteToSpam Feb 26 at 8:40
@VoteToSpam I meant how to create a "try it" link that executes a chosen expression. – Adám Apr 8 at 2:08
@Nᴮᶻ There's a last command permalink in the bottom right corner. – Dennis Apr 8 at 2:35

Haskell, 12 11 bytes

Thanks @LambdaFairy for doing some magic:


My old version:

share|improve this answer
(**)<*>(1/) is 11 bytes. – Lambda Fairy Feb 24 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=) – flawr Feb 24 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. – MathematicalOrchid Feb 24 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 at 16:52
@nimi So it's the equivalent of the S combinator i.e. S(**)(1/)? – Neil Mar 2 at 13:03

Pyth, 3 bytes


Trivial challenge, trivial solution...

(noncompeting, 1 byte)


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

share|improve this answer
Does this solution predate the feature of implicit input? – Leaky Nun Apr 7 at 23:39
@KennyLau Yes, by a long time. But I've edited the one-byte solution in anyway. – Doorknob Apr 8 at 4:40

JavaScript ES6, 18 bytes

share|improve this answer

Mathematica, 8 7 4 bytes


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

share|improve this answer
#^#^-1& saves 1 byte. – njpipeorgan Feb 23 at 15:16
NOW it is golfed. – Adám Feb 23 at 23:16
NOW it is golfed. – CalculatorFeline Mar 10 at 2:43
When Mthmtca is released, we are going to rule this board. – Michael Stern Mar 16 at 3:48
Hmm...time to look through my answers and make a compressed version of every builtin... – CalculatorFeline Mar 16 at 4:58

Java 8, 18 bytes


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

interface Test {
  double xthRoot(double x);
share|improve this answer
It's the fact that it's a function – CalculatorFeline Feb 29 at 21:30

Java, 41 bytes

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

Not exactly competitive because Java, but why not?

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

MATL, 5 bytes


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
share|improve this answer

Perl 5, 10 bytes

9 bytes plus 1 for -p

share|improve this answer

R, 19 17 bytes


-2 bytes thanks to @Flounderer

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

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.

share|improve this answer
@NBZ: I usually use Dyalog APL, but this should work with any recent APL that supports function trains. I went and tested it with NARS2000 and ngn/apl and they also worked. – marinus Feb 23 at 23:11
@NBZ: The obvious solution in NARS is √⍨, now that I'm looking at it, but that's a NARS-specific extension. Nevertheless, I'm going to submit that instead, as it's shorter. As for the others, my train gives consistent output (as it logically should) with {⍵*⍵*¯1}, except for 0, where my train behaves as the comments to the question want, but the naive implementation gives an error. – marinus Feb 23 at 23:26
@nbz: In ngn/apl, (+*÷) and {⍵*⍵*¯1} behave exactly equal, at least over the domain ⌈/⍬ ... 0 ... ⌊/⍬, as far as I can tell. (Perhaps there's some value somewhere for which they give slightly different answers because of floating point weirdness, but that's not really something I can see.) In Dyalog, it's going to depend on what ⎕div is. 0*0*¯1 is an error there in any case, (+*÷)0 only if ⎕div=0, otherwise it will be 1. (NARS gives 0 for 0√0, is that correct? If so, +*÷ is correct in ngn, but for Dyalog I think you'd have to resort to something like {⍵=0:0⋄⍵*÷⍵}.) 1/2 – marinus Feb 23 at 23:54
@NBZ: don't worry, I'm not offended, just trying to figure it out. – marinus Feb 23 at 23:57
@nbz: ...shit. I forgot about complex numbers. – marinus Feb 24 at 0:02

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
share|improve this answer
Functions are okay. – CalculatorFeline Feb 24 at 1:18

CJam, 6 bytes


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).
share|improve this answer

Seriously, 5 bytes


Try it online!


,;     input, dupe
  ì@   1/x, swap
    ^  pow
share|improve this answer

Pylons, 5 bytes.


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.
share|improve this answer

Japt, 3 bytes


Test it online!

Very simple: U is the input integer, and q is the root function on numbers.

share|improve this answer

Ruby, 15 Bytes



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

share|improve this answer

O, 6 bytes


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


j.      push two copies of input
  1\/   push 1/input (always float division)
     ^  push pow(input, 1/input)
share|improve this answer
oh hey you did it yay – phase Mar 19 at 4:20

𝔼𝕊𝕄𝕚𝕟, 5 chars / 7 bytes


Try it here (Firefox only).


share|improve this answer

Pyke (commit 29), 6 bytes



D      - duplicate top
 1_    - load -1
   R   - rotate
    ^  - ^**^
     ^ - ^**^
share|improve this answer
Can haz link pls? – cat Feb 24 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 at 17:36

C# - 18 43 41 bytes

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

-2 byes thanks to @VoteToClose

Try it out


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

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

Gogh, 2 bytes

This is the debut answer for Gogh!

Edited (2 bytes):


Original (5 bytes):


See the edit history for an explanation of this method.


÷       “ Duplicate the TOS               ”
 r      “ Push the TOSth root of the STOS ”


Input is implicit and, with the o flag, output is implicit.


$ ./gogh <flags> <code-or-path> <input>

The flags used for this program should be io. The o flag signifies implicit output, and the i flag signifies input as an integer.

To add a trailing newline, add the n flag.

Working:User $ ./gogh nio '÷r' 9
Working:User $ ./gogh nio '÷r' 100

Or, without the n flag:

Working:User $ ./gogh nio '÷r' 9
1.276518Working:User $ ./gogh nio '÷r' 100
1.047129Working:User $
share|improve this answer
Note: This answer is non-competing, as it was developed after the challenge was posted. – Zach Gates Mar 15 at 19:43
@Nᴮᶻ: I wasn't insinuating I would win; just a fact. – Zach Gates Mar 15 at 20:18
What is STOS and TOS? Also, don't flags count in th byte count? – Downgoat Mar 15 at 22:09
using ndo seems to make this also work with floats – Downgoat Mar 15 at 23:41
Also, generally interpreter flags count as extra bytes. – Eᴀsᴛᴇʀʟʏ Iʀᴋ Apr 5 at 21:39

C++, 48 bytes

[](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

share|improve this answer
Does ^ not work in C++ as it does in C? – minerguy31 Feb 23 at 23:18
@minerguy31: ^ is bitwise xor in C (and C++). – marinus Feb 23 at 23:19

PHP 5.6, 32 30 29 bytes




30->29, thank you Dennis!

share|improve this answer

Milky Way 1.6.5, 5 bytes



'      ` 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



$ ./mw <path-to-code> -i <input-integer>
share|improve this answer

Awk, 8 bytes


A shell command to check it

awk '{print $1^$1^-1}'

Longer version (+1) with

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.