VOOZH about

URL: https://www.geeksforgeeks.org/dsa/program-to-add-two-fractions/

⇱ Program to add two fractions - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Program to add two fractions

Last Updated : 21 Mar, 2025

Given two integer arrays a[] and b[] containing two integers each representing the numerator and denominator of a fraction respectively. The task is to find the sum of the two fractions and return the numerator and denominator of the result.

Examples :

Input: a = [1, 2] , b = [3, 2]
Output: [2, 1]
Explanation: 1/2 + 3/2 = 2/1

Input: a = [1, 3] , b = [3, 9]
Output: [2, 3]
Explanation: 1/3 + 3/9 = 2/3

Input: a = [1, 5] , b = [3, 15]
Output: [2, 5]
Explanation: 1/5 + 3/15 = 2/5

Algorithm to Add Two Fractions

  • Find a common denominator by finding the LCM (Least Common Multiple) of the two denominators.
  • Change the fractions to have the same denominator and add both terms.
  • Reduce the final fraction obtained into its simpler form by dividing both the numerator and denominator by their largest common factor.

Output
2, 1

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

Comment
Article Tags: