欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python基于遞歸和非遞歸算法求兩個數(shù)最大公約數(shù)、最小公倍數(shù)示例

 更新時間:2018年05月21日 11:23:25   作者:Together_CZ  
這篇文章主要介紹了Python基于遞歸和非遞歸算法求兩個數(shù)最大公約數(shù)、最小公倍數(shù),涉及Python遞歸算法、流程循環(huán)控制進行數(shù)值運算相關操作技巧,需要的朋友可以參考下

本文實例講述了Python基于遞歸和非遞歸算法求兩個數(shù)最大公約數(shù)、最小公倍數(shù)。分享給大家供大家參考,具體如下:

最大公約數(shù)和最小公倍數(shù)的概念大家都很熟悉了,在這里就不多說了,今天這個是因為做題的時候遇到了所以就寫下來作為記錄,也希望幫到別人,下面是代碼:

#!/usr/bin/env python
#coding:utf-8
from fractions import gcd
#非遞歸實現(xiàn)
def gcd_test_one(a, b):
  if a!=0 and b!=0:
    if a>b:
      a, b=b, a
    if b%a==0:
      return a
    gcd_list=[]
    for i in range(1,a):
      if b%i==0 and a%i==0:
        gcd_list.append(i)
    return max(gcd_list)
  else:
    print 'Number is wrong!!!'
#遞歸實現(xiàn)
def gcd_test_two(a, b):
  if a>b:
    a, b=b, a
  if b%a==0:
    return a
  else:
    return gcd_test_two(a,b%a)
#python自帶的gcd
def gcd_test_three(a, b):
  return gcd(a,b)
if __name__ == '__main__':
  print gcd_test_one(12,24)
  print gcd_test_one(12,8)
  print gcd_test_one(6,24)
  print gcd_test_one(0,24)
  print '----------------------------------------------------------------------------'
  print gcd_test_two(12,24)
  print gcd_test_two(12,8)
  print gcd_test_two(6,32)
  print '----------------------------------------------------------------------------'
  print gcd_test_three(12,24)
  print gcd_test_three(12,8)

結果如下:

12
4
6
Number is wrong!!!
None
----------------------------------------------------------------------------
12
4
2
----------------------------------------------------------------------------
12
4

PS:這里再為大家推薦一款本站相關在線工具供大家參考:

在線最小公倍數(shù)/最大公約數(shù)計算工具:
http://tools.jb51.net/jisuanqi/gbs_gys_calc

更多關于Python相關內(nèi)容感興趣的讀者可查看本站專題:《Python數(shù)學運算技巧總結》、《Python數(shù)據(jù)結構與算法教程》、《Python函數(shù)使用技巧總結》、《Python字符串操作技巧匯總》、《Python入門與進階經(jīng)典教程》及《Python文件與目錄操作技巧匯總

希望本文所述對大家Python程序設計有所幫助。

相關文章

最新評論