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.
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;
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With