user6794537
user6794537

Reputation:

Library Function for logx(n)

I want to calculate the value of log x(n) where x is base and n is any integer. Is there any library function in c++ to do the operation? Or i need to do it manually? If I need to do it manually how can i do that? I have tried to do like that but it says "log x was not declared".

int x,n;
cin>>x>>n;
cout<<logx(n);

enter image description here

x=1,2,3,4,5,6,7,8........ and
n= Any positive integer.

Upvotes: 2

Views: 5034

Answers (2)

eerorika
eerorika

Reputation: 238441

Is there any library function in c++ to do the operation?

There is no such function in the standard library. However, it is easy to implement and therefore an implementation may exist in another library.

Or i need to do it manually?

You can do it manually.

If I need to do it manually how can i do that?

Using the magic of maths. The following equivalence makes the implementation easy, using the natural logarithm function that is provided by the C++ standard library.

logb(x) = loge(x) / loge(b)

Where x is any number greater than 0, logb is logarithm in base b, and loge is the natural logarithm.

I have tried to do like that but it says "log x was not declared".

That is a likely result of trying to guess a name of a function. I would recommend to instead check the reference or a book for what functions are available.

Upvotes: 3

Jonathan Mee
Jonathan Mee

Reputation: 38959

You will have to change the base manually. C++ provides these logarithmic functions:

You can use the Change of Base trick to find your value, because of optimizations you'll want to use log2 to do this.

So for example if you want to do log13(42) you could do:

log2(42) / log2(13)

Upvotes: 3

Related Questions