[英]What is the most effective way to create BigInteger instance from int value?
[英]Effective way to loop through BigInteger
我正在像這樣遍歷BigInteger
:
BigInteger i = new BigInteger(Long.MAX_VALUE + "");
BigInteger end = i.add(new BigInteger("10"));
// Display results
for (i = new BigInteger(Long.MAX_VALUE + "");
i.compareTo(end) <= 0;
i = i.add(new BigInteger("1"))) {
System.out.println(i.multiply(i));
}
而且由於占用內存,這太昂貴了,因為在每個循環中都創建了新的BigInteger
對象,而不是僅使用++
來增加值。
有沒有一種方法可以增加值而不是每次都創建新對象?
好了,您可以使用BigInteger.valueOf(long)
避免解析String
。 您可以使用BigInteger.ONE
而不是每次迭代都重新創建1
。 喜歡,
BigInteger end = BigInteger.valueOf(Long.MAX_VALUE).add(BigInteger.valueOf(10));
// Display results
for (BigInteger i = BigInteger.valueOf(Long.MAX_VALUE); i.compareTo(end) <= 0;
i = i.add(BigInteger.ONE)) {
System.out.println(i.multiply(i));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.