code: public static BigInteger generateRandomIntegerLessThan(BigInteger num) {
          BigInteger r = null;
          while (r == null || r.compareTo(num) >= 0) {
              r = new BigInteger(num.bitLength(), RANDOM);
          }
          return r;
      }
docs: Generate random number guaranteed to be less than the number specified.
  
  @param num upper bound of the generated random number
  @return random number guaranteed to be less than the specified number