在 Java 中简化或减少分数

Zeeshan Afridi 2022年5月31日
在 Java 中简化或减少分数

在数学中,分数代表整体的一部分或一部分。它有分子和分母两部分,其中分子是被除数,分母是除数。

示例:500/1000 是等于 1/20.5 的分数。

在 Java 中简化或减少分数

在计算机编程中,实现任务或目标的方法总是不止一种。但最好和最有效的解决方案是具有以下特点的解决方案:

  1. 简洁精确的代码
  2. 具有高性能
  3. 空间复杂度低

分数示例代码:

package articlecodesinjava;
class Fraction{

    public static long gcd(long x, long y) {
    return y == 0 ? x : gcd(y, x % y);
    }

public static String asFraction(long x, long y) {
    long gcd = gcd(x, y);
    return (x / gcd) + "/" + (y / gcd);
    }
}

class GuessingGame {
public static void main(String[] args){

    Fraction obj = new Fraction();  // Create the object of Fraction class

    System.out.println("Output");

    System.out.println(obj.asFraction(500, 1000));
    System.out.println(obj.asFraction(9, 3));
    System.out.println(obj.asFraction(11, 2));
    System.exit(0);
    }
}

输出:

Output
1/2
3/1
11/2
Zeeshan Afridi avatar Zeeshan Afridi avatar

Zeeshan is a detail oriented software engineer that helps companies and individuals make their lives and easier with software solutions.

LinkedIn

相关文章 - Java Math