Java 中的 BigInteger 上的數學運算


讓我們使用 Java 中的內建方法對 BigInteger 執行以下運算。

Addition: add() method
Subtraction: subtract() method
Multiplication: multiply() method
Division: divide() method

讓我們建立三個 BigInteger 物件。

BigInteger one = new BigInteger("98765432123456789");
BigInteger two = new BigInteger("94353687526754387");
BigInteger three = new BigInteger("96489687526737667");

對它們應用數學運算。

one = one.add(two);
System.out.println("Addition Operation = " + one);
one = one.multiply(two);
System.out.println("Multiplication Operation = " + one);

以下是一個示例 −

示例

 線上演示

import java.math.BigInteger;
public class Main {
   public static void main(String[] args) {
      BigInteger one = new BigInteger("98765432123456789");
      BigInteger two = new BigInteger("94353687526754387");
      BigInteger three = new BigInteger("96489687526737667");
      one = one.add(two);
      System.out.println("Addition Operation = " + one);
      one = one.multiply(two);
      System.out.println("Multiplication Operation = " + one);
      two = three.subtract(two);
      System.out.println("Subtract Operation = " + two);
      two = three.divide(two);
      System.out.println("Division Operation = " + two);
   }
}

輸出

Addition Operation = 193119119650211176
Multiplication Operation = 18221501070917918273532554434429112
Subtract Operation = 2135999999983280
Division Operation = 45

更新於: 30-Jul-2019

2K+ 瀏覽

開啟你的 事業

透過完成課程獲得認證

開始吧
廣告