How do you do exponentiation in C?

前端 未结 7 1452
执笔经年
执笔经年 2020-12-05 06:31

I tried \"x = y ** e\", but that didn\'t work.

相关标签:
7条回答
  • 2020-12-05 07:03
    int power(int x,int y){
     int r=1;
     do{
      r*=r;
      if(y%2)
       r*=x;
     }while(y>>=1);
     return r;
    };
    

    (iterative)

    int power(int x,int y){
     return y?(y%2?x:1)*power(x*x,y>>1):1;
    };
    

    (if it has to be recursive)

    imo, the algorithm should definitely be O(logn)

    0 讨论(0)
提交回复
热议问题