Trying to Implement power and factorial functions recursively. C++
All ive got so far are the definitions.
double power(double base, int exponent);
double factorial(double n);
And after this i am completely lost and I'm looking for开发者_JAVA百科 ideas.
Well, 3^4 is 3 * 3 * 3 * 3. Which is 3 * 3^3. 3^3 is 3 * 3^2. 3^2 is 3 * 3^1. 3^1 is 3.
5! is 5 * 4 * 3 * 2 * 1. Which is 5 * 4!. 4! is 4 * 3!. 3! is 3 * 2!. 2! is 2 * 1!. 1! is 1.
That should give you enough to be getting on with...
Start by reading these:
- Exponentiation by squaring
- Factorial
int factorial(int n){
if(n==0) return 1;
else return n*factorial(n-1);}
int power(int number, int p){
if(p==1) return number;
else return number*power(number, p-1);
}
double power(double base, int exponent)
{
if (exponent == 0)
return 1;
else
return base * power(base, exponent - 1);
}
double factorial(double n)
{
if (n == 0)
return 1;
else
return n * factorial(n - 1);
}
Try solving this without using recursion first (if you were actually writing these functions for production code, recursion would hurt their performance anyway). After you get that working, it should be a simple matter to convert it to a recursive algorithm.
HINT:
N! = N * (N-1)!
N^P = product from 1 to P of N
Everyone else seems to assume exp is positive. Possibly could modify to handle 0^0 properly as a NaN rather than 1, if that's important to your application.
double int_power(double base, int exp) {
if (exp == 0)
return 1;
if (exp > 0)
return base*int_power(base, exp-1);
else
return int_power(base, exp+1)/base;
}
精彩评论