gpt4 book ai didi

java - 如何获得 BigInteger 中的第 n 个数字?

转载 作者:行者123 更新时间:2023-11-29 06:48:34 25 4
gpt4 key购买 nike

我正在研究一些 BigInteger 问题,其中每个数字的大小是 2^100。我需要该数字的第 n 个数字我该怎么做?

使用 toString() 我将 BigInteger 转换为 String 然后得到那个数字但是String的大小最多只能是Int的最大值?

int get(BigInteger b,BigInteger n)
{
return Character.getNumericValue(b.toString().charAt(n.intValue()));
}

因此此代码仅在 BigInteger 小于 Int 最大值时才有效。但在我的情况下,经过某些迭代后,可能是我的 BigInteger 越过限制的机会,那么如何才能获得该 BigInteger 中的第 n 个 BigInteger 数字?

最佳答案

您可以尝试使用 BigInteger#toString 并使用 charAt(int i) ...我为您编写了一个测试:

@Test
void testBigInt(){
BigInteger bi = new BigInteger("123456789012345678901234567890");
System.out.println(bi.toString().charAt(25));
}

运行时,我打印了一个“6”……这似乎是对的

当您在“charAt()”中使用的位置整数太大(大于 maxIntValue)时,您将需要对原始 BigInteger 进行取模和除法

你可以“截掉”第一个和最后一个数字,只看你感兴趣的范围

    @Test
public void testIt() {
BigInteger bi = new BigInteger("1234567890");
BigInteger resDiv = bi.divide(new BigInteger("100000"));
System.out.println(resDiv.toString());
BigInteger resMod = resDiv.mod(new BigInteger("1234"));

System.out.println(resMod.toString());

}

关于java - 如何获得 BigInteger 中的第 n 个数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57442219/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com