How to Simplify a Fraction
How to Simplify a Fraction
How to Simplify a Fraction
Given a numerator and a denominator, I need to simplify the fraction to its lowest terms. How can I do this?
solveurit24@gmail.com Changed status to publish February 16, 2025
You can find the greatest common divisor (GCD) of the numerator and denominator and divide both by it.
Code Example:
import math
def simplify_fraction(numerator, denominator):
if denominator == 0:
raise ValueError("Denominator cannot be zero.")
gcd = math.gcd(numerator, denominator)
return (numerator // gcd, denominator // gcd)
# Example usage
print(simplify_fraction(12, 18)) # Output: (2, 3)This function calculates the GCD of the numerator and denominator and returns the simplified fraction.
solveurit24@gmail.com Changed status to publish February 16, 2025