Euclid’s Algorithm allows you to find the HCF of two numbers. The steps of the algorithm are given below:
- Ask the user for 2 numbers
- Test which one is bigger
- Make the bigger number m and the smaller number n
- Set r to be the remainder when m is divided by n
- Set n to m
- Set r to n
- If r is 0, the HCF is n. Stop
- Else go back to step 5
This article will cover steps 1 to 3. The first step is to create a script and name it euclid.py.
To write the code for step 1, enter the code shown below into the script:
# Ask the user for the first number first_number = int(input("Please enter the first number: ")) # Ask the user for the second number second_number = int(input("Please enter the second number: "))
To test which of the input numbers is bigger, we will use the greater than symbol. We will ignore other cases. The code to do this is shown below:
# Test if the second number is bigger than the first number if (second_number > first_number): # Swap if the first number is greater than the second number temp = second_number second_number = first_number first_number = temp # Print out to check the swap print(first_number, second_number)
Now the program can receive input and swap them correctly. Below is an image of a running program.
