查找hcf和lcm的python程序

查找hcf和lcm的python程序,python,python-2.7,lcm,Python,Python 2.7,Lcm,我用python编写了以下程序,以找出两个数字a和b的hcf和lcm。x是两个数字中较大的一个,y是较小的,我打算在程序的上半部分找到这两个数字。它们将在以后用于查找hcf和lcm。但当我运行它时,它会将x变成红色。我不明白原因 a,b=raw_input("enter two numbers (with space in between: ").split() if (a>b): int x==a else: int x==b for i in range (1,x):

我用python编写了以下程序,以找出两个数字a和b的hcf和lcm。x是两个数字中较大的一个,y是较小的,我打算在程序的上半部分找到这两个数字。它们将在以后用于查找hcf和lcm。但当我运行它时,它会将x变成红色。我不明白原因

a,b=raw_input("enter two numbers (with space in between: ").split()
if (a>b):
    int x==a
else:
    int x==b
for i in range (1,x):
    if (a%i==0 & b%i==0):
        int hcf=i
print ("hcf of both is: ", hcf)
for j in range (x,a*b):
    if (j%a==0 & j%b==0):
        int lcm=j
print ("lcm of both is: ", lcm)        

这个查找lcm,hcf的算法在c语言中非常有效,所以我觉得这个算法不应该有问题。这可能是一些语法问题

您几乎完全正确,但有许多Python语法问题需要解决:

a, b = raw_input("enter two numbers (with space in between: ").split()

a = int(a)  # Convert from strings to integers
b = int(b)

if a > b:
    x = a
else:
    x = b

for i in range(1, x):
    if a % i == 0 and b % i==0:
        hcf = i

print "hcf of both is: ", hcf

for j in range(x, a * b):
    if j % a == 0 and j % b == 0:
        lcm = j
        break       # stop as soon as a match is found

print "lcm of both is: ", lcm

使用Python 2.7.6

程序进行测试,以查找LCM和HCF

import sys
a = int(sys.argv[1])
b = int(sys.argv[2])
sa = a
sb = b
r = a % b
while r != 0:
    a, b = b, r
    r = a % b
h = b
l = (sa * sb) / h
print('a={},b={},hcf={},lcm={}\n'.format(sa,sb,h,l))
a=int(input("Enter the value of a:"))
b=int(input("Enter the value of b:"))
if(a>b):
    x=a
else:
    x=b
for i in range(1,x+1):
    if(a%i==0)and(b%i==0):
        hcf=i
print("The HCF of {0} and {1} is={2}".format(a,b,hcf));
for j in range(x,a*b):
    if(j%a==0)and(j%b==0):
        lcm=j
        break
print("The LCM of {0} and {1} is={2}".format(a,b,lcm));

你的代码有很多语法错误。请按照初学者教程进行操作。这是根据条件a>b将a的值赋值给x。int x==a这不是赋值的工作方式。即使在C语言中也不行。在将a和b作为数字进行比较之前,您必须先将它们转换为数字。虽然这可能为问题提供了答案,但提供一些注释有助于其他人了解此代码为什么会这样做。请参阅,了解如何为答案添加更多细节/上下文。请格式化您的代码-类似缩进的格式是Python程序的一部分。OP询问的是代码中错误的原因,而不是整个代码本身。
a=int(input("Enter the value of a:"))
b=int(input("Enter the value of b:"))
if(a>b):
    x=a
else:
    x=b
for i in range(1,x+1):
    if(a%i==0)and(b%i==0):
        hcf=i
print("The HCF of {0} and {1} is={2}".format(a,b,hcf));
for j in range(x,a*b):
    if(j%a==0)and(j%b==0):
        lcm=j
        break
print("The LCM of {0} and {1} is={2}".format(a,b,lcm));