Search code examples
c++mathpow

How can I obtain from n a number which raised to the power of itself equals n?


I have an integer n, and I want to obtain a number which raised to the power of itself equals n. How can I do that?


Solution

  • You question states two things.

    I want to get the nth root of n

    This means finding the solution to x^n=n. For this std::pow(n, 1./n) would be a good thing. Note that 1/n will likely perform integer division if n is an integer, so you may well end up with std::pow(n, 0) which is 1.

    I want to obtain a number which raised to the power of itself equals n

    This is something completely different. You are trying to solve x^x=n for x. Taking the specific case of n=2 and asking Wolfram Alpha about it, it returns

    x = exp(W(log(2)))

    where W would be the Lambert W function. As far as I know this is not part of the C++ standard, so you'll likely have to find a library (in source code or dynamically linked) to compute that function for you. GSL might serve. Generalizing to different values of n should be obvious, though.