菜鸟教程 -- 学的不仅是技术,更是梦想!

Python 3 教程
Python3 教程 Python3 简介 Python3 环境搭建 Python3 VScode Python3 基础语法 Python3 基本数据类型 Python3 数据类型转换 Python3 解释器 Python3 注释 Python3 运算符 Python3 数字(Number) Python3 字符串 Python3 列表 Python3 元组 Python3 字典 Python3 集合 Python3 条件控制 Python3 循环语句 Python3 编程第一步 Python3 推导式 Python3 迭代器与生成器 Python3 with Python3 函数 Python3 lambda Python3 装饰器 Python3 数据结构 Python3 模块 Python __name__ Python3 输入和输出 Python3 File Python3 OS Python3 错误和异常 Python3 面向对象 Python3 命名空间/作用域 Python 虚拟环境的创建 Python 类型注解 Python3 标准库概览 Python3 实例 Python 测验

Python3 高级教程

Python3 正则表达式 Python3 CGI编程 Python3 MySQL(mysql-connector) Python3 MySQL(PyMySQL) Python3 网络编程 Python3 SMTP发送邮件 Python3 多线程 Python3 XML 解析 Python3 JSON Python3 日期和时间 Python3 内置函数 Python3 MongoDB Python3 urllib Python uWSGI 安装配置 Python3 pip Python3 operator Python math Python requests Python random Python OpenAI Python 有用的资源 Python AI 绘画 Python statistics Python hashlib Python 量化 Python pyecharts Python selenium 库 Python 爬虫 Python Scrapy 库 Python Markdown Python sys 模块 Python Pickle 模块 Python subprocess 模块 Python queue 模块 Python StringIO 模块 Python logging 模块 Python datetime 模块 Python re 模块 Python csv 模块 Python threading 模块 Python asyncio 模块 Python PyQt Python for 循环 Python while 循环
(追記) (追記ここまで)

Python 最大公约数算法

Document 对象参考手册 Python3 实例

以下代码用于实现最大公约数算法:

实例(Python 3.0+)

# Filename : test.py# author by : www.runoob.com# 定义一个函数defhcf(x, y): """该函数返回两个数的最大公约数"""# 获取最小值ifx > y: smaller = yelse: smaller = xforiinrange(1,smaller + 1): if((x % i == 0)and(y % i == 0)): hcf = ireturnhcf# 用户输入两个数字num1 = int(input("输入第一个数字: "))num2 = int(input("输入第二个数字: "))print(num1,"", num2,"的最大公约数为", hcf(num1, num2))

执行以上代码输出结果为:

输入第一个数字: 54
输入第二个数字: 24
54 和 24 的最大公约数为 6

Document 对象参考手册 Python3 实例

AI 思考中...

