Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Starting from <strong>Java 7</strong> (or Android API Level 21 = 5.0+) you could directly use <code>ThreadLocalRandom.current().nextLong(n)</code> (for 0 ≤ x &lt; n) and <code>ThreadLocalRandom.current().nextLong(m, n)</code> (for m ≤ x &lt; n). See <a href="https://stackoverflow.com/a/31682930/224671">@Alex</a>'s answer for detail.</p> <hr> <p>If you are stuck with <strong>Java 6</strong> (or Android 4.x) you need to use an external library (e.g. <code>org.apache.commons.math3.random.RandomDataGenerator.getRandomGenerator().nextLong(0, n-1)</code>, see <a href="https://stackoverflow.com/a/11747812/224671">@mawaldne</a>'s answer), or implement your own <code>nextLong(n)</code>.</p> <p>According to <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/Random.html" rel="noreferrer">http://java.sun.com/j2se/1.5.0/docs/api/java/util/Random.html</a> <code>nextInt</code> is implemented as</p> <pre><code> public int nextInt(int n) { if (n&lt;=0) throw new IllegalArgumentException("n must be positive"); if ((n &amp; -n) == n) // i.e., n is a power of 2 return (int)((n * (long)next(31)) &gt;&gt; 31); int bits, val; do { bits = next(31); val = bits % n; } while(bits - val + (n-1) &lt; 0); return val; } </code></pre> <p>So we may modify this to perform <code>nextLong</code>:</p> <pre><code>long nextLong(Random rng, long n) { // error checking and 2^x checking removed for simplicity. long bits, val; do { bits = (rng.nextLong() &lt;&lt; 1) &gt;&gt;&gt; 1; val = bits % n; } while (bits-val+(n-1) &lt; 0L); return val; } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload