Powers of 2 can simply be computed by Bit Shift Operators
int exponent = ...
int powerOf2 = 1 << exponent;
Even for the more general form, you should not compute an exponent by "multiplying n times". Instead, you could do Exponentiation by squaring
Powers of 2 can simply be computed by Bit Shift Operators
int exponent = ...
int powerOf2 = 1 << exponent;
Even for the more general form, you should not compute an exponent by "multiplying n times". Instead, you could do Exponentiation by squaring
Here is a post that allows both negative/positive power calculations.
https://stackoverflow.com/a/23003962/3538289
Function to handle +/- exponents with O(log(n)) complexity.
double power(double x, int n){
if(n==0)
return 1;
if(n<0){
x = 1.0/x;
n = -n;
}
double ret = power(x,n/2);
ret = ret * ret;
if(n%2!=0)
ret = ret * x;
return ret;
}
java - Calculating powers of integers - Stack Overflow
java - Find if a number is a power of two without math function or log function - Stack Overflow
How to raise a number to the power of another without Math.pow() ?
Math.pow() Method Not Operating Correctly? - Programming & Development - Spiceworks Community
Videos
When it's a power of 2 keep in mind that you can use a simple and fast shift expression: 1 << exponent
For example:
22 = 1 << 2 = (int) Math.pow(2, 2)
210 = 1 << 10 = (int) Math.pow(2, 10)
For larger exponents (over 31) use long instead:
232 = 1L << 32 = (long) Math.pow(2, 32)
BTW, in Kotlin you have shl instead of <<:
(Java) 1L << 32 = 1L shl 32 (Kotlin)
Integers are only 32 bits. This means that its max value is 2^31 -1. As you see, for very small numbers, you quickly have a result which can't be represented by an integer anymore. That's why Math.pow uses double.
If you want arbitrary integer precision, use BigInteger.pow. But it's of course less efficient.
You can test if a positive integer n is a power of 2 with something like
(n & (n - 1)) == 0
If n can be non-positive (i.e. negative or zero) you should use
(n > 0) && ((n & (n - 1)) == 0)
If n is truly a power of 2, then in binary it will look like:
10000000...
so n - 1 looks like
01111111...
and when we bitwise-AND them:
10000000...
& 01111111...
-----------
00000000...
Now, if n isn't a power of 2, then its binary representation will have some other 1s in addition to the leading 1, which means that both n and n - 1 will have the same leading 1 bit (since subtracting 1 cannot possibly turn off this bit if there is another 1 in the binary representation somewhere). Hence the & operation cannot produce 0 if n is not a power of 2, since &ing the two leading bits of n and n - 1 will produce 1 in and of itself. This of course assumes that n is positive.
This is also explained in "Fast algorithm to check if a positive number is a power of two" on Wikipedia.
Quick sanity check:
for (int i = 1; i <= 100; i++) {
if ((i & (i - 1)) == 0)
System.out.println(i);
}
1 2 4 8 16 32 64
You can use the bitwise AND (&) operator:
return (num & -num) == num
Why this works?
Consider the number 8, what it is in binary (assuming 32-bits)?
0000 0000 0000 0000 0000 0000 0000 1000
Now let's see how -8 is represented? 1
1111 1111 1111 1111 1111 1111 1111 1000
Finally.. let's calculate 8 & -8:
0000 0000 0000 0000 0000 0000 0000 1000 8
↓↓↓↓ ↓↓↓↓ ↓↓↓↓ ↓↓↓↓ ↓↓↓↓ ↓↓↓↓ ↓↓↓↓ ↓↓↓↓ &
1111 1111 1111 1111 1111 1111 1111 1000 -8
---------------------------------------
0000 0000 0000 0000 0000 0000 0000 1000 8 ¯\_(ツ)_/¯
Now let's take another example, let's say 7, which is not power of two.
0000 0000 0000 0000 0000 0000 0000 0111 7
↓↓↓↓ ↓↓↓↓ ↓↓↓↓ ↓↓↓↓ ↓↓↓↓ ↓↓↓↓ ↓↓↓↓ ↓↓↓↓ &
1111 1111 1111 1111 1111 1111 1111 1001 -7
---------------------------------------
0000 0000 0000 0000 0000 0000 0000 0001 != 7 ¯\_(ة_ة)_/¯
As mentioned by @arshajii, think what will happen if num is zero.. I'll leave the solution for you :)
1 A good way to remember how to calculate that: Begin from the rightmost bit, for each 0 you see, don't change it, when you see 1, leave it and proceed, but from now on, invert all bits. I tried to explain this more here.
I've been asked to create a method that takes two numbers, one for the base and one for the exponent, and then calculate and return the result. How can I go about this without utilizing the Math.pow() ?
What you are asked for is to check if the number passed as an argument to the function is a power of 2, and if it is, what is the power of 2 that sums up to aNumber. (2^x = aNumber) - you want to find x.
For example if you pass 8 to the function, you should return 3, since 2^3 = 8. But if the number isn't the power of 2, you should return -1 - for example if the parameter is 9, there is no integral power of 2 that can result in 9.
Regarding your program, you can make it work with some minor modifications:
What you want to do is make a loop and in every iteration check if the input number is dividable by 2 (aNumber % 2 == 0), and if it is divide it by two (aNumber = aNumber / 2). If you can get to 1 in this way, that means that your number is a power of two, and you just have to count the iterations (number of times you divided aNumber by 2). So your function might look like this:
private static int powerOf2(int aNumber)
{
int power = 0;
if(aNumber % 2 != 0)
{
return -1;
}
else
{
System.out.print(aNumber + " is 2 raised to ");
while (true)
{
if(aNumber % 2 == 0){
aNumber /= 2;
power++;
if(aNumber == 1) return power;
}else{
return -1;
}
}
}
}
Power of 2 means you can get the number by multiplying digit 2, for example:
If the input is 1, then you should return 0 since 20 = 1;
If the input is 2, then you should return 1 since 21 = 2 * 1 = 2;
If the input is 4, then you should return 2 since 22 = 2 * 2 = 4;
If the input is 8, then you should return 2 since 23 = 2 * 2 * 2 = 8;
...
If the input is 0 or negative, you should return -1;
If the input is not a power of 2(for example 3, 5, 7, 10), you should return -1;
I've been trying to calculate the Xn without using math.pow in order to compare it with other algorithms to test their performance and math.pow is too optimized so it will impede me to compare it successfully with other algorithms:
I will use the Xn method to use it within a bruteforce method that evaluates a polynomial at x.
This method will be compared with my horners method.
If I do it using math.pow(x,n) the bruteforce will be faster than horners sometimes and I presume that its because math.pow being too fast.
Here are both method to compare, can you shed some light on why sometimes bruteforce is faster than horners, is it because of math.pow?
//Metodo de Horner:
public double horners(int[] coef_array, double x) {
double resultado = 0;
int c = 0;
for (int i = coef_array.length - 1; i >= 0; i--) {
resultado = (resultado * x) + coef_array[i];
c++;
} //Evalua en x;
set_cant_mult_H(c);
return resultado;
}
//Metodo "obvio", "a pie" o "bruteforceado":
public double brute(int[] coef_array, double x) {
double resultado = 0;
int c = 0;
for (int i = coef_array.length - 1; i >= 0; i--) {
c++;
resultado += coef_array[i] * Math.pow(x, i); // Change this mathpow with something slower?!
}
set_cant_mult_BF(c);
return resultado;
} So to wrap it off, Horners bruteforce are compared but sometimes horners is slower than bruteforce and I presume its because math.pow(x,n) is too fast.
Remember I am using arrays so maybe the new pow method may need to receive an array!
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;
}
You have three main problems:
The
returnstatement inside the loop is breaking it in the first repetition.You're using your
avariable as the loop variable.If you allow negative exponents then the return value should be a double.
public static double mathPower(double a, int b)
{
double result = 1.0;
if (b == 0)
{
result = 1.0;
}
if (b < 0)
{
a = (1.0 / a);
b = -b;
}
for (int i = 0; i < b; i++)
{
result = result * a;
}
return result;
}