24
\$\begingroup\$

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.

\$\endgroup\$
  • 1
    \$\begingroup\$ 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). \$\endgroup\$ – Jeppe Stig Nielsen Feb 24 '16 at 14:36
  • \$\begingroup\$ What about for languages that do not handle power of decimals? \$\endgroup\$ – Leaky Nun Mar 31 '16 at 3:24
  • 1
    \$\begingroup\$ @KennyLau Feel free to post with a note that says so, especially if the algorithm would work, had the language supported it. \$\endgroup\$ – Adám Mar 31 '16 at 5:37

61 Answers 61

3
\$\begingroup\$

Awk, 8 bytes

$1^$1^-1

A shell command to check it

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

Longer version (+1) with

$1^(1/$1)
\$\endgroup\$
3
\$\begingroup\$

MATLAB, 11bytes

@(x)x^(1/x)

Creates an anonymous function. This will work with all test cases including complex numbers and infinities.

This also works with Octave. You can try online here. Simply enter something like:

f=@(x)x^(1/x)

At the command line of the online interpreter, then do:

f(-1)

To test.

\$\endgroup\$
3
\$\begingroup\$

C#, 25 bytes, type: double

Bare form of a lambda expression:

x=>System.Math.Pow(x,1/x)

The expression can be assigned to a function variable, e.g. (Func<double, double>), ...

System. can be omitted, if using System; is used (but more bytes).

Complete test program (143 bytes) with the input of the question:

using System;class P{static void Main(){Array.ForEach(new double[]{-.2,-.5,.5,1,2,Math.E,3,100,10000},x=>Console.WriteLine(Math.Pow(x,1/x)));}}

Result:

-3125
4
0,25
1
1,4142135623731
1,44466786100977
1,44224957030741
1,0471285480509
1,0009214583193

C#, 37 bytes, type: Complex

x=>System.Numerics.Complex.Pow(x,1/x)

Also the assembly for System.Numerics needs to be referenced. The division operator is overloaded for complex arguments.

Test program (189 bytes) with the input of the question for complex numbers:

using System;using C=System.Numerics.Complex;class P{static void Main(){Array.ForEach(new C[]{new C(-2,0),new C(0,1),new C(0,2),new C(1,2),new C(2,2)},x=>Console.WriteLine(C.Pow(x,1/x)));}}

Result:

(4,32963728535968E-17, -0,707106781186548)
(4,81047738096535, 0)
(2,0628722350809, -0,745007062179724)
(1,81984053615444, -0,183434723804562)
(1,57500291115344, -0,100274868564155)

Test program (264 bytes) with infinity:

using System;using C=System.Numerics.Complex;class P{static void Main(){var p=double.PositiveInfinity;var n=double.NegativeInfinity;Array.ForEach(new C[]{new C(-1/p,0),new C(0,0),new C(1/p,0),new C(p,0),new C(n,0),new C(n,2) },x=>Console.WriteLine(C.Pow(x,1/x)));}}

Result:

(0, 0)
(0, 0)
(0, 0)
(1, 0)
(1, 0)
(1, 0)
\$\endgroup\$
3
\$\begingroup\$

Vitsy, 4 + 1 (function declaration) = 5 bytes

Hey, look, my language actually does this. Go figure.

Di^^
D    Duplicate the top item (input)
 i   Push -1.
  ^  Pop top (-1), put the second to top to the power of the popped item (x^-1)
   ^ Same as above, except we now have the desired number.

This is a function that leaves the value requested on the stack. For view-ability, I have also made the program output on the Try it Online! link.

Try it Online!

\$\endgroup\$
  • \$\begingroup\$ -1: Anonymous functions are allowed. \$\endgroup\$ – Erik the Outgolfer Jun 14 '16 at 8:51
  • \$\begingroup\$ @EʀɪᴋᴛʜᴇGᴏʟғᴇʀ Unfortunately, that's what I thought. However, I was informed that I would have to include the return character before the function in order for it to be valid. \$\endgroup\$ – Addison Crump Jun 15 '16 at 16:21
3
\$\begingroup\$

PARI/GP, 9 bytes

