Posted By

ankurtrapasiya on 06/13/13


Tagged

Value mod mathematics negative


Versions (?)

Safety for checking MOD for negative values


 / Published in: Java
 

-13%2 = -1 so this might cause problem in your program sometime. So always write your code in such a way that it never cause any problem in sleep also.. :) Use anyone of the following code snippet.

  1. int mod(int x, int m) {
  2. return (x%m + m)%m;
  3. }
  4.  
  5. int mod(int x, int m) {
  6. int r = x%m;
  7. return r<0 ? r+m : r;
  8. }

Report this snippet  

You need to login to post a comment.