Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Practice Mathematical Algorithm
  • Mathematical Algorithms
  • Pythagorean Triplet
  • Fibonacci Number
  • Euclidean Algorithm
  • LCM of Array
  • GCD of Array
  • Binomial Coefficient
  • Catalan Numbers
  • Sieve of Eratosthenes
  • Euler Totient Function
  • Modular Exponentiation
  • Modular Multiplicative Inverse
  • Stein's Algorithm
  • Juggler Sequence
  • Chinese Remainder Theorem
  • Quiz on Fibonacci Numbers
Open In App
Next Article:
Fraction to Recurring Decimal
Next article icon

Program to add two fractions

Last Updated : 21 Mar, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

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.
C++
#include<bits/stdc++.h> using namespace std;  // Function to find gcd of a and b int gcd(int n1, int n2) {     if (n1 == 0)         return n2;     return gcd(n2%n1, n1); }  //Function to add two fractions vector<int> addFraction(vector<int> a, vector<int>b) {     vector<int> ans;      // Finding gcd of den1 and den2     int den = gcd(a[1],b[1]);      // Denominator of final fraction obtained     // finding LCM of den1 and den2     // LCM * GCD = a * b      den = (a[1]*b[1]) / den;      // Changing the fractions to have same denominator     // Numerator of the final fraction obtained     int num = (a[0])*(den/a[1]) + (b[0])*(den/b[1]);      // finding the common factor of numerator and denominator     int common_factor = gcd(num,den);      // Converting the result into simpler      // fraction by dividing them with common factor      den = den/common_factor;     num = num/common_factor;     ans.push_back(num);      ans.push_back(den);      return ans;      }  int main() {     vector<int> a = {1,2};     vector<int> b = {3,2};     vector<int> ans = addFraction(a, b);      cout<<ans[0]<<", "<<ans[1];     return 0; } 
C
#include <stdio.h>  // Function to find gcd of a and b int gcd(int n1, int n2) {     if (n1 == 0)         return n2;     return gcd(n2 % n1, n1); }  // Function to add two fractions void addFraction(int a[], int b[], int result[]) {     // Finding gcd of den1 and den2     int den = gcd(a[1], b[1]);      // Denominator of final fraction obtained     // finding LCM of den1 and den2     // LCM * GCD = a * b      den = (a[1] * b[1]) / den;      // Changing the fractions to have same denominator     // Numerator of the final fraction obtained     int num = (a[0]) * (den / a[1]) + (b[0]) * (den / b[1]);      // finding the common factor of numerator and denominator     int common_factor = gcd(num, den);      // Converting the result into simpler      // fraction by dividing them with common factor      den = den / common_factor;     num = num / common_factor;     result[0] = num;     result[1] = den; }  int main() {     int a[] = {1,2};;     int b[] = {3,2};;     int ans[2];     addFraction(a, b, ans);     printf("%d, %d", ans[0], ans[1]);     return 0; } 
Java
import java.util.ArrayList; import java.util.List;  public class Main {     // Function to find gcd of a and b     public static int gcd(int n1, int n2) {         if (n1 == 0)             return n2;         return gcd(n2 % n1, n1);     }      // Function to add two fractions     public static List<Integer> addFraction(List<Integer> a, List<Integer> b) {         List<Integer> ans = new ArrayList<>();          // Finding gcd of den1 and den2         int den = gcd(a.get(1), b.get(1));          // Denominator of final fraction obtained         // finding LCM of den1 and den2         // LCM * GCD = a * b          den = (a.get(1) * b.get(1)) / den;          // Changing the fractions to have same denominator         // Numerator of the final fraction obtained         int num = (a.get(0)) * (den / a.get(1)) + (b.get(0)) * (den / b.get(1));          // finding the common factor of numerator and denominator         int common_factor = gcd(num, den);          // Converting the result into simpler          // fraction by dividing them with common factor          den = den / common_factor;         num = num / common_factor;         ans.add(num);          ans.add(den);          return ans;     }      public static void main(String[] args) {         List<Integer> a = new ArrayList<>();         a.add(1);         a.add(2);         List<Integer> b = new ArrayList<>();         b.add(3);         b.add(2);         List<Integer> ans = addFraction(a, b);          System.out.println(ans.get(0) + ", " + ans.get(1));     } } 
Python
from math import gcd  # Function to add two fractions def addFraction(a, b):     # Finding gcd of den1 and den2     den = gcd(a[1], b[1])      # Denominator of final fraction obtained     # finding LCM of den1 and den2     # LCM * GCD = a * b      den = (a[1] * b[1]) // den      # Changing the fractions to have same denominator     # Numerator of the final fraction obtained     num = (a[0]) * (den // a[1]) + (b[0]) * (den // b[1])      # finding the common factor of numerator and denominator     common_factor = gcd(num, den)      # Converting the result into simpler      # fraction by dividing them with common factor      den //= common_factor     num //= common_factor     return [num, den]  if __name__ == '__main__':     a = [1, 2]     b = [3, 2]     ans = addFraction(a, b)     print(f'{ans[0]}, {ans[1]}') 
C#
// Function to find gcd of a and b int gcd(int n1, int n2) {     if (n1 == 0)         return n2;     return gcd(n2 % n1, n1); }  // Function to add two fractions List<int> addFraction(List<int> a, List<int> b) {     List<int> ans = new List<int>();      // Finding gcd of den1 and den2     int den = gcd(a[1], b[1]);      // Denominator of final fraction obtained     // finding LCM of den1 and den2     // LCM * GCD = a * b      den = (a[1] * b[1]) / den;      // Changing the fractions to have same denominator     // Numerator of the final fraction obtained     int num = (a[0]) * (den / a[1]) + (b[0]) * (den / b[1]);      // finding the common factor of numerator and denominator     int common_factor = gcd(num, den);      // Converting the result into simpler      // fraction by dividing them with common factor      den = den / common_factor;     num = num / common_factor;     ans.Add(num);      ans.Add(den);      return ans; }  public static void Main() {     List<int> a = new List<int> {1,2};     List<int> b = new List<int> {3,2};     List<int> ans = addFraction(a, b);      Console.WriteLine(ans[0] + ", " + ans[1]); } 
JavaScript
// Function to find gcd of a and b function gcd(n1, n2) {     if (n1 === 0)         return n2;     return gcd(n2 % n1, n1); }  // Function to add two fractions function addFraction(a, b) {     let ans = [];      // Finding gcd of den1 and den2     let den = gcd(a[1], b[1]);      // Denominator of final fraction obtained     // finding LCM of den1 and den2     // LCM * GCD = a * b      den = (a[1] * b[1]) / den;      // Changing the fractions to have same denominator     // Numerator of the final fraction obtained     let num = (a[0]) * (den / a[1]) + (b[0]) * (den / b[1]);      // finding the common factor of numerator and denominator     let common_factor = gcd(num, den);      // Converting the result into simpler      // fraction by dividing them with common factor      den = den / common_factor;     num = num / common_factor;     ans.push(num);      ans.push(den);      return ans; }  let a = [1, 2]; let b = [3, 2]; let ans = addFraction(a, b);  console.log(ans[0] + ", " + ans[1]); 

Output
2, 1

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



Next Article
Fraction to Recurring Decimal

R

Rahul Agrawal
Improve
Article Tags :
  • DSA
  • Mathematical
  • GCD-LCM
Practice Tags :
  • Mathematical

Similar Reads

  • Program to compare two fractions
    Given two fractions a/b and c/d, compare them and print the larger of the two. Examples : Input: 5/6, 11/45Output: 5/6 Input: 4/5 and 2/3Output: 4/5 We can simply convert the fractions into floating-point values by dividing the numerator by the denominator. Once we have the two floating-point number
    5 min read
  • LCM and HCF of fractions
    Given n fractions as two arrays Num and Den. The task is to find out the L.C.M of the fractions. Examples: Input: num[] = {1, 7, 4}, den[] = {2, 3, 6} Output: LCM is = 28/1 The given fractions are 1/2, 7/3 and 4/6. The LCM is 28/1 Input: num[] = {24, 48, 72, 96}, den[] = {2, 6, 8, 3} Output: LCM is
    13 min read
  • Program to solve the Alligation Problem
    Write a program to find the ratio in which a shopkeeper will mix two types of rice worth Rs. [Tex]X [/Tex]kg and Rs. [Tex]Y [/Tex]kg, so that the average cost of the mixture is Rs. [Tex]Z [/Tex]kg. Examples: Input: X = 50, Y = 70, Z = 65Output: Ratio = 1:3 Input: X = 1000, Y = 2000, Z = 1400Output:
    6 min read
  • Fraction to Recurring Decimal
    Given two integers a and b(b != 0), the task is to return the fraction a/b in string format. If the fractional part is repeating, enclose the repeating part in parentheses. Examples: Input: a = 1, b = 2Output: "0.5"Explanation: 1/2 = 0.5 with no repeating part.Input: a = 50, b = 22Output: "2.(27)"Ex
    8 min read
  • Reduce the fraction to its lowest form
    Given two integers x and y and where x is divisible by y. It can be represented in the form of a fraction x/y. The task is to reduce the fraction to its lowest form.Examples: Input : x = 16, y = 10 Output : x = 8, y = 5 Input : x = 10, y = 8 Output : x = 5, y = 4 Approach: Both of the values x and y
    4 min read
  • Find the Nth digit in the proper fraction of two numbers
    Given three integers P, Q and N where P < Q, the task is to compute the fraction value of P / Q and find the Nth digit after the decimal.Example Input: P = 1, Q = 2, N = 1 Output: 5 (1 / 2) = 0.5 and 5 is the first digit after the decimal.Input: P = 5, Q = 6, N = 5 Output: 3 (5 / 6) = 0.833333333
    4 min read
  • C++ program to divide a number by 3 without using *, / , +, -, % operators
    For a given positive number we need to divide a number by 3 without using any of these *, /, +, – % operatorsExamples: Input : 48 Output : 16 Input : 16 Output : 5 Algorithm Take a number num, sum = 0while(num>3), shift the number left by 2 bits and sum = add(num >> 2, sum). Create a functi
    2 min read
  • Program to convert float decimal to Octal number
    Write a program that converts a floating-point decimal number into its octal format. The program should take a number and the precision for the octal fractional part as inputs from the user. It should calculate and provide its correct octal representation as output. Examples: Input: Number = 123.45,
    8 min read
  • Addition of two numbers without carry
    You are given two positive numbers n and m. You have to find a simple addition of both numbers but with a given condition that there is not any carry system in this addition. That is no carry is added at higher MSBs.Examples : Input : m = 456, n = 854 Output : 200 Input : m = 456, n = 4 Output : 450
    6 min read
  • HCF of array of fractions (or rational numbers)
    Given a fraction series. Find the H.C.F of a given fraction series. Examples: Input : [{2, 5}, {8, 9}, {16, 81}, {10, 27}] Output : 2, 405 Explanation : 2/405 is the largest number that divides all 2/5, 8/9, 16/81 and 10/27. Input : [{9, 10}, {12, 25}, {18, 35}, {21, 40}] Output : 3, 1400 Approach:
    8 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences