Home > Backend Development > C++ > 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
Release: 2023-09-06 10:33:05
forward
702 people have browsed it

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;
}
Copy after login

Output

The answer is 16
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template