Analysis of operation code of power index value in Java

When it comes to power exponents, we'll use math Pow (double a, double B), the returned result is the B power of A.

In Java, when we calculate the n-th power of 2, we can directly use math POW to calculate. Very convenient.

However, given that the result of a power is m and the base a of the power, now the exponent n of the power is required. The log (double) method is provided in math, but only one parameter, m, can be passed in. So the question is, how to meet our requirements simply, conveniently and quickly? The answer is as follows:

n=Math. log(M)/Math. log(a);

This method can meet the calculation of most of our power exponents, but the value accessed and the value passed in each time are double. What if you don't want to turn it? We have a new scheme.

Scheme premise: the base of power index is a multiple of 2.

Here we use the shift operation (the shift operation is based on binary, so the premise of the scheme is this basis). If we find the third power of 2, we can use 2 < < (3-1) to calculate the result.

To the power of 4, we first convert 4 to the power of 2, and then 2 < < (4-1) to calculate the result.

The effect of the following method is that we pass in two numbers added by a multiple of 2, such as 12 (4 + 8), and we automatically calculate [4,8]

For example, 18, we calculate it [2,16]

For example, 22, let's calculate [2,4,16]

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>