中国剩余定理(Chinese Remainder Theorem-CRT):又称孙子定理,是数论中的一个定理。即如果一个人知道了一个数n被多个整数相除得到的余数,当这些除数两两互质的情况下,这个人就可以唯一的确定被这些个整数乘积除n所得的余数。
维基百科上wiki:The Chinese remainder theorem is a theorem of number theory, which states that, if one knows the remainders of the division of an integer n by several integers, then one can determine uniquely the remainder of the division of n by the product of these integers, under the condition that the divisors are pairwise coprime.
- 有一数n,被2除余1,被3除余2,被5除余4,被6除余5,正好被7整除,求该数n.
分析:n被2除余1,说明概述最小为1,之后该条件一直满足,所以需要加上的数一定是2的倍数。被3除余2,即(1+2*i)%3=2,其中i为正整数。之后该条件一直满足,所以需要加上的数一定是3的倍数,又因为前一个条件的限制,所以是2和3的最小公倍数的整数倍。一次类推,知道找到被7整除的数。
n=1
while(n%3 != 2):
n += 2
while(n%5 != 4):
n += 6
while(n%6 != 5):
n += 30
while(n%7 != 0):
n += 30
最终结果为119。