找到hcf和lcm

时间:2015-11-05 13:20:04

标签: python python-2.7 lcm

我在python中写了下面的progran来找出两个数字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中完美运行,所以我不觉得算法应该有问题。它可能是一些语法问题。

4 个答案:

答案 0 :(得分:0)

你几乎把它弄错了,但是你需要处理许多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进行测试

答案 1 :(得分:0)

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))

答案 2 :(得分:0)

a, b =input("enter two numbers (with space in between: ").split()#converted the previous answer into python because it still had runtime errors

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: ", i)

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: ", j)

答案 3 :(得分:-1)

找到LCM和HCF的程序

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));