Recursive function to calculate x to the power n
| 15 | |
| 16 | // Recursive function to calculate x to the power n |
| 17 | long double power(double x, int n) |
| 18 | { |
| 19 | if (n == 0) return 1.0; |
| 20 | else if (n < 0) return 1.0 / power(x, -n); |
| 21 | else if (n % 2) return x * power(x, n - 1); // n is odd |
| 22 | |
| 23 | // If we make it this far, n > 0 and even |
| 24 | const auto y{ power(x, n / 2) }; |
| 25 | return y * y; |
| 26 | } |