问题
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.
回答1:
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 between 0 and x. Divide it by 2 = x2. If the x2 * x2 < x then your search space moves to x2 -> x or else it will be 0 -> x2. If x2 * x2 matches x then your square root is x2. Similar technique for nth root.
回答2:
For those not doing numerical experiments: use the <cmath> functions sqrt and cbrt (cube-root) to construct the any root that is factorable by 2 and 3. For example, the 4th root is sqrt(sqrt(x)) and the 6th root is sqrt(cbrt(x)). If you need something for general use you can construct a recursive function which calls sqrt and cbrt appropriately.
I'm guessing this will give a faster and more accurate answer than pow, if that matters. If it doesn't, just use pow.
来源:https://stackoverflow.com/questions/11266640/finding-nth-root-of-a-number-by-using-divide-and-conquer-method