Using int, double and long in calculation of powers
18,538
Solution 1
You could do it by yourself:
public static long powerN(
int number,
int power
) {
if(power == 0) return 1;
int result = number;
while(power > 1) {
result*=number;
power--;
}
return (long)result;
}
PS: This does not handle negative powers.
Solution 2
Wait! If you're doing it yourself, use a faster algorithm like Exponentiation by squaring, something like this:
long powerN(long number, int power){
long res = 1;
long sq = number;
while(power > 0){
if(power % 2 == 1){
res *= sq;
}
sq = sq * sq;
power /= 2;
}
return res;
}
Author by
MelJ
Updated on June 19, 2022Comments
-
MelJ about 2 years
I'm having trouble figuring out when to use int, double and long.
I'm working on calculating the power of an integer and return the result as long as the power provided is not a negative number.
For the assignment, I'm required to use the following code to start:
public static long powerN(int number, int power) {
Here's what I came up with:
public class PowerCalculator { /** * Calculate the non-negative power of an integer number. If a negative power is input, the method returns 1. * * @param number The number to take power. * @param power The power factor to be taken to. * @return The calculation result after taking power of the integer number. */ public static long powerN(int number, int power) { if (power > 0) { double result = (Math.pow(number, power)); return result; } else { return 1; } } }
I know I'm messing up the use of int, double or long but I don't know how to fix it.
-
Martin M J about 9 yearsWhat is
result * number
ifresult == 0
? Your method will always return 0. -
nramirez about 9 yearsI just edited my answer, I missed initializing result with number. result*=number is the same that saying result = result * number. @martin-m-j
-
MelJ about 9 yearsThanks. The assignment said we could come up with our own implementation so I stuck to math.pow and made the edit: (long) result. I just submitted the code. You guys have been very helpful.
-
Olexii about 7 yearsThis code doesn't work in a proper way. 1) x pow n will return x pow n+1 2) x pow 0 should return 1, but will return x*x
-
Anton Krug over 6 yearsshould be the while condition different? while(power > 1) instead?