0

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!

David BS
  • 53
  • 5
  • 1
    This method of calculating MOD works for 2^n, but I don't believe it works for non-powers of 2 (e.g. 8 MOD 6 = 2, but 8 AND 5 = 0). – Jerry Federspiel Aug 03 '15 at 18:04
  • 1
    Are you sure there's a performance bottleneck on the MOD operator? – Jerry Federspiel Aug 03 '15 at 18:05
  • Thank you for answers. If we consider the positives 2^N numbers, yes, we have a good improvement related to MOD. But since the tip just function to "power of 2" numbers, I have to consider the MOD instruction as the default. – David BS Aug 03 '15 at 18:44

2 Answers2

2

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.

Community
  • 1
  • 1
Douglas Barbin
  • 3,595
  • 2
  • 14
  • 34
0

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?