Java 如何对BigInteger使用运算符

Java 如何对BigInteger使用运算符,java,operators,biginteger,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;

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

这是我得到的错误:

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);
    }
}
解释 不能在
biginger
上使用运算符。它们不是像
int
那样的原语,而是类。Java没有运算符重载

查看并使用相应的方法:

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

    .

操作员详细信息 您可以在(JLS)中查找运算符的详细定义以及何时可以使用它们

以下是相关章节的一些链接:

  • 乘法
    *
  • 分部
    /
  • 字符串串联
    +
  • 加减法
    +
    -
它们中的大多数都使用数值类型的概念,包括积分类型浮点类型

整数类型有
字节
整数
,其值分别为8位、16位、32位和64位有符号二位补码整数;
字符
,其值为代表UTF-16码单元的16位无符号整数()

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

此外,如果需要,Java可以将
Integer
之类的包装类取消装箱到
int
中,反之亦然。将取消装箱转换添加到支持的操作数集中


笔记 您创建的
BigInteger
过长且复杂:

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);
如果可能,您应该更喜欢从
String
biginger
,从
biginger
String
。由于
biginger
的目的是用于太大而无法用原语表示的数字:

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

// Prefer this instead
BigInteger c = BigInteger.valueOf(e1);
另外,请遵守Java命名约定。变量名应该是camelCase,所以
c
而不是
c


此外,更喜欢有意义的变量名。像
c
d
这样的名称不能帮助任何人理解变量应该代表什么。

算术运算在Java中不适用于对象。然而,在中已经有这样做的方法,例如。而不是做

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

// BigInteger -> String
BigInteger number = ...
String numberText = number.toString();
你会的

q=(x/n)

在Java中,不能对对象执行诸如“*”、“/”、“+”之类的操作数,如果需要这些操作,需要这样做

q = x.divide(n);

不能在这些对象上使用这些运算符。如果您阅读javadocs,您将看到这个类有一些方法来执行您想要执行的操作。您必须使用
biginger
的算术方法,就像您已经使用
pow
一样:
q = x.divide(n);
p=q.multiply(n);
m=x.subtract(p);