Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I obtain the cube root in C++?

Tags:

c++

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?

like image 790
Hava Darabi Avatar asked Aug 07 '13 12:08

Hava Darabi


People also ask

Can you do square root in C?

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.

How do you find the cubed root of a binary search?

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.


1 Answers

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:

  • Square root: std::pow(n, 1/2.) (or std::sqrt(n))
  • Cube root: std::pow(n, 1/3.) (or std::cbrt(n) since C++11)
  • Fourth root: std::pow(n, 1/4.)
  • etc.

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.

like image 174
Lightness Races in Orbit Avatar answered Sep 22 '22 08:09

Lightness Races in Orbit