x->x^x^-1

This is shorter than the alternatives x->x^(1/x) and x->sqrtn(x,x). It uses the right-associativity of ^ and the strong binding of the unary -. GP isn't quite functional enough to curry (a,b)->sqrtn(a,b) into (x)->sqrtn(x,x); the best it can manage is x->call(sqrtn,[x,x]) which is far too long.

\$\endgroup\$
2
\$\begingroup\$

Codename Dragon, 16 bytes

a=<>;dispa^(1/a)

I'm abusing the lack of a syntax error.

Ungolfed:

disp((a=<>)^(1/a))

This is a simple program that takes input through <>.

You can find an interpreter here, no github site yet.

\$\endgroup\$
2
\$\begingroup\$

Jolf, 5 bytes

Try it here!

^j/1j
 j    input
^ /1j to the 1/j pow.
\$\endgroup\$
2
\$\begingroup\$

Gnuplot, 13 bytes

f(x)=x**(1/x)

or

f(x)=x**x**-1
\$\endgroup\$
2
\$\begingroup\$

Brachylog, 8 7 bytes

Thanks to Fatalize for saving a byte.

^?^-1=.

Explanation

^?^-1=.
     =.   unify output with
^?^-1     input raised to the 1/input power
\$\endgroup\$
  • \$\begingroup\$ You can save one byte: you don't need the first ?, it is implicitely the current variable at the beginning of the predicate. \$\endgroup\$ – Fatalize Mar 16 '16 at 20:28
2
\$\begingroup\$

Lua, 20

n=(...)print(n^n^-1)

How it works:

n=(...)              Take input and store at n
       print(
             n^n^-1  n^(n^(-1))
                   )
\$\endgroup\$
2
\$\begingroup\$

dc, 8 6 chars

Outputs to the top of the stack:

?d1r/^

Or if I can expect the input at the top of the stack, this 5 char solution works too:

d1r/^

Explanation:

?        take input from STDIN and execute it (numbers are executed by pushing to the stack)
 d1r     duplicate top of stack, push 1 and swap them
    /^   divide and exponentiate

Alas, dc does not allow for fractional exponents so this answer does not actually work for any given inputs above 1, and gives the wrong answer for 0 < input < 1. It does the same thing as many of the other programs though.

\$\endgroup\$
2
\$\begingroup\$

Factor, 14 10 bytes

1 over / ^

Expects input on top of the stack.

\$\endgroup\$
2
\$\begingroup\$

Convex, 3 bytes

Convex is a new language that I am developing that is heavily based on CJam and Golfscript. The interpreter and IDE can be found here. Input is an integer into the command line arguments. Indexes are one-based. Uses the CP-1252 encoding. This answer in non-competing as it was created after this challenge.

_¹#

Explanation:

    Implied input
_   Duplicate top of stack
 ¹  Find reciprocal
  # Power
    Implied output
\$\endgroup\$
  • \$\begingroup\$ Can be found... where? \$\endgroup\$ – cat Apr 5 '16 at 21:47
  • \$\begingroup\$ @cat oops. Fixed. Note that I literally just updated the interpreter though, but this still works. \$\endgroup\$ – GamrCorps Apr 6 '16 at 2:04
2
\$\begingroup\$

Racket, 28 22 bytes

(λ(n)(expt n(/ 1 n)))

@cat gets credit for the 6 byte save. Thanks!

Seriously, Racket is impossible to golf with :). Nothing to see here, move along!

\$\endgroup\$
  • 1
    \$\begingroup\$ You can do (λ(n)(expt n(/ 1 n))) as an anonymous function for 22 bytes \$\endgroup\$ – cat Apr 5 '16 at 21:43
  • 1
    \$\begingroup\$ We need a golfing dialect of Racket, like we need a golfing dialect of Factor except people have already made LISPs for golf and the code becomes mostly parentheses. \$\endgroup\$ – cat Apr 6 '16 at 2:08
  • 1
    \$\begingroup\$ I forgot that anonymous functions are generally okay. We definitely could use a lovely LISP for golfing. But yeah, I can only imagine the parens are still going to reduce competitiveness. \$\endgroup\$ – Winny Apr 6 '16 at 6:44
