Saturday, June 19, 2021
Home coding Write a program to add two fraction.

Write a program to add two fraction.

Given a two fraction number,we need to add both of them and print their resultant value on screen

Example:

input: 1 5 3 15
output:2 5

Logic:

step 1- find the numerator and denominator of the both number.
step 2-calculate the gcd of both number.
step 3-divide gcd by numbers.

Code-

#include<bits/stdc++.h>
using namespace std;
int gcd(int a, int b) 
{
   if (a == 0)
      return b;
   return gcd(b%a, a);
}
void factor(int &d, int &n) {
 
   int factor = gcd(n,d);
   d = d/factor;
   n=n/factor;
}
void add(int n1, int d1, int n2, int d2, int &n3, int &d3)
{
   d3 = gcd(d1,d2);
   d3 = (d1*d2) / d3;
   n3 = (n1)*(d3/d1) + (n2)*(d3/d2);
   factor(d3,n3);
}
int main() {
   int n1=1;
   int d1=4;
   int n2=2;
   int d2=12;
   int d3, n3;
   add(n1, d1, n2, d2, n3, d3);
 cout<<n3<<"/"<<d3<<endl;
  
}

Output:

5/12

Time complexity:0(N)

Space Complexity:O(1)

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -

Most Popular

Recent Comments