Home >Backend Development >C++ >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.
#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; }
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!