Java Random Long nextLong(Random rng, long n)

Here you can find the source of nextLong(Random rng, long n)

Description

Returns a random long

License

Apache License

Parameter

Parameter Description
rng the Random object to generate the result;
n The long value of the roof.

Return

The random long value between 0 and n.

Declaration

public static long nextLong(Random rng, long n) 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.util.Random;

public class Main {
    /**/*from  w  w w  .j  av  a2 s  . c  om*/
     * Returns a random long
     * 
     * @param rng
     *            the {@link Random} object to generate the result;
     * @param n
     *            The long value of the roof.
     * @return The random long value between 0 and n.
     */
    public static long nextLong(Random rng, long n) {
        if (n <= 0)
            throw new IllegalArgumentException("n must be positive");

        if ((n & -n) == n) // i.e., n is a power of 2
            return (long) ((n * (long) rng.nextInt(31)) >> 31);

        long bits, val;
        do {
            bits = (rng.nextLong() << 1) >>> 1;
            val = bits % n;
        } while (bits - val + (n - 1) < 0L);
        return val;
    }
}

Related

  1. nextLong()
  2. nextLong(long n)
  3. nextLong(long n)
  4. nextLong(long RangeBottom, long rangeTop)
  5. nextLong(Random random, final long lower, final long upper)
  6. nextLong(Random rng, long n)
  7. nextLongId()
  8. randLong()
  9. randLong(long minimum, long maximum)