anastaciu
anastaciu

Reputation: 23802

Refactoring function that uses long argument to use BigInteger

I need to convert some methods which use long arguments, it turns out 64 bit longs 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.

Upvotes: 1

Views: 77

Answers (1)

Onur Başt&#252;rk
Onur Başt&#252;rk

Reputation: 735

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);

Upvotes: 3

Related Questions