Interesting question. Here's some executable code that does it with minimal code:
/** @return the greatest common denominator */
public static long gcd(long a, long b) {
return b == 0 ? a : gcd(b, a % b);
}
public static String asFraction(long a, long b) {
long gcd = gcd(a, b);
return (a / gcd) + "/" + (b / gcd);
}
// Some tests
public static void main(String[] args) {
System.out.println(asFraction(500, 1000)); // "1/2"
System.out.println(asFraction(17, 3)); // "17/3"
System.out.println(asFraction(462, 1071)); // "22/51"
}
Bonus methods:
/** @return the lowest common multiple */
public static long lcm(long a, long b) {
return a * b / gcd(a, b);
}
/** @return the greatest common denominator */
public static long gcd(List<? extends Number> numbers) {
return numbers.stream().map(Number::longValue).reduce((a, b) -> gcd(a, b)).orElseThrow(NoSuchElementException::new);
}
/** @return the lowest common multiple */
public static long lcm(List<? extends Number> numbers) {
return numbers.stream().map(Number::longValue).reduce((a, b) -> lcm(a, b)).orElseThrow(NoSuchElementException::new);
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…