Home > Article > Backend Development > Function to find power in c++
C provides multiple methods for finding powers: use the pow() function or the std::pow() function, which accepts base and exponent parameters. Using a loop, for a positive integer exponent, multiply the base by the exponential times. Use the binary search algorithm to quickly find the power through the divide and conquer method. For negative integer exponents, use the formula 1 / power(base, -exponent) for calculation.
Power raising function in C
There are many ways to raise the power in C. The most straightforward way is to use the pow()
function, which accepts two parameters: base and exponent. For example:
<code class="cpp">#include <cmath> int main() { double base = 2.0; int exponent = 3; double result = pow(base, exponent); // 结果为 8.0 }</code>
For integer exponent, you can use the std::pow()
function, which accepts three parameters: base, integer exponent and target type. For example:
<code class="cpp">#include <cmath> int main() { int base = 2; int exponent = 3; int result = std::pow(base, exponent, long long); // 结果为 8 }</code>
Another way is to use a loop. For example, for positive integer exponents:
<code class="cpp">int power(int base, int exponent) { int result = 1; for (int i = 0; i < exponent; i++) { result *= base; } return result; }</code>
For negative integer exponents, you can use the following formula:
<code class="cpp">int power(int base, int exponent) { if (exponent == 0) { return 1; } else if (exponent < 0) { return 1 / power(base, -exponent); } else { int result = 1; for (int i = 0; i < exponent; i++) { result *= base; } return result; } }</code>
Finally, you can also use the binary search algorithm to quickly find the power. For example:
<code class="cpp">int power(int base, int exponent) { if (exponent == 0) { return 1; } else if (exponent < 0) { return 1 / power(base, -exponent); } else { int result = 1; while (exponent > 0) { if (exponent % 2 == 1) { result *= base; } base *= base; exponent /= 2; } return result; } }</code>
The above is the detailed content of Function to find power in c++. For more information, please follow other related articles on the PHP Chinese website!