本文實例講述了Python實現的中國剩余定理算法。分享給大家供大家參考,具體如下:
中國剩余定理(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=1while(n%3 != 2): n += 2while(n%5 != 4): n += 6while(n%6 != 5): n += 30while(n%7 != 0): n += 30
最終結果為119。
更多關于Python相關內容感興趣的讀者可查看本站專題:《Python數據結構與算法教程》、《Python函數使用技巧總結》、《Python字符串操作技巧匯總》及《Python入門與進階經典教程》
希望本文所述對大家Python程序設計有所幫助。
新聞熱點
疑難解答