I know how to obtain the square root of a number using the sqrt
function.
How can I obtain the cube root of a number?
include <cmath>
std::pow(n, 1./3.)
Also, in C++11 there is cbrt
in the same header.
Math for Dummies.
The nth root of x is equal to x^(1/n), so use std::pow
. But I don't see what this has to with operator overloading.
sqrt
stands for "square root", and "square root" means raising to the power of 1/2
. There is no such thing as "square root with root 2", or "square root with root 3". For other roots, you change the first word; in your case, you are seeking how to perform cube rooting.
Before C++11, there is no specific function for this, but you can go back to first principles:
std::pow(n, 1/2.)
(or std::sqrt(n))std::pow(n, 1/3.)
(or std::cbrt(n) since C++11)std::pow(n, 1/4.)
If you're expecting to pass negative values for n
, avoid the std::pow
solution — it doesn't support negative inputs with fractional exponents, and this is why std::cbrt
was added:
std::cout << std::pow(-8, 1/3.) << '\n'; // Output: -nan
std::cout << std::cbrt(-8) << '\n'; // Output: -2
N.B. That .
is really important, because otherwise 1/3
uses integer division and results in 0
.
in C++11 std::cbrt
was introduced as part of math library, you may refer
sqrt()
is not an operator.sqrt()
.Please explain why do you need to overload sqrt()
so we can help you to do what you want.
I would discourage any of the above methods as they didn't work for me. I did pow(64, 1/3.) along with pow(64, 1./3.) but the answer I got was 3
Here's my logic.
ans = pow(n, 1/3.);
if (pow(ans, 3) != n){
ans++;
}