14 篇笔记 写笔记

  1. #0

    HaydnLiao

    Hay***[email protected]

    82

    可按以下思路减少循环次数:

    1. 当最小值为最大公约数时,直接返回;

    2. 当最小值不为最大公约数时,最大公约数不会大于最小值的1/2;

    3. 求最大公约数理应从大到小循环递减求最大。

    实例:

    def gcd(a, b):
     if b > a:
     a, b = b, a # b为最小值
     if a % b == 0:
     return b # 判断b是否为最大公约数
     for i in range(b//2+1, 1, -1): # 倒序求最大公约数更合理
     if b % i == 0 and a % i == 0:
     return i
     return 0
    while(True):
     a = int(input("Input 'a':"))
     b = int(input("Input 'b':"))
     print(gcd(a, b))

    HaydnLiao

    Hay***[email protected]

    9年前 (2017年07月02日)
  2. #0

    Joshua

    cos***[email protected]

    65

    参考方法:

    def gcd(x, y): # very fast
     return x if y == 0 else gcd(y, x%y)
    print(gcd(378, 5940)) # result: 54

    Joshua

    cos***[email protected]

    9年前 (2017年07月19日)
  3. #0

    thinrock

    thi***[email protected]

    17

    参考方法:

    x = int(input('请输入第一个数:'))
    y = int(input('请输入第二个数:'))
    for i in range(1,min(x,y) + 1):
     if (y % i == 0) & (x % i == 0):
     divisor = i
    print(divisor)

    thinrock

    thi***[email protected]

    9年前 (2017年08月17日)
  4. #0

    Santana

    378***[email protected]

    4

    从大到小一个一个计算:

    n1=int(input("input a number: "))
    n2=int(input("input another number: "))
    if n1<n2:
     smaller=n1
    else:
     smaller=n2
    while True:
     if (n1%smaller==0) and (n2%smaller==0):
     print(smaller)
     break
     smaller-=1

    Santana

    378***[email protected]

    9年前 (2017年09月09日)
  5. #0

    susion

    245***[email protected]

    14

    两个数的最大公约数可以使用 欧几里得算法实现。即两个数的最大公约数等于其中较小的那个数和两数相除余数的最大公约数。

    def gcd(a, b):
     if a == 0:
     a, b = b, a
     while b != 0:
     a, b = b, a % b
     return a
    print(gcd(54, 24))

    susion

    245***[email protected]

    9年前 (2017年10月15日)
  6. #0

    黄桃果捞

    zhe***[email protected]

    6

    可以利用辗转相除的方法实现求两个正数的最大公约数,代码如下:

    #!/usr/bin/python3
    # -*- coding: UTF-8 -*-
    # find the greatest common divisor of two integer
    def find_GCD(x, y):
     find_GCD = y
     while (x % y) != 0:
     find_GCD = x % y
     x, y = y, find_GCD
     return find_GCD
    int1 = int(input('Input 1st integer: '))
    int2 = int(input('Input 2nd integer: '))
    print('The greatest common divisor of {} and {} is {}'.format(int1, int2, find_GCD(int1, int2)))

    代码运行结果如下:

    Input 1st integer: 54
    Input 2nd integer: 24
    The greatest common divisor of 54 and 24 is 6

    黄桃果捞

    zhe***[email protected]

    8年前 (2018年03月20日)
  7. #0

    桃之夭夭

    956***[email protected]

    5

    欧几得里算法的完善版,输入任意两个整数,求最大公约数。

    def gcd(a,b):
     if a == 0:
     a,b = b,a
     while b != 0:
     a,b = b,a%b
     return a
    c = int(input('请输入第一个正整数: '))
    d = int(input('请输入第二个正整数: '))
    if c>d:
     b = d
    else:
     b = c
    print('{}和{}的最大公约数为: {}'.format(c,d,gcd(c,d)))

    桃之夭夭

    956***[email protected]

    8年前 (2018年06月28日)
  8. #0

    Egg_Hu

    799***[email protected]

    18

    不能再精简了吧

    # 辗转相除法(不用判断大小)
    def f1(a,b):
     while b!=0:
     a,b=b,a%b
     print(a)
    f1(27,6)
    # 相减法
    def f2(a,b):
     while a!=b:
     a,b=min(a,b),abs(a-b)
     print(a)
    f2(27,6)

    Egg_Hu

    799***[email protected]

    8年前 (2018年07月24日)
  9. #0

    The_Matrix

    995***[email protected]

    10

    求多个数的最大公约数

    num = str(input('输入要检测的数字(如:5,25,75):')).split(',')
    ss,kk,ee= [],[],[]
    for i in num:
     ss.append(int(i)) #将输入的数字存入列表
    for j in ss:
     for m in range(1,1+max(ss)):
     if(j % m ==0):
     kk.append(m) #求出输入的每一个数字的约数,并将其存入列表
    for q in kk:
     if(kk.count(q)==len(ss)):
     ee.append(q) #将所有的公约数存入列表
    print(ee)
    print('{}的最大公约数为:{}'.format(ss,max(ee))) #输出最大公约数

    测试结果:

    输入要检测的数字:5,25,75
    [1, 5, 1, 5, 1, 5]
    [5, 25, 75]的最大公约数为:5

    The_Matrix

    995***[email protected]

    8年前 (2018年08月01日)
  10. #0

    Alex

    934***[email protected]

    25

    使用 math 模块的 gcd()。

    import math
    a = 54
    b = 24
    print(math.gcd(a, b))

    输出结果为:

    6

    Alex

    934***[email protected]

    8年前 (2018年11月12日)
  11. #0

    慕容君少

    shu***[email protected]

    9

    参考方法:

    # 没办法,就喜欢用 filter,能用 filter 解决的,坚决不用循环,哇哈哈哈
    while True:
     try:
     n1=int(input('请输入第 1 个数字:'))
     n2=int(input('请输入第 2 个数字:'))
     L1=list(filter(lambda x:n1%x==0,range(1,n1)))
     L2=list(filter(lambda x:n2%x==0,range(1,n2)))
     L=list(filter(lambda x:x in L2,L1))
     print('{0}共有{1}个公约数,分别为{2},最大公约数为{3}'.format((n1,n2),len(L),L,max(L)))
     break
     except ValueError:
     print('输入正整数')

    慕容君少

    shu***[email protected]

    8年前 (2018年11月22日)
  12. #0

    favourite45

    jas***[email protected]

    5

    用空列表方式实现最大公约数:

    '''最大公约数'''
    def hcf(x,y):
     list = [] #初始化一个空列表
     for i in range(1,min(x,y)+1):
     if (x % i == 0) & (y % i == 0):
     list.append(i) #将符合的值加到列表中
     print(max(list)) #求列表中最大值,有内置函数
    hcf(18,12)

    favourite45

    jas***[email protected]

    7年前 (2019年07月14日)
  13. #0

    白云黑土

    mr.***[email protected]

    5

    求两个数的所有公约数:

    list = []
    def hec(x, y):
     value = max(x, y)
     for i in range(1, value+1):
     if((x % i == 0) and (y % i == 0)):
     list.append(i)
    num1 = int(input("Please input the first number:"))
    num2 = int(input("Please input the secend number:"))
    hec(num1, num2)
    print(num1, "and", num2, "of Maximum common divisor is:",list)

    白云黑土

    mr.***[email protected]

    7年前 (2019年10月26日)
  14. #0

    残存的影子

    176***[email protected]

    2

    这个时间复杂度太高了吧,好像有一个叫辗转相除法的,效率很高:

    def func2():
     num1 = int(input("请输入第一个数字:"))
     num2 = int(input("请输入第一个数字:"))
     m = max(num1, num2)
     n = min(num1, num2)
     r = m % n
     while r != 0:
     m = n
     n = r
     r = m % n
     print(num1, "和", num2, "的最大公约数为", n)
     
    if __name__ == '__main__':
     func2()

    残存的影子

    176***[email protected]

    3年前 (2023年02月25日)

点我分享笔记

  • 昵称 (必填)
  • 邮箱 (必填)
  • 引用地址

AltStyle によって変換されたページ (->オリジナル) /