-2

I have the following code

public static void main(String[] args) {
    BigInteger iter = BigInteger.valueOf(140);
    BigInteger y = BigInteger.valueOf(1114112);
    BigInteger sum = BigInteger.valueOf(0);
    while(iter.intValue() != 0) {
        BigInteger z = BigInteger.valueOf((y.pow(iter.intValue())).longValue());
        sum = sum.add(z);
        iter = iter.subtract(BigInteger.valueOf(1));
        System.out.println("Itereration: " + (140 - iter.longValue()));
        System.out.println("Y: " + y.longValue());
        System.out.println("Z: " + z.longValue());
        System.out.println("Sum: " + sum.longValue());
   }
}

However, the output is this (only last 3 iterations)

Iteration: 137
Y: 1114112
Z: 0
Sum: 0
Iteration: 138
Y: 1114112
Z: 1382886560579452928
Sum: 1382886560579452928
Iteration: 139
Y: 1114112
Z: 1241245548544
Sum: 1382887801825001472
Iteration: 140
Y: 1114112
Z: 1114112
Sum: 1382887801826115584

The rest of iterations 1-136 are the same as iteration 137

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
Andrew Smith
  • 37
  • 1
  • 10

1 Answers1

4

The .longValue() calls do completely wrong things on BigInteger values this large. If you tried using .longValueExact() instead, you'd see that it throws an exception because the values are out of range for a long. But if you don't do the unnecessary .longValue() calls , the code works:

BigInteger iter = BigInteger.valueOf(140);
BigInteger y = BigInteger.valueOf(1114112);
BigInteger sum = BigInteger.valueOf(0);
while(iter.intValue() != 0) {
    BigInteger z = y.pow(iter.intValue();
    sum = sum.add(z);
    iter = iter.subtract(BigInteger.valueOf(1));
    System.out.println("Itereration: " + (140 - iter.longValue()));
    System.out.println("Y: " + y);
    System.out.println("Z: " + z);
    System.out.println("Sum: " + sum);
}

And as @RC. has suggested in the comment, you could make iter a simple int, which simplifies the code further:

int iter = 140;
BigInteger y = BigInteger.valueOf(1114112);
BigInteger sum = BigInteger.valueOf(0);
while(iter != 0) {
    BigInteger z = y.pow(iter);
    sum = sum.add(z);
    iter--;
    System.out.println("Itereration: " + (140 - iter));
    System.out.println("Y: " + y);
    System.out.println("Z: " + z);
    System.out.println("Sum: " + sum);
}
zsmb13
  • 85,752
  • 11
  • 221
  • 226