è² æ°ãå«ã¾ããå°ä½ãè¨ç®ããå ´åãè¨èªã«è·¨ãã£ã¦ä¸æãªçµæãå¾ãããªãã
-5 % 3 | 5 % -3 | |
C | -2 | 2 |
C++ | -2 | 2 |
Java | -2 | 2 |
Ruby | 1 | -1 |
Python | 1 | -1 |
Common Lisp | 1 | -1 |
ãã¦ããªããããªãã¨ãèµ·ããã®ãã¨ããã¨ãå°ä½ã«ã¯è¤æ°ã®å®ç¾©ãåå¨ããããã§ããã
m ÷ n = q ⦠r
ãã® r ãå°ä½ã¨è¨ããã r ã®ç¯å²ã
- 0 ≤ r < n
- æå°éè² å°ä½
- -n/2 ≤ r < n/2
- 絶対å¤æå°å°ä½
ã®äºã¤ã®å®ç¾©ããããä¸è¬çã«ã¯åè ã®ãæå°éè² å°ä½ããç¨ããããã§ããã
m ãè² æ°ã n ãæ£æ°ã®å ´åã¯ãå ç¨ã®è¡¨ã«ããããã°ã©ãã³ã°è¨èªã¯ä»¥ä¸ã®ããã«åé¡ãããã
- 絶対å¤æå°å°ä½
- æå°éè² å°ä½
ããããæå°éè² å°ä½ã§ã¯ r ãæ£æ°ã«ãªãå¿
è¦ããããå°ä½ã®çµæã -1 ã«ãªãã®ã¯æå°éè² å°ä½ã®å®ç¾©ããå¤ãã¦ããã
ããã¯ãé¤æ° n ãè² æ°ã«ãªãå ´åãããã°ã©ãã³ã°è¨èªã§ã¯ä»¥ä¸ã®å®ç¾©ã«ãªãçç±ã«ãããã®ã§ããã
m % -n == -(m % n)
ãã ããæ°å¦çã«æå°éè² å°ä½ã¯ä»¥ä¸ãçã«ãªãããã 0 ≤ r < n ã常ã«æãç«ã¤ã
m % (-n) = m % n
ã¾ã¨ã
é¤æ°ã被é¤æ°ã«è² æ°ãå ¥ãå°ä½æ¼ç®ã¯ããã°ã©ãã³ã°è¨èªã«ããçµæãå¤ããã®ã§ä½¿ãã®ãè¾ãã¾ãããã
/* è² æ°ã¯æ±ããªãããã«ãã */ int mod(int m, int n) { if (m < 0 || n < 0) { return ERROR_NEGATIVE_MOD; } return (m % n); }
è² æ°ã®å°ä½ã«ã¤ãã¦ãæ確ã«éããåãã£ã¦ããã°ä½¿ãåã«ã¯èªå·±è²¬ä»»ã ã¨æãã¾ãããä»äººãç解ã§ããªã (äºæ³ããåä½ã«ãªããªã) å¯è½æ§ãé«ãã®ã§ãã¼ã éçºã§ã¯å©ç¨ããã¹ãã§ã¯ãªãã§ãããã