求两个数的 lcm [英] To find the lcm of two numbers

查看:69
本文介绍了求两个数的 lcm的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的任务是计算任意两个数字的 lcm.我用 python 编码.问题是当我在 python2.7 下编译它时,我得到的结果与在 python3 下编译时不同.

导入系统def gcd(a,b):如果 b == 0:返回一个余数 = a % b返回 gcd(b,remainder)def lcm(a, b):返回 int( (a*b)/gcd(a,b))如果 __name__ == '__main__':输入 = sys.stdin.read()a, b = map(int, input.split())打印(int(lcm(a,b)))

输入

<块引用>

226553150 1023473145

输出

<块引用>

46374212988031352(python3.5下)

46374212988031350(python2.7下)

有人可以帮我吗?

解决方案

在 Python 2 中,除法运算符 / 在处理两个整数时将执行整数除法,而不是浮点除法.您可以通过从 __future__

导入除法来强制 Python 2 中的 Python 3 行为<预><代码>>>>来自 __future__ 进口部门>>>2/31.5

I was given the task to compute lcm of any two numbers.I have coded in python.The problem is when i compiled it under python2.7, i got a result which is different from , when i compiled under python3.

import sys

def gcd(a,b):     
   if b == 0:
     return a
   remainder = a % b
   return gcd(b,remainder)

def lcm(a, b):
  return int( (a*b) / gcd(a,b))

if __name__ == '__main__':
   input = sys.stdin.read()
   a, b = map(int, input.split())
   print(int(lcm(a, b)))

Input

226553150 1023473145

Output

46374212988031352 (under python3.5)

46374212988031350 (under python2.7)

Can someone help me ?

解决方案

In Python 2 the division operator / will perform integer division, and not float division, when dealing with two integers. You can force the Python 3 behavior in Python 2 by importing division from __future__

>>> from __future__ import division
>>> 2/3
1.5

这篇关于求两个数的 lcm的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