在 Java 中簡化或減少分數

Zeeshan Afridi 2023年10月12日
在 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
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