Hello! My name is "Nisanth" and welcome to my blog, Articklez! In this post, I'm going to show you how to make a simple LCM/HCF calculator. We will be using Python for this project. Go to "python.org" to install Python. Check out the below image for how to install it.
Open any text editor—such as Notepad, Notepad ++, Visual Studio Code, or Sublime Text—and start typing. In python, a bunch of code can be associated with a block based on the indentation. First, type the following text.
print("LCM/HCF calculator")
This will simply display "LCM/HCF calculator". Now, to declare the variables. A "variable" is just a value that can be changed afterwards. They can be integers, text, lists, or boolean values (True/False); among others.
num1 = int(input("Enter the first number.\n"))
num2 = int(input("Enter the second number.\n"))
lcm = 0
hcf = 0
found = False
lcmOrHcf = input("Would you like to find the LCM or HCF?\n").upper()
In the first two declarations, we are using "int()" and "input()". "input()" allows the user to enter something. This is stored as text. "int()" converts numbers stored as text, to actual numbers. ".upper()" converts all the text to capital letters.
if lcmOrHcf == "LCM":
if num2 > num1:
counter = num2
if num1 > num2:
counter = num1
while found == False:
if (counter % num1 == 0) and (counter % num2 == 0):
lcm = counter
found = True
else:
counter += 1
print("The LCM is " + str(lcm) + ".")
The first line is an "if" condition. If "lcmOrHcf"—the variable we declared—is "LCM", it sets "counter" to the smaller number. Then, the "while" loop we declared keeps running the code under it as long as "found" is False. If the counter is divisible by both numbers, it sets "lcm" to "counter" and "found" to True. If otherwise, it increases "counter" by 1. Once the loop is over (indicating that "found" is True), it displays the LCM. "str()" converts the LCM to text because "print()" can only display text.
elif lcmOrHcf == "HCF":
if num2 > num1:
counter = num1
if num1 > num2:
counter = num2
while found == False:
if (num1 % counter == 0) and (num2 % counter == 0):
hcf = counter
found = True
else:
counter -= 1
print("The HCF is " + str(hcf) + ".")
The first line is an "elif" condition. If the previous condition is false and this condition is true, it runs the code. If "lcmOrHcf"—the variable we declared—is "HCF", it sets "counter" to the larger number. If the both numbers are divisible by "counter", it sets "hcf" to "counter" and "found" to True. If otherwise, it decreases "counter" by 1. Once the loop is over (indicating that "found" is True), it displays the HCF. "str()" converts the HCF to text because "print()" can only display text. It's complete! To view the output, in your cmd/terminal, open the directory and type "python " and the filename. The below pictures should elaborate.
Here is the output.
Thank you!
Comments
Post a Comment