-1

The code fragment

int x = < an integer value >;
System.out.println(x*x);

displays -131071. Which of the following is a possible value of x?

Apparently the answer is 2^16 - 1.

I don't even know how that was an answer choice. How am I supposed to solve this problem without a calculator?


The statement

System.out.println(Integer.MAX_VALUE);

prints 2147483647, which is equal to 2^31 - 1. What does the following statement print?

System.out.println(Integer.MAX_VALUE + 2);

The answer was -2137483546. I'm confused how, shouldn't it cause an ArithmeticException since we're going out of bounds?

I'm not asking these questions for you to do them for me? If you could give me the reasoning and not just the answers (which I already have)? I'm just confused about manipulating with ints near their max values.

Asker123
  • 350
  • 1
  • 3
  • 15

1 Answers1

1

I'd start by writing -131071 in a more useful form: 0xfffe0001

Now just solve x * x == 0xfffe0001. Clearly x is odd, otherwise its square could never be odd. That argument can go further: modulo 216 we get x * x = 1, so x is either 1 or -1 modulo 216 since those are the only square roots of 1.

So there are only two choices for the lower 16 bits, what about the upper 16?

First let's try 0xffff (aka -1 modulo 216) for the lower 16 bits. That (ie upper 16 bits are zero) immediately turns out to work but "by calculation" a boring reason. Here's a nicer reason: the original number was 232-217+1 (easily visible from its hexadecimal representation), which factors into (216-1)2, just do the usual "reverse square" thing, so 232 is a2, -217 = 2ab and 1 = b2.

But that's just one possibility, there are more:

  • 0x0000ffff = 216-1
  • 0x8000ffff = 231+216-1 (the 231 cancels out if you square it)

Remember how the bottom 16 bits could be 1? That also gives 2 possibilities:

  • 0x7fff0001
  • 0xffff0001

shouldn't it cause an ArithmeticException since we're going out of bounds?

Not with standard wrapping arithmetic, but see Math.multiplyExact and friends. Of the normal operators, / and % can throw, the others are thankfully safe.

harold
  • 61,398
  • 6
  • 86
  • 164