FIND ADDITION OF TWO FRACTIONS



You are given four numbers num1, den1, num2, and den2. You need to find(num1/den1)+(num2/den2) and output the result in the form of (numx/denx).
Input Format:
The first line of input contains an integer T denoting the number of test cases . Then T test cases follow . Each test case contains four integers num1, den1, num2, den2respectively .
Output Format:
For each test case, in a new line,  output will be the fraction in the form a/b where the fraction denotes the sum of the two given fractions in reduced form.
Your Task:
Since this is a function problem, you don't need to worry about the testcases. Your task is to complete the function addFraction  which adds the two fractions and prints the resulting fraction. The function takes four arguments num1, den1, num2, den2where num1, num2 denotes the numerators of two fractions and den1, den2denotes their denominators.
Constraints:
1 <= T <= 100
1 <= den1,den2,num1,num2 <= 1000
Example:
Input

1
1 500 2 500

Output
3/500
Explanation:
In above test case 1/500+2/500=3/500

Note:The Input/Ouput format and Example given are used for system's internal purpose, and should be used by a user for Expected Output only. As it is a function problem, hence a user should not read any input from stdin/console. The task is to complete the function specified, and not to write the full code.

import java.util.*;
class Fraction_Addition
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
while(T>0)
{
int a = sc.nextInt();
int b = sc.nextInt();
int c = sc.nextInt();
int d = sc.nextInt();
GfG g = new GfG();
g.addFraction(a,b,c,d);
T--;
}
}
}
}

/*Please note that it's Function problem i.e.
you need to write your solution in the form of Function(s) only.
Driver Code to call/invoke your function is mentioned above.*/

/*You are required to complete this function*/
class GfG
{
    void addFraction(int num1, int den1, int num2, int den2)
    {
        int den3=gcd(den1,den2);
        den3 = (den1*den2) / den3; 
        int num3 = (num1)*(den3/den1) + (num2)*(den3/den2); 
        lowest(den3,num3);  
    }
    static int gcd(int a,int b)
{
if (a == 0)  
        return b;  
    return gcd(b%a, a);  

}
static void lowest(int den3, int num3)  
{  
    // Finding gcd of both terms  
    int common_factor = gcd(num3,den3);  
  
    // Converting both terms into simpler  
    // terms by dividing them by common factor  
    den3 = den3/common_factor;  
    num3 = num3/common_factor; 
    System.out.println(num3+"/"+den3); 
}  
  
}

Comments

Popular posts from this blog

Problem Statement Of Real Estate Use Cases

Problem Statement Of Bank Marketing analysis

Hadoop