C language power calculation of the efficient solution

  • 2020-04-02 02:47:33
  • OfStack

In this paper, an example is given to demonstrate the efficient method of power calculation in C language. Very practical value. Share with you for your reference. Specific methods are as follows:

The topic is as follows:

So given base, you take the power of base, e to the p

Considering only basic functions and not making any determination of boundary conditions, the following code can be obtained:


#include <iostream>

using namespace std;

int cacExp(int base, int exp)
{
 int result = 1;
 int theBase = 1;
 while (exp)
 {
 if (exp & 0x01)
  result = result * base;
 base = base * base;
 exp = exp >> 1;
 }
 
 return result;
}

int getRecurExp(int base, int exp)
{
 if (exp == 0)
 {
 return 1;
 }

 if (exp == 1)
 {
 return base;
 }

 int result = getRecurExp(base, exp >> 1);
 result *= result;
 if (exp & 0x01)
 result *= base;

 return result;
}

int main()
{
 for (int i = 1; i < 10; i++)
 {
 int result = cacExp(2, i);
 //int result = getRecurExp(2, i);
 cout << "result: " << result << endl;
 }

 return 0;
}

Now let's look at the solution of integer power:


#include <iostream>

using namespace std;

bool equalZero(double number)
{
 if (number < 0.000001 && number > -0.000001)
 return true;
 else
 return false;
}

double _myPow(double base, int exp)
{
 if (exp == 0)
 return 1;
 if (exp == 1)
 return base;

 double result = _myPow(base, exp >> 1);
 result *= result;
 if (exp & 0x01)
 result *= base;

 return result;
}

double _myPow2(double base, int exp)
{
 if (exp == 0)
 return 1;
 
 double result = 1;
 while (exp)
 {
 if (exp & 0x01)
  result *= base;
 base *= base;
 exp = exp >> 1;
 }

 return result;
}

double myPow(double base, int exp)
{
 if (equalZero(base))
 return 0;
 if (exp == 0)
 return 1;

 bool flag = false;
 if (exp < 0)
 {
 flag = true;
 exp = -exp;
 }

 double result = _myPow2(base, exp);
 if (flag)
 {
 result = 1 / result;
 }

 return result;
}

void main()
{
 double base = 2.0;
 int exp = -5;

 double result = myPow(base, exp);
 cout << "result: " << result << endl;
}

It is believed that this paper has certain reference value to the learning of C program algorithm design.


Related articles: