Home  >  Article  >  Backend Development  >  In a C program, write your own exponentiation function, but you cannot use the multiplication (*) and division (/) operators

In a C program, write your own exponentiation function, but you cannot use the multiplication (*) and division (/) operators

WBOY
WBOYforward
2023-09-06 10:33:05669browse

In a C program, write your own exponentiation function, but you cannot use the multiplication (*) and division (/) operators

The power function is calculated using the multiplication operator, that is, 5n is equal to 5*5*5... n times. In order for this function to work properly without using the multiplication (*) and division (/) operators, we will use a nested loop to repeatedly add the number n times.

Example

#include <iostream>
using namespace std;
int main() {
   int a= 4 , b = 2;
   if (b == 0)
      cout<<"The answer is"<<1;
   int answer = a;
   int increment = a;
   int i, j;
   for(i = 1; i < b; i++) {
      for(j = 1; j < a; j++) {
         answer += increment;
      }
      increment = answer;
   }
   cout<<"The answer is "<<answer;
   return 0;
}

Output

The answer is 16

The above is the detailed content of In a C program, write your own exponentiation function, but you cannot use the multiplication (*) and division (/) operators. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete