Write Power Function without using multiplication(*) and division(/) operators

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.

0 Thoughts on “Write Power Function without using multiplication(*) and division(/) operators

  1. Saiteja Turlapati on September 25, 2015 at 4:34 pm said:

    #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;
    }

  2. Uday Pratap Maurya on October 31, 2015 at 11:30 pm said:

    int power(int x,int y)
    {
    if(y==0)

    }

  3. Uday Pratap Maurya on October 31, 2015 at 11:32 pm said:

    int power(int x,int y)
    {
    if(y==0)
    return 1
    return x*power(x,y-1);
    }

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Post Navigation