Java解决大数、高精度问题

做了几个大数,高精度的题目,发现用C/C++实现太繁琐,了解到可以用Java里现成的 BigInteger 类和 BigDecimal 类高效解题,只需要调用其中的方法就行了。文末附有官方文档网址,本文只列出一些常用的。

BigInteger:

构造方法

BigInteger BigInteger(String val)
把字符串型的大数转换为大数对象
BigInteger BigInteger(String val, int radix)
同上,并可以设定基数

普通方法

BigInteger abs()
返回绝对值(返回BigInteger型)
BigInteger add(BigInteger val)
返回本身+val的值(返回BigInteger型)
BigInteger substract(BigInteger val)
返回本身-val的值(返回BigInteger型)
BigInteger multiply(BigInteger val)
返回本身*val的值(返回BigInteger型)
BigInteger divide(BigInteger val)
返回本身/val的值(返回BigInteger型)
double doubleValue()
将大数转换为double类型(返回double类型)
boolean equals(Object x)
比较是否相等(返回boolean值)
int intValue()
将大数转换为int型(返回int型)
BigInteger max(BigInteger val)
比较本身 和 val 谁大,返回大的值(返回BigInteger型)
BigInteger min(BigInteger val)
比较本身 和 val 谁小,返回小的值(返回BigInteger型)
BigInteger mod(BigInteger m)
返回 (本身 % m)的值(返回BigInteger型)
BigInteger pow(int exponent)
返回(本身^ exponent)的值(返回BigInteger型)
String toString()
返回十进制字符串
String toString(int radix)
返回字符串,可设置基数

常量

static BigInteger ONE
static BigInteger TEN
static BigInteger ZERO

用法

import java.math.BigInteger;
import java.util.Scanner;
import java.util.*;
 
public class Main {
    
    
 
    public static void main(String[] args) {
    
    
        Scanner scanner = new Scanner(System.in);
        while(scanner.hasNext()){
    
    
            BigInteger a = scanner.nextBigInteger();
            BigInteger b = scanner.nextBigInteger();
            String s = a.add(b).toString(); //加法、转换为字符串
            System.out.println(s); 
            System.out.println(BigInteger.ONE); //常数
        }
 
    }

}

BigDecimal

构造方法

BigDecimal(BigInteger val)
BigDecimal(double val)
BigDecimal(int val)
BigDecimal(String val)

普通方法

BigDecimal setScale(int newScale)
设置精度
BigDecimal abs()
绝对值,精度为本身的精度
BigDecimal abs(MathContext mc)
同上,带舍入设置
BigDecimal add(BigDecimal augend)
加法,精度为 max(this.scale(), augend.scale())的精度.
BigDecimal add(BigDecimal augend, MathContext mc)
同上,带精度设置
BigDecimal plus()
加法,精度为本身精度
BigDecimal plus(MathContext mc)
带舍入设置的加法
BigDecimal divide(BigDecimal divisor)
除法
BigDecimal negate()
减法,本身精度
BigDecimal negate(MathContext mc)
减法,带舍入设置
BigDecimal multiply(BigDecimal multiplicand)
除法,精度为 (this.scale() + multiplicand.scale())的精度.
BigDecimal multiply(BigDecimal multiplicand, MathContext mc)
除法
BigDecimal pow(int n)
幂运算
BigDecimal pow(int n, MathContext mc)
幂运算
String toString()
转换为字符串

常量

static BigDecimal TEN
static BigDecimal ZERO

这里是官方文档的网址,大家感兴趣可以点进去查看所有的方法以及它们的详细用法
在这里插入图片描述
点击导航栏上BigInteger右侧出现其所有方法和解释。
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_45218241/article/details/112674504