2
\$\begingroup\$

Python 3: 34

n=complex(input());print(n**(1/n))

Unless I'm missing something this would do nicely. I like that Python normally uses spaces, but this solution doesn't need them.

\$\endgroup\$
  • \$\begingroup\$ Why the int(...)? \$\endgroup\$ – Adám Jun 14 '16 at 7:19
  • \$\begingroup\$ Python 3 won't implicitly take an input as an integer. So it needs to be converted for the arithmetic in the second statement. Unless it does work for this scenarios in which case my solution will be shorter \$\endgroup\$ – george Jun 14 '16 at 7:29
  • \$\begingroup\$ OP: for any number in your language's domain \$\endgroup\$ – Adám Jun 14 '16 at 7:37
  • \$\begingroup\$ @Adám I'm not sure that I understand that part then. I just thought it meant it would take any number in the normal base. For Python that is base 10. \$\endgroup\$ – george Jun 14 '16 at 8:05
  • \$\begingroup\$ If Python natively handles real numbers, then input may be a real (i.e. non-integer). \$\endgroup\$ – Adám Jun 14 '16 at 8:11
2
\$\begingroup\$

05AB1E, 3 bytes (non-competing)

Non-competing, because 05AB1E couldn't parse floats correctly at the time the challenge was posted. Code:

Dzm

Explanation:

D    # Duplicate the input
 z   # Inverse, 1 ÷ input
  m  # Power, calculating input ** (1 ÷ input)

Try it online!.

\$\endgroup\$
  • \$\begingroup\$ Wait a minute! If it couldn't parse floats, then floats were not in the domain, and so an integer solution was acceptable. \$\endgroup\$ – Adám Jun 14 '16 at 11:01
  • \$\begingroup\$ @Adám Oh, I didn't know that! The code would still be the same though :p. \$\endgroup\$ – Adnan Jun 14 '16 at 11:02
  • \$\begingroup\$ Weird how -.2 still returns -3124.999999999999 \$\endgroup\$ – Magic Octopus Urn Mar 21 '17 at 14:36
  • \$\begingroup\$ And, also, I think he meant you can remove the non-competing tag. \$\endgroup\$ – Magic Octopus Urn Mar 21 '17 at 14:36
  • \$\begingroup\$ @carusocomputing Hmm, how is that weird then? \$\endgroup\$ – Adnan Mar 21 '17 at 14:42
2
\$\begingroup\$

(Noncompeting) Quetzalcoatl, 4 bytes

c.I?

Explanation:

c    # Input
 .   # Duplicate
  I  # Inverse
   ? # Power

This answer was too short to post before adding this sentence.

\$\endgroup\$
  • \$\begingroup\$ So... "Quetzalcoatl" can have an operator which finds x^x^-1... \$\endgroup\$ – Erik the Outgolfer Jun 14 '16 at 8:57
  • \$\begingroup\$ @EʀɪᴋᴛʜᴇGᴏʟғᴇʀ What operator are you referring to? \$\endgroup\$ – NoOneIsHere Jun 14 '16 at 14:39
  • \$\begingroup\$ Like Python's a**a**-1. \$\endgroup\$ – Erik the Outgolfer Jun 14 '16 at 14:43
2
\$\begingroup\$

Bean, 11 bytes (non-competing)

Hexdump:

00000000 26 4c a0 43 95 4c a5 3a 8e 20 43  &L C.L¥:. C
0000000b

Equivalent JavaScript:

A**(1/A)

Implicitly converts first line of input to number as A and implicitly outputs the result of the expression.

Try the demo here.

Try the test suite here.

\$\endgroup\$
  • \$\begingroup\$ Sorry, just noticed the post date of the question. I had previously assumed it was new \$\endgroup\$ – Patrick Roberts Feb 5 '17 at 12:06
1
\$\begingroup\$

TI-Basic, 4 bytes

Ans^Ansֿ ¹

Since TI-Basic is tokenized, this code is a mere four bytes.

