Write your own Power function without using multiplication(*) and division(/) operators?
(Using Nested Loops)
We can calculate power by using repeated addition.
For example to calculate 5^4.
1) First 5 times add 5, we get 25. (5^2)
2) Then 5 times add 25, we get 125. (5^3)
3) Then 5 time add 125, we get 625 (5^4)
Implementation
/* Works only if a >= 0 and b >= 0 */ int pow(int a, int b) { 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; }
Recursive approach of same problem is left for readers to implement.
#include
#include
int power(int a, int b)
{
int i,sum = 0;
if(b==0) return 1;
for(i=0;i<power(a,b-1);i++)
{
sum += a;
}
return sum;
}
int main()
{
int a,b, sum=0;
printf("Enter a and b\n");
scanf("%d%d",&a,&b);
sum = power(a,b);
printf("POWER=%d",sum);
return 0;
}
int power(int x,int y)
{
if(y==0)
}
int power(int x,int y)
{
if(y==0)
return 1
return x*power(x,y-1);
}