-2

i wrote the following progran in python to find out hcf and lcm of two numbers a and b. x is the greater of the two numbers and y is smaller, both of which i intend to find in upper part of program. they will be used later for finding hcf and lcm.but when i run it, it shades x in red. i cant understand the reason.

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)        

this algo of finding lcm, hcf works perfectly in c, so i dont feel there should be problem with algo. it might be some syntax problem.

Tarun Khare
  • 1,447
  • 6
  • 25
  • 43

4 Answers4

1
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))
balabhi
  • 641
  • 5
  • 5
  • 3
    While this may provide an answer to the question, it helps to provide some commentary so others can learn "why" this code does what it does. Please see [How to answer](http://stackoverflow.com/help/how-to-answer) for ways to add more detail/context to an answer. – Glen Selle Nov 05 '15 at 17:46
1
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
Davis Herring
  • 36,443
  • 4
  • 48
  • 76
0

You almost had it correct, but there were a number of Python syntax issue you need need to work on:

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

Tested using Python 2.7.6

Martin Evans
  • 45,791
  • 17
  • 81
  • 97
-1

Program to find the LCM and 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));