Created
January 6, 2020 17:03
-
-
Save AbsolutelySaurabh/38201d2dbc598aa7854b2b501a9bdae3 to your computer and use it in GitHub Desktop.
Adding Fractions in java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.*; | |
import java.util.*; | |
/* | |
* To execute Java, please define "static void main" on a class | |
* named Solution. | |
* | |
* If you need more classes, simply define them inline. | |
*/ | |
class Solution { | |
private static double gcd(int a, int b){ | |
if(a == 1 || b == 1){ | |
return 1; | |
} | |
if(a == b){ | |
return a; | |
} | |
if(a > b){ | |
return gcd(a-b, b); | |
} | |
return gcd(a, b-a); | |
} | |
private static double lcm(int a, int b){ | |
return (a*b)/gcd(a, b); | |
} | |
private static double add(int num1, int den1, int num2, int den2){ | |
if(den1 == den2){ | |
return (num1+num2)/den1; | |
} | |
double ans = (num1*den2 + num2*den1)/lcm(den1, den2); | |
int ans1 = (int)num1*den2 + num2*den1; | |
int ans2 = (int)lcm(den1, den2); | |
//print in fraction form | |
System.out.println(ans1 + " / " + ans2); | |
return ans; | |
} | |
public static void main(String[] args) { | |
Scanner s = new Scanner(System.in); | |
int test = s.nextInt(); | |
while(test>0){ | |
int num1 = s.nextInt(); | |
int den1 = s.nextInt(); | |
int num2 = s.nextInt(); | |
int den2 = s.nextInt(); | |
System.out.printf("%.2f", add(num1, den1, num2, den2)); | |
test--; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment