-2

我在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 中完美运行,所以我不觉得算法应该有问题。这可能是一些语法问题。

4

4 回答 4

0
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 + 1):
    if a % i == 0 and b % i == 0:
        hcf = i

print "hcf of both is:", hcf

for j in range(x, a * b + 1):
    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
于 2018-06-04T14:01:45.753 回答
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 测试

于 2015-11-05T14:22:05.353 回答
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))
于 2015-11-05T16:14:14.687 回答
-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));
于 2020-06-02T13:28:19.270 回答