java.bigInteger valueOf 如何工作?
我正在制作一个涉及大数字的项目,没有 BigInteger、BigDecimal 等。我已经成功完成了所有基础知识,但现在我需要添加计算阶乘的能力。我的 BigNumber 将数据存储为 int[] 。
这是一个使用 BigInteger 的示例解决方案,但如果没有我的号码的实际值,我就无法使用它。
BigInteger n = BigInteger.ONE;
for (int i=1; i<=20; i++) {
n = n.multiply(BigInteger.valueOf(i));
System.out.println(i + "! = " + n);
}
那么如何计算价值呢?将整数从最后到第一个相加,将十乘以 10,将百乘以 100,依此类推,并将其存储为 long ?
大整数的来源: http://developer.classpath.org/doc/java/math/ BigInteger-source.html
I'm making a project concerned big numbers without BigInteger, BigDecimal etc. I've managed to do all the basics but now I need to add ability to count factorials. My BigNumber stores data as int[] .
Here's a sample solution with BigInteger but I can't use it without having the actual value of my number.
BigInteger n = BigInteger.ONE;
for (int i=1; i<=20; i++) {
n = n.multiply(BigInteger.valueOf(i));
System.out.println(i + "! = " + n);
}
So how to count the value ? Add ints from last to first, multiplying tens by 10, hundreds by 100 and so on and so on and store it as long ?
Source of BigInteger :
http://developer.classpath.org/doc/java/math/BigInteger-source.html
我不认为将其存储为
long
是您想要的。如果该值大于Long.MAX_VALUE
会发生什么?如果
n
是BigInteger
,则n.multiply(BigInteger.valueOf(i));
应返回BigInteger
> 对象。multiply
方法应该知道如何对两个BigInteger
对象进行乘法运算,而不需要将它们转换为long
。一种方法是使用我们在小学学到的乘法进位算法循环遍历每个数字。如果您的值是天文数字,这将非常慢,但它确实具有易于理解和实现的好处。I don't think storing it as a
long
is what you intend. What would happen if the value gets bigger thanLong.MAX_VALUE
?If
n
is aBigInteger
, thenn.multiply(BigInteger.valueOf(i));
should return aBigInteger
object. Themultiply
method should know how to do multiplication with twoBigInteger
objects without needing to convert them tolong
. One way of doing that is to loop through each digit using the multiply-and-carry algorithm that we learned in grade school. This will be pretty slow if your values are astronomical, but it does have the benefit of being easy to understand and implement.