Java中的大数处理 —— BigInteger

Java中的BigInteger - 260401

  • [BigInteger - 大数类](#BigInteger - 大数类)
  • 基础例题

BigInteger - 大数类

  • 前置:import java.Math.BigInteger;
  • 性质:是不可变类,每次作运算之后都会在计算机里创建一个新对象
  • 构造:BigInteger a = new BigInteger("123");从字符串创建
    BigInteger a = BigInteger.valueOf(123L);从long数字创建
  • 常用值表示:BigInteger.ZERO BigInteger.ONE BigInteger.TWO
  • 常用函数:
    a.add(b) :加法
    a.subtract(b):减法
    a.multiply(b):乘法
    a.devide(b):除法
    a.remainder(b):取余
    a.pow():幂运算
    a.gcd(b):最大公约数
    a.compareTo(b):当 前>后 时返回1,反之返回-1,相等返回0
    a.toString():变成字符串

基础例题

洛谷 P1009

  • 代码实现
java 复制代码
import java.util.*;
import java.math.BigInteger;

public class Main{
    public static void main(String [] args){
        Scanner input = new Scanner(System.in);
        long n = input.nextLong();
        BigInteger sum = BigInteger.ZERO;
        BigInteger pre = BigInteger.ONE;
        for(int i=1;i<=n;i++){
            pre = pre.multiply(BigInteger.valueOf(i));
            sum = sum.add(pre);
        }
        System.out.print(sum.toString());
    }
}

洛谷 P1303

  • 代码实现
java 复制代码
import java.util.*;
import java.math.BigInteger;
public class Main{
    public static void main(String [] args){
        Scanner input = new Scanner (System.in);
        String a = input.nextLine();
        String b = input.nextLine();
        BigInteger aa = new BigInteger(a);
        BigInteger bb = new BigInteger(b);
        BigInteger ans = aa.multiply(bb);
        System.out.print(ans.toString());
    }
}
相关推荐
武昌库里写JAVA2 小时前
SpringBoot+Vue 项目介绍
java·javascript·git·sql·ai
学长毕设3 小时前
基于SpringBoot的儿童慈善捐赠管理系统-附源码
java·spring boot·后端
慧一居士3 小时前
@RestControllerAdvice 的注解作用和使用
java
ComPDFKit4 小时前
RAG 回答只显示 PDF 文件名?用 Python 保留引用页码
开发语言·python·pdf·rag
FRing034 小时前
vue3干货总结2(vue3生命周期、父子通信、模版引用、provide和inject)
开发语言·前端·vue.js·vue3
学长毕设4 小时前
基于SpringBoot非遗文化展示与传播平台设计与实现-附源码
java·spring boot·后端
金銀銅鐵6 小时前
用 Swing 重做操作数栈演示
java·jvm·后端
琳少_6 小时前
java程序开发笔记
java·开发语言·数据库·笔记
七夜zippoe6 小时前
Agent 告警设计:分级告警、智能降噪与值班排班
开发语言·ai·agent·告警·智能降噪·值班排班
叼烟扛炮8 小时前
[LangChain] 学习笔记(15):为什么你的重试没用——429、抖动、fallback 与熔断
java·服务器·前端