Saturday 4 August 2012

Calculate a to the power of b in o(log b) complexity.


#include<iostream.h>
#include<conio.h>
int power(int base,int exp)
{
      if(exp==1)
            return base;
      if(exp%2==0)
            return (power(base*base,exp/2));
      else
            return base*(power(base*base,exp/2));
}
void main()
{
      clrscr();
      int base,exponent,p;
      cout<<"BASE : ";
      cin>>base;
      cout<<"\nEXPONENT : ";
      cin>>exponent;
      p=power(base,exponent);
      cout<<"a ^ b = "<<p;
      getch();
}

No comments:

Post a Comment