本文實(shí)例講述了Python實(shí)現(xiàn)的中國(guó)剩余定理算法。分享給大家供大家參考,具體如下:
中國(guó)剩余定理(Chinese Remainder Theorem-CRT):又稱孫子定理,是數(shù)論中的一個(gè)定理。即如果一個(gè)人知道了一個(gè)數(shù)n被多個(gè)整數(shù)相除得到的余數(shù),當(dāng)這些除數(shù)兩兩互質(zhì)的情況下,這個(gè)人就可以唯一的確定被這些個(gè)整數(shù)乘積除n所得的余數(shù)。
維基百科上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.
有一數(shù)n,被2除余1,被3除余2,被5除余4,被6除余5,正好被7整除,求該數(shù)n.
分析:n被2除余1,說明概述最小為1,之后該條件一直滿足,所以需要加上的數(shù)一定是2的倍數(shù)。被3除余2,即(1+2*i)%3=2,其中i為正整數(shù)。之后該條件一直滿足,所以需要加上的數(shù)一定是3的倍數(shù),又因?yàn)榍耙粋€(gè)條件的限制,所以是2和3的最小公倍數(shù)的整數(shù)倍。一次類推,知道找到被7整除的數(shù)。
n=1while(n%3 != 2): n += 2while(n%5 != 4): n += 6while(n%6 != 5): n += 30while(n%7 != 0): n += 30
最終結(jié)果為119。
希望本文所述對(duì)大家Python程序設(shè)計(jì)有所幫助。
新聞熱點(diǎn)
疑難解答
圖片精選