Skip to content

Instantly share code, notes, and snippets.

@weihao
Created October 29, 2019 22:58
Show Gist options
  • Save weihao/17153354591a82bdfa088f719ac89acc to your computer and use it in GitHub Desktop.
Save weihao/17153354591a82bdfa088f719ac89acc to your computer and use it in GitHub Desktop.
import java.math.BigInteger;
import java.util.Scanner;
public class RationalRatio {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String[] s = sc.nextLine().split(" ");
int repeating_digits = Integer.parseInt(s[1]);
String[] split = s[0].split("\\.");
int diff = split[1].length() - repeating_digits;
BigInteger numerator = new BigInteger(split[0] + split[1]);
StringBuilder sub = new StringBuilder(split[0]);
for (int i = 0; i < diff; i++) {
sub.append(split[1].charAt(i));
}
numerator = numerator.subtract(new BigInteger(sub.toString()));
StringBuilder sb = new StringBuilder("1");
for (int i = 0; i < split[1].length(); i++) {
sb.append("0");
}
StringBuilder temp = new StringBuilder("1");
for (int i = 0; i < diff; i++) {
temp.append("0");
}
BigInteger dem = new BigInteger(sb.toString());
dem = dem.subtract(new BigInteger(temp.toString()));
while (gcd(numerator, dem) != 1) {
long gcd = gcd(numerator, dem);
numerator = numerator.divide(new BigInteger(String.valueOf(gcd)));
dem = dem.divide(new BigInteger(String.valueOf(gcd)));
}
System.out.println(String.format("%d/%d", numerator, dem));
}
public static int gcd(BigInteger a, BigInteger b) {
BigInteger gcd = a.gcd(b);
return gcd.intValue();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment