I need help on how to get nth root of some number.
User enters number n and number he wants root of. I need to solve this without cmath lib and with divide and conquer method.
Here's my code that doesn't work yet:
#include<iostream>
using namespace std;
float pow(float a,float c){
if (a == 0)
return 0;
else if(a == 1)
return 1;
else{
float p = pow(a,(c/2));
if(c%2)
return p*p*a;
else
return p*p;
}
}
int main(){
float a,b;
float c;
cout << "Enter positive number:(base)" << endl;
do{
cin >> a;
}while (a < 0);
cout << "Enter number: (root)" << endl;
cin >> b;
c = 1/b;
cout << "Result:"<<pow(a,c) << endl;
system("pause");
return 0;
}
Any ideas on how to approach this problem would be more than useful.
Let me tell you how you can use divide and conquer for finding square root. The nth root would be similar.
For a given number
x
, you need to search for it's square root between0
andx
. Divide it by2
=x2
. If thex2 * x2
<x
then your search space moves tox2 -> x
or else it will be0 -> x2
. Ifx2 * x2
matchesx
then your square root isx2
. Similar technique for nth root.For those not doing numerical experiments: use the
<cmath>
functionssqrt
andcbrt
(cube-root) to construct the any root that is factorable by 2 and 3. For example, the 4th root issqrt(sqrt(x))
and the 6th root issqrt(cbrt(x))
. If you need something for general use you can construct a recursive function which callssqrt
andcbrt
appropriately.I'm guessing this will give a faster and more accurate answer than
pow
, if that matters. If it doesn't, just usepow
.