Is there a trick for creating a faster integer modulus than the standard % operator for particular bases?
For my program, I’d be looking for around 1000-4000 (e.g. n%2048). Is there a quicker way to perform n modulus 2048 than simply: n%2048?
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.
If the denominator is known at compile time to be a power of 2, like your example of 2048, you could subtract 1 and do a bitwise-and.
That is:
…where
mis a power of 2.For example:
Bear in mind that a good compiler will have its own optimizations for
%, maybe even enough to be as fast as the above technique. Arithmetic operators tend to be pretty heavily optimized.