top of page
9
C/C++ Program for Write you own Power without using multiplication (*) and division (/) operators.
program solution
#include<stdio.h>
/* Works only if a >= 0 and b >= 0 */
int pow(int a, int b)
{
//base case : anything raised to the power 0 is 1
if (b == 0)
return 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;
}
return answer;
}
/* driver program to test above function */
int main()
{
printf("\n %d", pow(5, 3));
getchar();
return 0;
}
Output
125
bottom of page