'How can I obtain the cube root in 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?
Solution 1:[1]
in C++11 std::cbrt was introduced as part of math library, you may refer
Solution 2:[2]
include <cmath>
std::pow(n, 1./3.)
Also, in C++11 there is cbrt in the same header.
Solution 3:[3]
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.
Solution 4:[4]
Just to point this out, though we can use both ways but
long long res = pow(1e9, 1.0/3);
long long res2 = cbrt(1e9);
cout<<res<<endl;
cout<<res2<<endl;
returns
999
1000
So, in order to get the correct results with pow function we need to add an offset of 0.5 with the actual number or use a double data type i.e.
long long res = pow(1e9+0.5, 1.0/3)
double res = pow(1e9, 1.0/3)
more detailed explanation here C++ pow unusual type conversion
Solution 5:[5]
Actually the round must go for the above solutions to work.
The Correct solution would be
ans = round(pow(n, 1./3.));
Solution 6:[6]
The solution for this problem is
cube_root = pow(n,(float)1/3);
and you should #include <math.h> library file
Older standards of C/C++ don't support cbrt() function.
When we write code like cube_root = pow(n,1/3); the compiler thinks 1/3 = 0 (division problem in C/C++), so you need to do typecasting using (float)1/3 in order to get the correct answer
#include<iostream.h>
#include<conio.h>
#include<math.h>
using namespace std;
int main(){
float n = 64 , cube_root ;
clrscr();
cube_root = pow(n , (float)1/3);
cout<<"cube root = "<<cube_root<<endl;
getch();
return 0;
}
cube root = 4
Solution 7:[7]
You can try this C algorithm :
// return a number that, when multiplied by itself twice, makes N.
unsigned cube_root(unsigned n){
unsigned a = 0, b;
for (int c = sizeof(unsigned) * CHAR_BIT / 3 * 3 ; c >= 0; c -= 3) {
a <<= 1;
b = 3 * a * (a + 1) + 1;
if (n >> c >= b)
n -= b << c, ++a;
}
return a;
}
Solution 8:[8]
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++;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | OrangeDog |
| Solution 3 | Sebastian Redl |
| Solution 4 | |
| Solution 5 | Sagar Kumar |
| Solution 6 | |
| Solution 7 | Michel |
| Solution 8 | Pranjal |
