How to Get Exponents Without Using the Math.Pow for Java

exponents without math.pow using for loop (in java)

The case with b<0 only makes sense with floating point numbers, so I changed the type of a and the return value to double.

public static double mathPower(double a, int b) 
{
double result = 1;

if (b < 0) {
a = 1.0 / a;
b = -b;
}

for (int i = 0; i < b; i++) {
result = result * a;
}

return result;
}

Getting exponents in a method without using Math.pow()

The int variable is overflowing. Try changing p=p*m to p=(p*m)%10.

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

Try with recursion:

int pow(int base, int power){
if(power == 0) return 1;
return base * pow(base, --power);
}

C++ calculate the power of a number without using pow or loop

pow(x, y) can be written as exp(y * log(x)). As far as I can tell that satisfies the question constraints.

With real x and y, any alternative to that is difficult. Sure, there are silly alternatives using recursion for integral y but using recursion for linear problems is never a particularly good approach.



Related Topics



Leave a reply



Submit