I have been trying to get more into programming, so I've been trying to make a simple program that takes two numbers as input, and computes the lowest common multiple. I did this in Python because I don't know how to take input in Java. What happens now is the program just hangs after I input my numbers, and nothing happens. Any pointers here would be greatly appreciated. Thank you.
#LCM Calculator
#Author: Ethan Houston
#Language: Python
#Date: 2013-12-27
#Function: Program takes 2 numbers as input, and finds the lowest number
# that goes into each of them
def lcmCalculator(one, two):
""" takes two numbers as input, computes a number that evenly
divides both numbers """
counter = 2 #this is the number that the program tried to divide each number by.
#it increases by 1 if it doesn't divide evenly with both numbers.
while True:
if one % counter == 0 and two % counter == 0:
print counter
break
else:
counter += 1
print "\nThis program takes two numbers and computes the LCM of them...\n"
first_number = input("Enter your first number: ")
second_number = input("Enter your second number: ")
print lcmCalculator(first_number, second_number)
Your logic is a bit off. This line:
needs to be rewritten like this:
Also, your function should return
counter
instead of print it. This has two advantages:It will keep the script from printing
None
at the end (the function's default return value).It allows you to condense these two lines:
into just one:
Finally, as @FMc noted in a comment, you can improve the efficiency of the function by doing two things:
Starting
counter
at the smaller of the function's two arguments.Incrementing
counter
by this value.Below is a version of your script that addresses all this:
Oh, and one more thing.
input
in Python 2.x evaluates its input as real Python code. Meaning, it is dangerous to use with uncontrolled input.A better approach is to use
raw_input
and then explicitly convert the input into integers withint
: