Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Write you own Power without using multiplication(*) and division(/) operators in C Program
Power function is calculated using repeated multiplication i.e. 5n is 5*5*5… n times. To implement this without using multiplication(*) and division(/) operators, we will use nested loops that add numbers repeatedly to simulate multiplication.
Syntax
int power(int base, int exponent);
Example: Using Nested Loops
This approach uses nested loops where the outer loop runs for the exponent value and the inner loop performs repeated addition to simulate multiplication −
#include <stdio.h>
int power(int base, int exponent) {
if (exponent == 0) {
return 1;
}
int result = base;
int temp = base;
int i, j;
for (i = 1; i < exponent; i++) {
int sum = 0;
for (j = 0; j < base; j++) {
sum += temp;
}
temp = sum;
}
return temp;
}
int main() {
int base = 4, exponent = 2;
printf("Base: %d, Exponent: %d<br>", base, exponent);
printf("Result: %d^%d = %d<br>", base, exponent, power(base, exponent));
return 0;
}
Base: 4, Exponent: 2 Result: 4^2 = 16
Example: Using Recursive Addition
An alternative approach using recursion to calculate power by repeated addition −
#include <stdio.h>
int add(int a, int b) {
if (b == 0) return a;
return add(a + 1, b - 1);
}
int multiply(int a, int b) {
if (b == 0) return 0;
return add(a, multiply(a, b - 1));
}
int power(int base, int exponent) {
if (exponent == 0) return 1;
if (exponent == 1) return base;
return multiply(base, power(base, exponent - 1));
}
int main() {
int base = 3, exponent = 3;
printf("Calculating %d^%d using recursive addition<br>", base, exponent);
printf("Result: %d<br>", power(base, exponent));
return 0;
}
Calculating 3^3 using recursive addition Result: 27
Key Points
- The nested loop approach has O(base * exponent) time complexity.
- Always handle the special case when exponent is 0 (result should be 1).
- These methods work only for positive integers due to the addition-based approach.
Conclusion
Power calculation without multiplication operators can be achieved using nested loops or recursive addition. Both approaches simulate multiplication through repeated addition, making them suitable for basic integer power operations.
