VOOZH about

URL: https://www.geeksforgeeks.org/dsa/product-given-n-fractions-reduced-form/

⇱ Product of given N fractions in reduced form - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Product of given N fractions in reduced form

Last Updated : 23 Jun, 2022

Given the Numerator and Denominator of N fractions. The task is to find the product of N fraction and output the answer in reduced form.
Examples: 
 

Input : N = 3
 num[] = { 1, 2, 5 }
 den[] = { 2, 1, 6 }
Output : 5/6
Product of 1/2 * 2/1 * 5/6 is 10/12.
Reduced form of 10/12 is 5/6.

Input : N = 4
 num[] = { 1, 2, 5, 9 }
 den[] = { 2, 1, 6, 27 }
Output : 5/18


 


The idea is to find the product of Numerator in a variable, say new_num. Now, find the product of Denominator in another variable, say new_den. 
Now, to find the answer in Reduced form, find the Greatest Common Divisor of new_num and new_den and divide the new_num and new_den by the calculated GCD.
Below is the implementation of this approach: 
 

Output :  

5/6

Time Complexity: O(n + log(min(a,b))) 
Auxiliary Space: O(log(min(a,b)))


How to avoid overflow? 
The above solution causes overflow for large numbers. We can avoid overflow by first finding prime factors of all numerators and denominators. Once we have found prime factors, we can cancel common prime factors.
Note : When you are asked to represent the answer in form of {P \times {Q} ^ {-1}} . 
For these questions, first convert the numerator and denominator in reducible form P / Q as explained above. Then, find modular multiplicative inverse of Q with respect to a prime number m (Generally, 10^9 + 7) which is given in question. After finding modular multiplicative inverse of Q, multiply it with P and take modulo with given prime number m which gives us our required output.
// Thanks VaiBzZk for suggesting this condition.

Please suggest if someone has a better solution which is more efficient in terms of space and time.
 

Comment
Article Tags: