code: public static long nextLong(long n) {
          // error checking and 2^x checking removed for simplicity.
          long bits, val;
          do {
              bits = (RND.nextLong() << 1) >>> 1;
              val = bits % n;
          } while (bits-val+(n-1) < 0L);
          return val;
      }
docs: http://stackoverflow.com/a/2546186/255231