Java高精度BigInteger类

 当我们想求100的阶乘的时候,long类型也会出现溢出,我们可以用到java.math包下的BigInteger类来实现高精度运算。可以认为一个BigInteger对象就是一个数。
 主要是对高精度的数进行加减乘除余

一、构造方法

 主要用到的是传入字符串创建BigInteger对象

  •  BigInteger a = new BigInteger(String num); //通过num创建对象
  •  BigInteger b = new BigInteger(String num,int n)通过num的n进制数创建对象

二、常用方法

1、加法 add()

 用到的是该类的add方法,传入一个BigInteger对象,返回也是一个BigInteger对象
 代码示例:

import java.math.BigInteger;
public class Test {
    public static void main(String[] args) {
        BigInteger a = new BigInteger("9999999999999999999");
        BigInteger b = new BigInteger("9999999999999999999");
        System.out.println(a.add(b)); //输出19999999999999999998

    }
}

2、减法subtract()

 代码示例:


import java.math.BigInteger;
public class Test {
    public static void main(String[] args) {
        BigInteger a = new BigInteger("999999999999999999999999999999999");
        BigInteger b = new BigInteger("9999999999999999999");
        System.out.println(a.subtract(b)); //输出1000000000000009999999999999999998

    }
}

3、乘法 multiply()

 代码示例:

import java.math.BigInteger;
public class Test {
    public static void main(String[] args) {
        BigInteger a = new BigInteger("99999999");
        BigInteger b = new BigInteger("99999999");
        System.out.println(a.multiply(b)); //输出9999999800000001

    }
}

4、除法 divide()

  mod()方法取模 。永远为正
 remainder()方法取余。可能会出现负数。

public class Test {
    public static void main(String[] args) {
        BigInteger a = new BigInteger("4");
        BigInteger b = new BigInteger("2");
        System.out.println("输出为:"+a.divide(b)); //输出2
        System.out.println("余数为:"+a.remainder(b)); // 输出0
    }
}

5、求最大公约数gcd()

 代码示例:


import java.math.BigInteger;
public class Test {
    public static void main(String[] args) {
        BigInteger a = new BigInteger("48");
        BigInteger b = new BigInteger("8");
        System.out.println(a.gcd(b)); //输出8
    }
}

6、转换成任意进制的字符串

 使用的方法是toString(int n); 传入的n为要转换的n进制
 代码示例:


import java.math.BigInteger;
public class Test {
    public static void main(String[] args) {
        BigInteger a = new BigInteger("8");
        System.out.println(a.toString(2)); //输出1000
    }
}

三、缺点

 BigInteger类每一次创建对象太消耗时间,可能编译超时,最好不要循环创建对象。高精度的话也只爆long的时候在用。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

tanxinji

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值