HCF of array of fractions ( or rational numbers ) | Java program to find HCF of array of rational numbers ( fractions ) . ; hcf of two number ; find hcf of numerator series ; return hcf of numerator ; find lcm of denominator series ; ans contains LCM of arr [ 0 ] [ 1 ] , . . arr [ i ] [ 1 ] ; return lcm of denominator ; Core Function ; found hcf of numerator ; found lcm of denominator ; return result ; Driver code ; Initialize the every row with size 2 ( 1 for numerator and 2 for denominator ) ; function for calculate the result ; print the result
class GFG { static int gcd ( int a , int b ) { if ( a % b == 0 ) return b ; else return ( gcd ( b , a % b ) ) ; } static int findHcf ( int [ ] [ ] arr , int size ) { int ans = arr [ 0 ] [ 0 ] ; for ( int i = 1 ; i < size ; i ++ ) ans = gcd ( ans , arr [ i ] [ 0 ] ) ; return ( ans ) ; } static int findLcm ( int [ ] [ ] arr , int size ) { int ans = arr [ 0 ] [ 1 ] ; for ( int i = 1 ; i < size ; i ++ ) ans = ( ( ( arr [ i ] [ 1 ] * ans ) ) / ( gcd ( arr [ i ] [ 1 ] , ans ) ) ) ; return ( ans ) ; } static int [ ] hcfOfFraction ( int [ ] [ ] arr , int size ) { int hcf_of_num = findHcf ( arr , size ) ; int lcm_of_deno = findLcm ( arr , size ) ; int [ ] result = new int [ 2 ] ; result [ 0 ] = hcf_of_num ; result [ 1 ] = lcm_of_deno ; for ( int i = result [ 0 ] / 2 ; i > 1 ; i -- ) { if ( ( result [ 1 ] % i == 0 ) && ( result [ 0 ] % i == 0 ) ) { result [ 1 ] /= i ; result [ 0 ] /= i ; } } return ( result ) ; } public static void main ( String [ ] args ) { int size = 4 ; int [ ] [ ] arr = new int [ size ] [ size ] ; for ( int i = 0 ; i < size ; i ++ ) arr [ i ] = new int [ 2 ] ; arr [ 0 ] [ 0 ] = 9 ; arr [ 0 ] [ 1 ] = 10 ; arr [ 1 ] [ 0 ] = 12 ; arr [ 1 ] [ 1 ] = 25 ; arr [ 2 ] [ 0 ] = 18 ; arr [ 2 ] [ 1 ] = 35 ; arr [ 3 ] [ 0 ] = 21 ; arr [ 3 ] [ 1 ] = 40 ; int [ ] result = hcfOfFraction ( arr , size ) ; System . out . println ( result [ 0 ] + " , ▁ " + result [ 1 ] ) ; } }