• 技术文章 >常见问题 >Python常见问题

    python中最小公倍数怎么求

    宋雪维宋雪维2021-03-25 14:09:19原创13049

    在化学式中无机物里,一般的情况下都表示的是各种元素的原子个数比,而知道化合价后,根据化合物中元素化合价的正负代数和为零,所以需要求出最小公倍数从而确定原子个数比的。最小公倍数可用于解决一些问题,因此要关注最小公倍数。在python中怎么求去最小公倍数呢?下面,小编来教教你吧。

    代码:

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    <p style="line-height: normal;"># 最小公倍数

     

    def lcm(a, b, c=1):

     

            if a * c % b != 0:

     

                    return lcm(a, b, c+1)

     

            else:

     

                    return a*c

     

      

     

    test_cases = [(4, 8), (35, 42), (5, 7), (20, 10)]

     

    for case in test_cases:

     

        print('lcm of {} & {} is {}'.format(*case, lcm(*case))) <br></p>

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    <p style="line-height: normal;">def lcm(a, b):

     

        for i in range(2, min(a,b)+1):

     

            if a % i == 0 and b % i == 0:

     

                return i * lcm(a//i, b//i)

     

        else:

     

            return a*b

     

      

    test_cases = [(4, 8), (5, 7), (24, 16), (35, 42)]

     

    for case in test_cases:

     

        print('lcm of {} & {} is {}'.format(*case, lcm(*case)))<br></p>


    以上就是python中求取最小公倍数的方法,最小公倍数虽然在平时我们感到不到它的存在,但是他的作用很大,它为什么计算提供了基础,快套下上串代码求最小公倍数试试看吧~

    (推荐操作系统:windows7系统、Python 3.9.1,DELL G3电脑。)



    专题推荐:python 最小公倍数
    上一篇:python entry怎么用? 下一篇:python如何质数求和?

    相关文章推荐

    • demo:飞机大战游戏 python小项目• python编程实战:海伦公式求取三角形的面积

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网