python 最大公約數


求解兩個整數(不能是負數)的最大公約數(要求兩數不能同時為0)

當兩數都是0時,最大公約數為0

方式一:窮舉法
 1 def GCU(m, n):
 2     if not m:
 3         return n
 4     elif not n:
 5         return m
 6     elif m is n:
 7         return m
 8 
 9     if m > n:
10         gcd = n
11     else:
12         gcd = m
13 
14     while m%gcd or n%gcd:
15         gcd -= 1
16 
17     return gcd
View Code

方式二:相減法

 1 def GCU(m, n):
 2     if not m:
 3         return n
 4     elif not n:
 5         return m
 6     elif m is n:
 7         return m
 8 
 9     while m!=n:
10         if m>n:
11             m -= n
12         else:
13             n -= m
14 
15     return m
View Code

方式三:歐幾里德輾轉相除法

 1 def GCU(m, n):
 2     if not m:
 3         return n
 4     elif not n:
 5         return m
 6     elif m is n:
 7         return m
 8 
 9     while m%n:
10         m, n = n, m%n
11 
12     return n
View Code

方式四:歐幾里德輾轉相除法 遞歸實現

 1 def GCU(m,n):
 2     if not n:
 3         return m
 4     else:
 5         return GCU(n, m%n)
 6 
 7 if __name__ == '__main__':
 8     a = int(input('Please input the first integers : '))
 9     b = int(input('Please input the second integers : '))
10     result = GCU(a, b)
11     print('GCU = ', result)
View Code

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM