Reputation: 53
I´m trying to make very fast MOD operations. I saw in several pages we can do alternatively calculate the MOD using the AND operator with (Divisor-1). Eg.:
result = (100 mod 8) is the same as result = (100 and 7)
It functions perfectly if the divisor is less than 8 bits, but if we calculate (1245 mod 67) we can see the result is different of (1245 and 66).
So, how can I calculate this faster than using the MOD operator provided by VB.NET language?
Thanks!
Upvotes: 0
Views: 185
Reputation:
Well, 100 mod 8
= 100 and 7
works, because 7 is binary 111b
.
Whatever number you have (100 decimal is 1100100b
), the last 3 binary digits (bits) are kept due to the 111b
. For 100, that would be 100b
= 4.
Now consider what you did attempt with 1245 mod 67.
1245 is binary 10011011101b
.
67 is binary 1000011b
.
Can you see, why it's not working?
Upvotes: 0
Reputation: 3615
Using a bitwise AND
only works for modulus powers of 2 (and only positive ones, at that). It does not work for other numbers. See this link
I think that the modulus operator built into the framework is fast and you probably won't be able to improve on it.
Upvotes: 2