Java大数类练习

该博客讲述了如何利用BigInteger类处理大整数,避免超时,来计算[l,r]区间内dd的倍数的个数。通过公式r/d-l/d求解,给出了一段Java代码示例,演示了如何进行大数运算来解决这个问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一天蒜头君在想,[l,r][l,r] 之间有多少个数字是 dd 的倍数呢?

但是区间 [l,r][l,r] 是 dd 的倍数的数字太多,于是聪明的蒜头君便找到了你。

当 l = 1032,r = 12302135942453,d = 234,d 的倍数有多少个呢?

r的数字很大,用long也放不下,所以用大数类来求解,但是用大数暴力求余会超时,我们可以用r/d-l/d来求。

add(BigInteger value)
返回其值为 (this + val) 的 BigInteger,超大整数加法运算
subtract(BigInteger value)
返回其值为 (this - val) 的 BigInteger,超大整数减法运算
multiply(BigInteger value)
返回其值为 (this * val) 的 BigInteger,超大整数乘法运算
divide(BigInteger value)
返回其值为 (this / val) 的 BigInteger,超大整数除法运算,除不尽取整数部分

取余的话:
用mod或者divideAndRemainder(这返回的是一个Bigiinteger数组,[0]是整除结果,[1]是取余结果)

BigInteger bigInteger = new BigInteger("45615146541561");
BigInteger bigInteger2 = new BigInteger("6541315");
BigInteger[] resBigIntegers =bigInteger.divideAndRemainder(bigInteger2);


import java.util.Scanner;

import java.math.BigInteger;

public class t1 {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);

        BigInteger r=new BigInteger("12302135942453");

        BigInteger d = BigInteger.valueOf(234);

        BigInteger l=BigInteger.valueOf(1032);

        BigInteger ans=BigInteger.ZERO;//初始为0

        BigInteger r1=r.divide(d);
        BigInteger l1=l.divide(d);

        System.out.println(r1.subtract(l1));

        in.close();
        System.out.println();
    }

}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值