Nearest integer value up to 20

If I have a number greater than 20, but this can be divided by 2 without any residues, I want to determine which number is closest to me 20. For example:

During 2048, dividing by 2 would increase me enough to 16, which is closest to 20. If the number is 800, the closest is 25.

I can write a loop and just continue to share and compare the range and choose the closest value. Maybe a simpler way, perhaps by bit shifting?

EDIT: When I say that it is evenly divisible by 2, I mean that it divides everything to two. A number of 70 would only divide up to 35 evenly. A number equal to 2048 or 1024 will be evenly distributed to 2.

Examples of numbers: 2048, 1920, 1600, 1536, 1080..640, 352, 320, 176. These are typical sizes of images from cameras.

+6
source share
3 answers

If your input number is x , I think you want x/2^[(log x/14)/log 2] if you want your target number to be in the range [14,27] .

In java code, the Math log function will come in handy (although the base-2 logarithm will be even better), and you will also need an integer listing (or somehow find the largest integer smaller than the expression in [] ).

What this means: let x be your input and y be the number you want to find. Then x=y*2^n for unknown n , and y is about 20 (see above). Obviously, n is the logarithm of the base 2 x/y . Now, if you choose the smallest possible y , name it y' , the integer part of the base-2 x/y' logarithm is still the n that we are looking for, if only x/y' is different from x/y > by more than 2 times, which, by the assumption of repeated division by 2, cannot. Thus, we have n and, therefore, y=x/2^n .

+5
source

You really want to trim all trailing zero bits until you get a number greater than 13.

Another way to do this is to trim all zeros and add them back if the result is too small.

 public static long func(long num) { if (num <= 26) return num; long trimZeros = num >>> Long.numberOfTrailingZeros(num); while(trimZeros <= 13) trimZeros <<= 1; return trimZeros; } 

26 is closer to 20 than 13, but 14 is closer to 20 than 28.

+2
source

If you want to use switching, you can start with something like this:

 public static int func2(int val) { int min = Integer.MAX_VALUE; int close = 0; while (val > 1) { val = val >>> 1; if (Math.abs(val - 20) < min) { min = Math.abs(val - 20); close = val; } } return close; } public static void main() { for ( int i : new int []{2048, 1920, 1600, 1536, 1080, 640, 352, 320, 176}) { System.out.println( i + " -> " + func2( i )); } } 

Print

 2048 -> 16 1920 -> 15 1600 -> 25 1536 -> 24 1080 -> 16 640 -> 20 352 -> 22 320 -> 20 176 -> 22 
+1
source

All Articles