如何对 BigInteger 使用运算符

She*_*han 0 java operators biginteger

import java.lang.Math;
import java.math.BigInteger;
import java.math.BigDecimal;

public class Main {
    public static void main(String[] args) {
        int e1 = 20, d = 13;
        BigInteger C = BigDecimal.valueOf(e1).toBigInteger();

        BigInteger po = C.pow(d);
        System.out.println("pow is:" + po);

        int num = 11;
        BigInteger x = po;
        BigInteger n = BigDecimal.valueOf(num).toBigInteger();
        BigInteger p, q, m;

        System.out.println("x: " + x);

        q=(x / n);
        p=(q * n);
        m=(x - p);
        System.out.println("mod is:" + m);
    }
}
Run Code Online (Sandbox Code Playgroud)

我试过寻找一些与之相关的答案,但无法解决。请有人告诉我这有什么问题。我将数据类型更改为整数,但幂函数不起作用。

这是我得到的错误:

error: bad operand types for binary operator '/'
    q=(x/n);
        ^
  first type:  BigInteger
  second type: BigInteger
Main.java:33: error: bad operand types for binary operator '*'
    p=(q*n);
        ^
  first type:  BigInteger
  second type: BigInteger
Main.java:34: error: bad operand types for binary operator '-'
    m=(x-p);
        ^
  first type:  BigInteger
  second type: BigInteger
3 errors

    .
Run Code Online (Sandbox Code Playgroud)

Zab*_*uza 8

解释

您不能使用 上的运算符BigInteger。它们不是像 那样的原语int,它们是类。Java 没有运算符重载。

查看类文档并使用相应的方法:

BigInteger first = BigInteger.ONE;
BigInteger second = BigInteger.TEN;

BigInteger addResult = first.add(second);
BigInteger subResult = first.subtract(second);
BigInteger multResult = first.multiply(second);
BigInteger divResult = first.divide(second);
Run Code Online (Sandbox Code Playgroud)

运营商详情

您可以在Java 语言规范(JLS) 中查找运算符的详细定义以及何时可以使用它们。

以下是相关部分的一些链接:

它们中的大多数使用数字类型 §4的概念,它由Integral TypeFloatingPointType 组成

整数类型为byteshortintlong,其值分别为 8 位、16 位、32 位和 64 位有符号二进制补码整数,和char,其值为表示 UTF-16 代码的 16 位无符号整数单位(第3.1 节)。

浮点类型是float,其值包括 32 位 IEEE 754 浮点数,和double,其值包括 64 位 IEEE 754 浮点数。

此外,Java可以拆箱包装类似Integerint反之亦然,如果需要的话,副。这将第5.1.8 节的拆箱转换添加到支持的操作数集。


笔记

你的创建BigInteger是不必要的冗长和复杂:

// Yours
BigInteger C = BigDecimal.valueOf(e1).toBigInteger();

// Prefer this instead
BigInteger c = BigInteger.valueOf(e1);
Run Code Online (Sandbox Code Playgroud)

如果可能,您应该更喜欢从StringtoBigInteger和 from BigIntegerto String。由于 的目的BigInteger是将它用于太大而无法用原语表示的数字:

// String -> BigInteger
String numberText = "10000000000000000000000000000000";
BigInteger number = new BigInteger(numberText);

// BigInteger -> String
BigInteger number = ...
String numberText = number.toString();
Run Code Online (Sandbox Code Playgroud)

另外,请遵守 Java 命名约定。变量名应该是驼峰式大小写,所以c而不是C.

此外,更喜欢具有有意义的变量名称。类似cd不帮助任何人理解变量应该代表什么的名称。