Fraction | Java program to add 2 fractions ; Function to return gcd of a and b ; Function to convert the obtained fraction into it 's simplest form ; Finding gcd of both terms ; Converting both terms into simpler terms by dividing them by common factor ; Function to add two fractions ; Finding gcd of den1 and den2 ; Denominator of final fraction obtained finding LCM of den1 and den2 LCM * GCD = a * b ; Changing the fractions to have same denominator . Numerator of the final fraction obtained ; Calling function to convert final fraction into it 's simplest form ; Driver Code
import java . util . * ; class GFG { static int den3 , num3 ; static int gcd ( int a , int b ) { if ( a == 0 ) return b ; return gcd ( b % a , a ) ; } static void lowest ( ) { int common_factor = gcd ( num3 , den3 ) ; den3 = den3 / common_factor ; num3 = num3 / common_factor ; } static void addFraction ( int num1 , int den1 , int num2 , int den2 ) { den3 = gcd ( den1 , den2 ) ; den3 = ( den1 * den2 ) / den3 ; num3 = ( num1 ) * ( den3 / den1 ) + ( num2 ) * ( den3 / den2 ) ; lowest ( ) ; } public static void main ( String [ ] args ) { int num1 = 1 , den1 = 500 , num2 = 2 , den2 = 1500 ; addFraction ( num1 , den1 , num2 , den2 ) ; System . out . printf ( "%d/%d + %d/%d is equal to %d/%dNEW_LINE", num1, den1, num2, den2, num3, den3); } }