gpt4 book ai didi

java - 找到一个数字的真正大幂

转载 作者:搜寻专家 更新时间:2023-11-01 04:04:44 24 4
gpt4 key购买 nike

我正在为学生制作一个小游戏,在一个地方,它要显示27830457+1

的值

如果数字不是那么大,我可以调用 BigInteger 的 pow() 方法。由于数量很大,所以该方法没有用。我怎样才能发现这种数字的巨大力量?请帮忙!

最佳答案

在二进制中它只是 10000...01 和 7830456 个零。

在十进制中,大约有两百万位数字,大约需要 2 兆字节的存储空间。这完全符合具有默认堆大小的 BigInteger 的可行性。

在实践中,它甚至使用 exponentiation by squaring 来快速计算它(尽管规范不保证)。但是,转换为 String 需要一些时间,因为它是线性时间操作。

import java.math.BigInteger;

public class BigPow {
public static void main(String[] args) {
BigInteger result = (new BigInteger("2")).pow(27830457).add(BigInteger.ONE);
System.out.println(result);
}
}

这是一个会慢慢打印出数字的版本:

import java.math.BigInteger;

public class BigPow {
public static void main(String[] args) {
BigInteger result = (new BigInteger("2")).pow(27830457).add(BigInteger.ONE);
BigInteger powten = BigInteger.TEN.pow(2357202);

while(powten.compareTo(BigInteger.TEN) > 0) {
BigInteger digit = result.divide(powten).mod(BigInteger.TEN);
System.out.print(digit);
powten = powten.divide(BigInteger.TEN);
}
}
}

第一位数字是:

27337386390628313557307248857732033008168556429738078791761607160549944954510637855005417718646965163546351365984857761796847950377880836291434244529029919271706271982523405687134334692691344477538489450971091437463160940371624647030064741968436401566711255284353690448270545402444641547030399228243743315193608710148721648879085592699913299745785392609301774185427367430782834290629265859073814466687714408436025809860462926275610087354595992436000187216152954542774991509992374985538879880897902639600451627914923043483436514419544413306391278529303650112773297502090619459167888563274071587848623085880067091968911236296732119252937497152769541579516150659424997041968213122450568364121976474269097910635641227922923398092242409755554115985855831015459204780391470591543281267373716556272259386683864538263922398723602210173800151405332100275913619559563575829498369806957031526077258236305186254269056811134135133350936924294101345294335698866339561918857584229744277901180792029180156485000086528174400878657004645726892816943589969701053158760210512171516969813345080894134663207988962182426459128577282934948790911691329475034324656384238413230485050607666988301932660490870167246016897007835866691705399794247746213819662270451531049826029606671683482160663572103374

WolframAlpha 确认。

关于java - 找到一个数字的真正大幂,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11317875/

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