http://www.sw.it.aoyama.ac.jp/2013/Math1/lecture11.html
© 2006-13 Martin J. Dürst 青山学院大学
(modular arithmetic)
a ≡(mod n) b ⇔ a - b = qn ⇔ a = q1n + r ∧ b = q2n + r ∧ 0 ≦ r < n
%
(C, Ruby and many other programming
languages)、mod (Mathematics)remainder for negative operands | |||||||
---|---|---|---|---|---|---|---|
operands | always non-negative | same sign as divisor | same sign as dividend | ||||
a | n | q | r | q | r | q | r |
11 | 7 | 1 | 4 | 1 | 4 | 1 | 4 |
-11 | 7 | -2 | 3 | -2 | 3 | 1 | -4 |
11 | -7 | -1 | 4 | -2 | -3 | -1 | 4 |
-11 | -7 | 2 | 3 | 1 | -4 | -1 | -4 |
Programming languages,... | Pascal, this lecture | Ruby, Python, MS Excel | C (ISO 1999), Java, JavaScript, Perl, PHP |
See English Wikipedia article on Modulo Operation
Output some data items, three items on a line.
A simple way:
int items = 0; for (i=0; i<length; i++) { /* print out */ items++; if (items==3) { printf("\n"); items = 0; } }
Using the modulo operation:
for (i=0; i<length; i++) { /* print out */ if (i%3 == 2) printf("\n"); }
Reason: a ≡(mod n) a mod n, and so on
Example: 216 mod 29 = ?
216 = 25 · 25 · 25 · 2
216 = 25 · 25 · 25 · 2 = 32 · 32 · 32 · 2 ≡(mod 29) 3 · 3 · 3 · 2 = 54 ≡(mod 29) 25
有理数などの割算: a/b = c ⇔a b-1 = c; b b-1 = 1 (逆数、inverse)
モジュラ逆数 (modular multiplicative inverse): bb-1 ≡ 1
n | b | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
---|---|---|---|---|---|---|---|---|---|
2 | - | 1 | |||||||
3 | - | 1 | 2 | ||||||
4 | - | 1 | - | 3 | |||||
5 | - | 1 | 3 | 2 | 4 | ||||
6 | - | 1 | - | - | - | 5 | |||
7 | - | 1 | 4 | 5 | 2 | 3 | 6 | ||
8 | - | 1 | - | 3 | - | 5 | - | 7 |
n と b がお互いに素 (coprime、最大公約数が 1) の場合のみ定義
計算には色々方法が存在
a/b (mod n) は a b-1 (mod n) として定義
具体例: 3/4 (mod 7) = 3 · 4-1 (mod 7) = 3 · 2 (mod 7) = 6
(確認: 6 · 4 (mod 7) = 24 (mod 7) = 3)
数字和 (digit sum): それぞれのけたの数字の合計
数字根 (digit root): 数字和を一桁になるまでに繰り返す
十進法での応用例: 1839275 の数字和は 1+8+3+9+2+7+5 = 35; 35 の数字和は 3+5 = 8; 1839275 の数字根は 8
十六進法の例: A8FB の数字和は A+8+F+B (10+8+15+11) = (44) 2C; 2C の数字和は 2+C (2+12) = (14) E; A3FB の数字根は E
(casting out nines)