Is there any alternative to using % (modulus) in C/C++?

c program to find remainder without using modulus operator
alternative to modulo operator
fast modulo
c program to find modulus of two numbers
modulo using bitwise
modulo algorithm
modulus without division
how to implement modulo

I read somewhere once that the modulus operator is inefficient on small embedded devices like 8 bit micro-controllers that do not have integer division instruction. Perhaps someone can confirm this but I thought the difference is 5-10 time slower than with an integer division operation.

Is there another way to do this other than keeping a counter variable and manually overflowing to 0 at the mod point?

const int FIZZ = 6;
for(int x = 0; x < MAXCOUNT; x++)
    if(!(x % FIZZ)) print("Fizz\n"); // slow on some systems


The way I am currently doing it:

const int FIZZ = 6;
int fizzcount = 1;
for(int x = 1; x < MAXCOUNT; x++)
    if(fizzcount >= FIZZ) 
        fizzcount = 0;

Ah, the joys of bitwise arithmetic. A side effect of many division routines is the modulus - so in few cases should division actually be faster than modulus. I'm interested to see the source you got this information from. Processors with multipliers have interesting division routines using the multiplier, but you can get from division result to modulus with just another two steps (multiply and subtract) so it's still comparable. If the processor has a built in division routine you'll likely see it also provides the remainder.

Still, there is a small branch of number theory devoted to Modular Arithmetic which requires study if you really want to understand how to optimize a modulus operation. Modular arithmatic, for instance, is very handy for generating magic squares.

So, in that vein, here's a very low level look at the math of modulus for an example of x, which should show you how simple it can be compared to division:

Maybe a better way to think about the problem is in terms of number bases and modulo arithmetic. For example, your goal is to compute DOW mod 7 where DOW is the 16-bit representation of the day of the week. You can write this as:

 DOW = DOW_HI*256 + DOW_LO

 DOW%7 = (DOW_HI*256 + DOW_LO) % 7
       = ((DOW_HI*256)%7  + (DOW_LO % 7)) %7
       = ((DOW_HI%7 * 256%7)  + (DOW_LO%7)) %7
       = ((DOW_HI%7 * 4)  + (DOW_LO%7)) %7

Expressed in this manner, you can separately compute the modulo 7 result for the high and low bytes. Multiply the result for the high by 4 and add it to the low and then finally compute result modulo 7.

Computing the mod 7 result of an 8-bit number can be performed in a similar fashion. You can write an 8-bit number in octal like so:

  X = a*64 + b*8 + c

Where a, b, and c are 3-bit numbers.

  X%7 = ((a%7)*(64%7) + (b%7)*(8%7) + c%7) % 7
      = (a%7 + b%7 + c%7) % 7
      = (a + b + c) % 7

since 64%7 = 8%7 = 1

Of course, a, b, and c are

  c = X & 7
  b = (X>>3) & 7
  a = (X>>6) & 7  // (actually, a is only 2-bits).

The largest possible value for a+b+c is 7+7+3 = 17. So, you'll need one more octal step. The complete (untested) C version could be written like:

unsigned char Mod7Byte(unsigned char X)
    X = (X&7) + ((X>>3)&7) + (X>>6);
    X = (X&7) + (X>>3);

    return X==7 ? 0 : X;

I spent a few moments writing a PIC version. The actual implementation is slightly different than described above

       movwf        temp1        ;
       andlw        7        ;W=c
       movwf        temp2        ;temp2=c
       rlncf   temp1,F        ;
       swapf        temp1,W ;W= a*8+b
       andlw   0x1F
       addwf        temp2,W ;W= a*8+b+c
       movwf        temp2   ;temp2 is now a 6-bit number
       andlw   0x38    ;get the high 3 bits == a'
       xorwf        temp2,F ;temp2 now has the 3 low bits == b'
       rlncf   WREG,F  ;shift the high bits right 4
       swapf   WREG,F  ;
       addwf        temp2,W ;W = a' + b'

 ; at this point, W is between 0 and 10

       addlw        -7
       bc      Mod7Byte_L2
       addlw        7

Here's a liitle routine to test the algorithm

       clrf    x
       clrf    count

       movf        x,W
       RCALL   Mod7Byte
       cpfseq count
        bra    fail

       incf        count,W
       xorlw   7
        xorlw        7
       movwf   count

       incfsz        x,F
       bra        TestLoop

Finally, for the 16-bit result (which I have not tested), you could write:

uint16 Mod7Word(uint16 X)
 return Mod7Byte(Mod7Byte(X & 0xff) + Mod7Byte(X>>8)*4);


Efficient C Tip #13 – use the modulus (%) operator with caution , This is the thirteenth in a series of tips on writing efficient C for embedded systems. Thus if you are using the modulus operator on an ARM processor then it's needs to be done – and so I investigated some alternatives. On the other hand, integer modulo also exists as a CPU command. If the integer modulo operator maps to this command in optimized builds, you will not see any improvement by using the bit shift trick. The following code caclulates 7%4 by shifting far enough that only the 2 last bits are left (since 4=2^2). This means that we need to shift 30 bits:

