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

Function power

Exercises/NoModules/Chapter 08/Soln8_08.cpp:17–26  ·  view source on GitHub ↗

Recursive function to calculate x to the power n

Source from the content-addressed store, hash-verified

15
16// Recursive function to calculate x to the power n
17long 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}

Callers 1

mainFunction · 0.70

Calls

no outgoing calls

Tested by

no test coverage detected