\$\endgroup\$
  • 3
    \$\begingroup\$ We already have a TI-BASIC answer at 3 bytes. \$\endgroup\$ – Zach Gates Feb 23 '16 at 23:37
  • \$\begingroup\$ Is ans accepted as input method? \$\endgroup\$ – flawr Feb 24 '16 at 0:06
1
\$\begingroup\$

Mouse-2002, 13 bytes

x:x.b/x.&ROOT

Other programs assume the number's on the top of the stack and so shall I.

x:    ~ put TOS in x
x.    ~ push x
b /   ~ divide by 1
x.    ~ push x again
&ROOT ~ y to the x root
\$\endgroup\$
1
\$\begingroup\$

Scala, 33 bytes

def f=(x:Double)=>Math.pow(x,1/x)
\$\endgroup\$
1
\$\begingroup\$

Perl, 11 bytes

Added 2 bytes for -pn.

$_**=1/$_

Try it here !

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

(Non-competing) Pyth, 1 byte

@

Pyth takes implicit input, so @ is really equivalent to @QQ, where Q is the evaluated input.

Try it online!

\$\endgroup\$
  • \$\begingroup\$ Why is it non-competing? Did you get an answer about implicit input predating the OP? \$\endgroup\$ – Adám Apr 8 '16 at 1:35
  • \$\begingroup\$ I am not sure yet, but I think Doorknob would have this solution if he has known about the implicit input. \$\endgroup\$ – Leaky Nun Apr 8 '16 at 1:45
  • 2
    \$\begingroup\$ @Nᴮᶻ Implicit input was introduced with this commit, which postdates this challenge by a month. \$\endgroup\$ – Dennis Apr 8 '16 at 4:44
  • \$\begingroup\$ @KennyLau this doesn't have to non-competing. \$\endgroup\$ – Rɪᴋᴇʀ Apr 8 '16 at 17:46
  • 1
    \$\begingroup\$ Why not? This feature postdates the challenge. \$\endgroup\$ – Leaky Nun Apr 8 '16 at 23:03
1
\$\begingroup\$

Mumps, 14 Bytes

R I W I**(1/I)

R reads from input into variable I, and the W (write) statement does the mathematical calculations.

I will warn you: the output will be ugly as there are no implied newlines in Mumps, and at least the way I read the challenge, the OP didn't require them. If you did want cleaner output, add 2 bytes and add a newline:

R I W !,I**(1/I)
\$\endgroup\$
1
\$\begingroup\$

SQL (MySQL), 60 bytes

CREATE FUNCTION G(X REAL) RETURNS REAL RETURN POWER(X,1./X);

Caps lock is cruise control for cool golf.

\$\endgroup\$
  • \$\begingroup\$ Can you do )RETURNS instead of ) RETURNS for -1 byte? \$\endgroup\$ – Erik the Outgolfer Jun 14 '16 at 8:59
  • \$\begingroup\$ @EʀɪᴋᴛʜᴇGᴏʟғᴇʀ Possibly; I don't have a MySQL server handy right now to test it, though. \$\endgroup\$ – Mego Jun 14 '16 at 9:00
1
\$\begingroup\$

Desmos, 14 bytes

a=1
\sqrt[a]{a}

Demonstration

\$\endgroup\$
  • \$\begingroup\$ That looks interesting. So \sqrt is a root-of function, and not square-root? \$\endgroup\$ – Adám Jun 6 '16 at 20:04
  • \$\begingroup\$ @Adám It is TeX. \sqrt is the Square Root symbol, and the brackets change the root. \$\endgroup\$ – NoOneIsHere Jun 6 '16 at 20:50
1
\$\begingroup\$

tcl, 23

I post two approaches which occupy the exact same number of bytes.

puts [expr $n**(1./$n)]

puts [expr $n**$n**-1.]

Available to test on http://rextester.com/EMW19680

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

QBIC, 9 bytes

:?a^(1/a)

Gets a numeric input from the command line and does the math...

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

SmileBASIC, 18 bytes

INPUT X?POW(X,1/X)
\$\endgroup\$
1
\$\begingroup\$

Common Lisp, 24 bytes

(lambda(x)(expt 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

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