Creating a basic algorithm is a more interesting version

See change history "Creating a basic algorithm . " There was a tangible sense of disappointment among the respondents when the OP changed the question by canceling some interesting answers. So, I think, why not ask the original question again to give answers to these questions.

So basically I want to find an easier way to do this:

if(size == 2) unit /= 2; if(size == 2 || size == 6) unit /= 2; if(size == 2 || size == 6 || size == 10) unit /= 2; 

So basically this is checking to see if size is 2, and then each new line adds 4 to the last size check.

I need up to 256.

I want to know if there is an easy way to do this.

+7
java algorithm
source share
1 answer

The fundamental criterion for numbers tested for equality here is that the remainder of size / 4 is 2. This can be detected using the modulo % operator:

 size % 4 == 2 

Then the question arises how many times to divide unit by 2. For the above examples:

  • For size == 2 , unit /= 8 (matches all 3 conditions);
  • For size == 6 , unit /= 4 (corresponds to the second 2 conditions);
  • For size == 10 , unit /= 2 (matches the last condition).

So, the smaller the number, the more it divides by 8. If the maximum size set to 10, unit is divisible by 2 ^ (1 + (10 - size) / 4) . This can be summarized using the right-shift operator:

 unit >>= 1 + (10 - size) / 4 

or, more generally:

 unit >>= 1 + (max_number - size) / 4 

where max_number % 4 == 2 .

Setting max_number = 254 (256 is asked in the question, but will not be present in the expression, the last verified number will be 254) and note that we only apply this in the case 2 <= size <= 254 , we can express the final answer as:

 if (size % 4 == 2 && size >= 2 && size <= 254) { unit >>= 1 + (254 - size) / 4; } 

Actually, the condition can be expressed more briefly (but, of course, less readable) as:

 if ((size & 0xffffff03) == 2) 

As @PaulBoddington noted, care must be taken with the size of the right shift: if the unit is int and the number of bits shifted is greater than 31, then unit should simply be set to zero.

+9
source share

All Articles