Which declaration turns the lower loop into an infinite loop?

Place the declaration for i on line 3 so that the loop becomes an infinite loop.

 public class Puzzel3 { public static void main(String[] args) { // Line 3 while (i == i + 1) { System.out.println(i); } System.out.println("done"); } } 
+6
source share
3 answers
 double i=1/0.0; 

He will turn the cycle into infinite

+9
source

Mathematics says that Infinity + 1 == Infinity , therefore

 // The declaration required double i = Double.POSITIVE_INFINITY; // It infinite loop now... while (i == i + 1) { System.out.println(i); } System.out.println("done"); 
+17
source

The while loop is infinite if the loop condition remains true. Since the expression depends only on i , and i not assigned in the body of the cycle, which is equivalent to the condition of the cycle, which is true at the first estimate.

Consequently, the question arises for which values ​​of which the expression i == i + 1 is true.

Java has the following types:

  • reference types: do not support the + operator, except for strings that become longer by concatenating "1" and therefore cannot remain identical.
  • primitive types:
    • boolean: does not support +
    • integral types: appendix 1 guarantees a change in value even in case of overflow
    • floating point types: float type floating point:
      • positive 0: 0- + 1 is 1, and therefore! = 0
      • negative 0: 0 + + 1 is 1, and therefore! = 0
      • NaN: NaN + 1 is NaN, but NaN! = NaN
      • positive infinity : inf + + 1 - inf +, and therefore == inf +
      • negative infinity : inf + 1 - inf-, and therefore == inf -
      • normal: c + 1 is not an exact calculation. Roughly speaking, 1 is added to c, and the nearest float (or double) to this value is taken as the result. Whether this float (or double) is different from the initial value depends on the density of floating point values ​​around c. Internally, the floating point type is represented by a signed bit and two fixed integers m and e, where the float value is given by s * m * 2 ^ e.
        • Appendix 1 will be an unlikely change in e (and if so, then the result is all the same). Otherwise:
          • if e <= 0, appendix 1 changes m
          • if e == 1, adding 1 can change m, depending on the rounding mode
          • if e> 1, adding 1 will not change m and, therefore, c + 1 == c. Now, for what values ​​will this happen?
            • For float m <2 ^ 24. Therefore, e> 1 if c> = 2 ^ 25 or c <= - (2 ^ 25)
            • For double m <2 ^ 53. Therefore, e> 1 if c> = 2 ^ 54 or c <= - (2 ^ 54)

It should be all cases :-)

+1
source

All Articles