How to write a function that can calculate power in Java. No loops

后端 未结 9 1103
一个人的身影
一个人的身影 2021-01-03 08:28

I\'ve been trying to write a simple function in Java that can calculate a number to the nth power without using loops.
I then found the Math.pow(a, b) class...

相关标签:
9条回答
  • 2021-01-03 09:34

    Try with recursion:

    int pow(int base, int power){
        if(power == 0) return 1;
        return base * pow(base, --power);
    }
    
    0 讨论(0)
  • 2021-01-03 09:34

    Function to handle +/- exponents with O(log(n)) complexity.

    double power(double x, int n){
     if(n==0)
      return 1;
    
      if(n<0){
          x = 1.0/x;
          n = -n;
      }
     double ret = power(x,n/2);
     ret = ret * ret;
     if(n%2!=0)
       ret = ret * x;
     return ret;
    

    }

    0 讨论(0)
  • 2021-01-03 09:34

    Use this code.

    public int mypow(int a, int e){
        if(e == 1) return a;
        return a * mypow(a,e-1);
    }
    
    0 讨论(0)
提交回复
热议问题