4.1.3.4.3 Mixed Repetition: Combination of for- and while-Loop


A combination of a for- and while-loop can be implemented via a labeled break statement.
breakLabel:
  for (initialization; termination; increment) {
    if(booleanExpression) { 
      break breakLabel;
    }
    statements 
    }
  }
Here, the label breakLabel marks the location where to break to when the booleanExpression returns true. So, when the condition is met, the break causes the execution to break out of the for-loop.

We use the above construction in the following application in which the first odd number n between 3 and 2000 is found for which holds

2n = 2 mod n2

We use the java.math.BigInteger class (available since JDK version 1.1) for computing with arbitrary precision integers. This complicates the commands, but is necessary for computing high powers. The code of the control structure is highlighted and the corresponding commands in pseudo-Java have been added as comments.
import java.math.*;

public class IntegerSearch {
  public static void main(String args[]) {
    BigInteger n;
    BigInteger two = BigInteger.valueOf(2);
    found:                                            // found:
      for (n = BigInteger.valueOf(3);                 //   for (n=3;
           n.compareTo(BigInteger.valueOf(2000))==-1; //        n<2000;
           n=n.add(two)) {                            //        n = n+2) {
 	if (two.modPow(n,n.pow(2)).equals(two)) {     //     if (2^n mod n^2 = 2) 
           break found;                               //       break found;  
        }                                             //   }
      }
    if ( n.compareTo(BigInteger.valueOf(2000))==1) {  // n>2000
      System.out.println("no integer with requested property found");
    }
    else {
      System.out.println("n = " + n.intValue());
    }
  }
}
When you run this application, you will find that n=1093.