user6244076
user6244076

Reputation:

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?

Upvotes: 1

Views: 461

Answers (3)

Salix alba
Salix alba

Reputation: 7824

So we want to solve the equation x^x = n. This is a quite different thing from finding y = n-th root of n in equivalent to y^n = n.

The first thing to do when looking at powers is to consider logs now using natural logs, x ln x = ln n. This does not help us too much and it's not a standard function, so some form of convergence routine will be needed and we want to solve f(x) = x ln x - ln n = 0. This function is nicely monotonic increasing a little faster than just x so it should be easy to solve.

We can use use Newton's method. First find the derivative f'(x) = log x + 1. Starting with a guess x1 an updated guess will be x2 = x1 - f(x1) / f'(x). If you do this a few times it should converge nicely. In my experiment to find x such that x^x = 21 it took just under 6 itterations to converge.

In psudocode

x[0] = ln(n);
for(i=0; i<6;++i ) {
    fx = x[i] * ln( x[i] ) - ln(n); 
    df = ln( x[i] ) + 1;
    x[i+1] = x[i] - fx / df;
}
println(x[6], pow(x[6], x[6]))

Upvotes: 5

MvG
MvG

Reputation: 60858

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.

Upvotes: 4

alexeykuzmin0
alexeykuzmin0

Reputation: 6440

TL;DR: use std::pow.

You want to find 1/nth power of n. There's a standard function which finds yth power of x, called std::pow. It's always a good idea to use a standard function unless you have a strong reason to not.

So, it's better to rephrase this question to "do you have any reasons to not use std::pow?", and, since you're asking community, looks like you don't.

Upvotes: 1

Related Questions