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?
The sqrt() function takes a single argument (in double ) and returns its square root (also in double ). The sqrt() function is defined in math. h header file. To find the square root of int , float or long double data types, you can explicitly convert the type to double using cast operator.
If we have to find cube root for a perfect cube, then we can just apply binary search directly on the space of [1, N], and return x where x equals to x3 . The (mid != start) and condition, in the while loop, help to return a smaller value in case the loop doesn't find a perfect cube root.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With