If you are calculating a number mod some power of two, you can use the bit-wise and operator. Just subtract one from the second number. For example:

x % 8 == x & 7
x % 256 == x & 255

A few caveats:

  1. This only works if the second number is a power of two.
  2. It's only equivalent if the modulus is always positive. The C and C++ standards don't specify the sign of the modulus when the first number is negative (until C++11, which does guarantee it will be negative, which is what most compilers were already doing). A bit-wise and gets rid of the sign bit, so it will always be positive (i.e. it's a true modulus, not a remainder). It sounds like that's what you want anyway though.
  3. Your compiler probably already does this when it can, so in most cases it's not worth doing it manually.

How to find modulus without using modulus operator, Modulus Operator %. It is used to find remainder, check whether a number is even or odd etc Duration: 4:18 Posted: May 9, 2020 The C and C++ standards don't specify the sign of the modulus when the first number is negative (until C++11, which does guarantee it will be negative, which is what most compilers were already doing). A bit-wise and gets rid of the sign bit, so it will always be positive (i.e. it's a true modulus, not a remainder).

There is an overhead most of the time in using modulo that are not powers of 2. This is regardless of the processor as (AFAIK) even processors with modulus operators are a few cycles slower for divide as opposed to mask operations.

For most cases this is not an optimisation that is worth considering, and certainly not worth calculating your own shortcut operation (especially if it still involves divide or multiply).

However, one rule of thumb is to select array sizes etc. to be powers of 2.

so if calculating day of week, may as well use %7 regardless if setting up a circular buffer of around 100 entries... why not make it 128. You can then write % 128 and most (all) compilers will make this & 0x7F

Program to find remainder without using modulo or % operator , Following is the implementation of above idea. Thanks to eleventyone for suggesting this solution in a comment. C++; Java; Python; C#; PHP. C� There is still a place for the other style of header file. If a constant or data type is used throughout an application, they belong in a traditional header file. I have used this module style for a while now. However, using the C preprocessor to rename functions to force clients to import the interface definitions is a recent addition.

Unless you really need high performance on multiple embedded platforms, don't change how you code for performance reasons until you profile!

Code that's written awkwardly to optimize for performance is hard to debug and hard to maintain. Write a test case, and profile it on your target. Once you know the actual cost of modulus, then decide if the alternate solution is worth coding.

Bitwise Alternatives to Multiply, Divide, and Modulus: Faster , Bitwise Alternatives to Multiply, Divide, and Modulus: Faster? Many programmers are aware of a special case where you can use a bitwise shift for too much to have any meaning. for example in� The answer is easy to compute: divide 11 by 3 and take the remainder: 2. But how would you compute this in a programming language like C or C++? It's not hard to come up with a formula, but the language provides a built-in mechanism, the modulus operator ('%'), that computes the remainder that results from performing integer division.

@Matthew is right. Try this:

int main() {
  int i;
  for(i = 0; i<=1024; i++) {
    if (!(i & 0xFF)) printf("& i = %d\n", i);
    if (!(i % 0x100)) printf("mod i = %d\n", i);

A fast alternative to the modulo reduction – Daniel Lemire's blog, Useful code: I published a C/C++ header on GitHub that you can use in your projects. Further reading: Daniel Lemire, Fast Random Integer� There does not seem to be a standard notation for this operation, so let us tentatively use a mod d n. We thus have the following definition: x = a mod d n just in case d ≤ x ≤ d+n−1 and x mod n = a mod n. Clearly, the usual modulo operation corresponds to zero offset: a mod n = a mod 0 n.

Compute modulus division without division and modulo operator , In this quick article, we will see how to compute modulus division of a positive number n by another positive number d which is a power of 2 without using division or modulo operator. post code in comments using C, C++, Java, Python, JavaScript, C#, PHP and many more For the last solution, isn't it a better alternative ? You can find modulus operator in almost all programming language. It makes to make logic easier for a programmer. We tried to explain the thing in easy manner to you. Hope you will get it. Thanks.

lemire/fastrange: A fast alternative to the modulo reduction, reduction. Contribute to lemire/fastrange development by creating an account on GitHub. The C rand function does not meet this requirement. If you must� The standard library provides a specialization of std::modulus when T is not specified, which leaves the parameter types and return type to be deduced. modulus <void> function object implementing x % y deducing argument and return types

Modulo operation, In computing, the modulo operation finds the remainder or signed remainder after a division of (Doing the division with a calculator will not show the result referred to here One correct alternative is to test that the remainder is not 0 ( because the result of the modulo operation has the sign of the dividend ( including C),� The modulus operator (%) has a stricter requirement in that its operands must be of integral type. (To get the remainder of a floating-point division, use the run-time function, fmod .) The conversions covered in Standard Conversions are applied to the operands, and the result is of the converted type.