MCPcopy Create free account
hub / github.com/Apress/beginning-cpp20 / power

Function power

Exercises/Modules/Chapter 08/Soln8_09.cpp:21–30  ·  view source on GitHub ↗

Recursive function to calculate x to the power n

Source from the content-addressed store, hash-verified

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

Callers 1

mainFunction · 0.70

Calls 1

multFunction · 0.70

Tested by

no test coverage detected