Safety for checking MOD for negative values


/ Published in: Java
Save to your folder(s)

-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.


Copy this code and paste it in your HTML
  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


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.