英文:
Refactoring function that uses long argument to use BigInteger
问题
以下是翻译好的部分:
原始代码:
static void ConditionalSum_1(long n) {
long soma = 0;
int i = 1;
while (i < n) {
for (int j = 0; j < i; j++) {
soma++;
}
i *= 2;
}
System.out.println("Soma C1 = " + soma);
}
转换后的代码:
static void ConditionalSum_2(BigInteger n) {
BigInteger soma = BigInteger.ZERO;
BigInteger i = BigInteger.ONE;
while (i.compareTo(n) < 0) {
for (BigInteger j = BigInteger.ZERO; j.compareTo(i) < 0; j = j.add(BigInteger.ONE)) {
soma = soma.add(BigInteger.ONE);
}
i = i.multiply(BigInteger.TWO);
}
System.out.println("Soma C2 = " + soma);
}
函数调用部分:
public static void main(String[] args) {
ConditionalSum_1(999999L); //正常工作
ConditionalSum_2(new BigInteger("999999")); //无限循环
}
由于某些我无法确定的原因,ConditionalSum_2
函数似乎无法正常工作,没有抛出异常,变量似乎没有改变,因此例程进入了无限循环。我对 Java 还有点陌生,所以我确定我在这里漏掉了一些基本的东西。帮助将不胜感激。
英文:
I need to convert some methods which use long
arguments, it turns out 64 bit long
s are too small for what I need, what I did was to convert these so they can take BigInteger
.
Here is reproducible example:
Original:
static void ConditionalSum_1(long n) {
long soma = 0;
int i = 1;
while (i < n) {
for (int j = 0; j < i; j++) {
soma++;
}
i *= 2;
}
System.out.println("Soma C1 = " + soma);
}
Converted:
static void ConditionalSum_2(BigInteger n) {
BigInteger soma = BigInteger.ZERO;
BigInteger i = BigInteger.ONE;
while (i.compareTo(n) < 0) {
for (BigInteger j = BigInteger.ZERO; j.compareTo(i) < 0; j.add(BigInteger.ONE)) {
soma.add(BigInteger.ONE);
}
i.multiply(BigInteger.TWO);
}
System.out.println("Soma C2 = " + soma);
}
Function calls:
public static void main(String[] args) {
ConditionalSum_1(999999L); //works fine
ConditionalSum_2(new BigInteger("999999")); //infinite loop
}
For reasons I can't pinpoint the ConditionalSum_2
function doesn't seem to be working, there are no exceptions thrown, the variables don't seem to be changing and as a consequence the routine enters an infinite loop.
I'm kind of new to Java so I'm sure I'm missing something basic here. Help would be apreciated.
答案1
得分: 3
当您将一个BigInteger与另一个BigInteger相加时,和将作为结果返回。因此,您必须将返回值再次赋值给适当的变量。
for (BigInteger j = BigInteger.ZERO; j.compareTo(i) < 0; j = j.add(BigInteger.ONE))
{
soma = soma.add(BigInteger.ONE);
}
i = i.multiply(BigInteger.TWO);
英文:
When you sum a BigInteger with another BigInteger the sum will be returned as the result. So you have to assign the return value to the appropriate variable again.
for (BigInteger j = BigInteger.ZERO; j.compareTo(i) < 0; j = j.add(BigInteger.ONE))
{
soma = soma.add(BigInteger.ONE);
}
i = i.multiply(BigInteger.TWO);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论