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
How to Convert Xml to Java.Util.Map and Vice Versa
How to Mock System.Getproperty Using Mockito
Most Efficient Solution for Reading Clob to String, and String to Clob in Java
How to Specify the Path for Getresourceasstream() Method in Java
How to Unpackage and Repackage a War File
How to Execute SQL Script File in Java
Reading Only the Integers from a Txt File and Adding the Value Up for Each Found
How to Split a Huge Zip File into Multiple Volumes
Java Generics Incompatible Types (No Instance(S) of Type Variable(S) Exist)
Getting Url Parameter in Java and Extract a Specific Text from That Url
Spring JPA Repository: Prevent Update on Save
Json to Pojo With Nested Values
How to Set a Maximum Height With Wrap Content in Android
How to Get File Extension from Content Type
Java.Time.Format.Datetimeparseexception: Text Could Not Be Parsed At Index 3
Iterate Through Each Digit in a Number