For unsigned int x, is it possible to calculate x % 255 (or 2^n – 1 in general) using only the following operators (plus no loop, branch or function call)?
!, ~, &, ^, |, +, <<, >>.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Yes, it’s possible. For 255, it can be done as follows:
This will work if
unsigned intis a 32-bit integer.EDIT: The pattern should be obvious enough to see how this can be generalized to
2^n - 1. You just have to figure out how many iterations are needed. Forn = 8and a 32-bit integer, 4 iterations should be enough.EDIT 2:
Here’s a slightly more optimized version combined with Paul R.’s conditional subtract code: