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

后端 未结 9 1165
一个人的身影
一个人的身影 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:11

    I think in Production recursion just does not provide high end performance.

    double power(double num, int exponent)
    {
    
    double value=1;
    int Originalexpn=exponent;
    double OriginalNumber=num;
    
    if(exponent==0)
        return value;
    
    if(exponent<0)
    {
        num=1/num;
        exponent=abs(exponent);
    }
    
    while(exponent>0)
    {
        value*=num;
        --exponent;
    }
    
    cout << OriginalNumber << " Raised to  " << Originalexpn << " is " << value << endl;
    return value;
    

    }

提交回复
热议问题