Better shift
For 2x where x ∈ ℕ, you are better off writing this as a bit shift
1L << x
instead of a floating point exponentiation
pow(2, x)
both in terms of precision and in terms of performance. In fact, 1L << x
is so easy to compute that I'd prefer writing that instead of array[x]
, so you might perhaps avoid the array altogether.
More errors?
pow(x, 2)
as you write in your code would be x2 which you could compute more easily as x*x
. So which one is it to be, powers of two or squares?
Furthermore, you write pow(size,2)
which uses size
and does not depend on i
. So all values of your array would be equal. I guess that is not what you meant.
Where your error comes from
The reason of the error message is the fact that the result of Math.pow
is double, and implicit conversion from double
to long
is forbidden in Java. You'd have to write an explicit cast, i.e. (long)pow(2, x)
. But that does round towards zero, so a slight numeric error might cause a wrong result. The only exactness guarantee you have for Math.pow
is this:
The computed result must be within 1 ulp of the exact result.
You could add 0.5
before doing the conversion, or use Math.round
instead of the cast, but as you see, you have to know a lot about the internal workings of floating point math to get this correct. Better to stick to integer math and avoid double
and Math.pow
altogether.