Below is a program which takes a numerator and a denominator as a user input and reduce the fraction to its lowest terms.
Python
def g_c_d(num1, num2):
if num2 == 0:
return num1
else:
return g_c_d(num2, num1 % num2)
def to_lowest_terms(numerator, denominator):
if denominator == 0:
return False
gcd = g_c_d(numerator, denominator)
numerator //= gcd
denominator //= gcd
return True
# Test cases
numerator = 48
denominator = 9
if to_lowest_terms(numerator, denominator):
print(f"The lowest terms of your fraction: {numerator}/{denominator}")
else:
print("Invalid input, denominator cannot be 0!")
numerator = -9
denominator = 45
if to_lowest_terms(numerator, denominator):
print(f"The lowest terms of your fraction: {numerator}/{denominator}")
else:
print("Invalid input, denominator cannot be 0!")
numerator = 8
denominator = 2
if to_lowest_terms(numerator, denominator):
print(f"The lowest terms of your fraction: {numerator}/{denominator}")
else:
print("Invalid input, denominator cannot be 0!")
So, the above program is one that works for all types of bad inputs from the user and recovers from the errors. For example, if the user enters a non-whole number for the numerator or denominator, the program will print an error message and ask the user to enter a new value.
So, If the user enters 0 for the denominator, the program will print an error message and terminate.