Java Random Long nextLong(long n)

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

Description

next Long

License

Open Source License

Declaration

public static long nextLong(long n) 

Method Source Code

//package com.java2s;
/**// w w  w. ja va2 s. com
 * Copyright (c) 2014-present Yg0R2. All rights reserved.
 *
 * This library is free software; you can redistribute it and/or modify it under
 * the terms of the GNU Lesser General Public License as published by the Free
 * Software Foundation; either version 2.1 of the License, or (at your option)
 * any later version.
 *
 * This library is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
 * details.
 */

import java.util.Random;

public class Main {
    private static Random _rnd = new Random();

    public static long nextLong(long n) {
        if (n <= 0) {
            throw new IllegalArgumentException("n must be positive");
        }

        long bits, val;

        do {
            bits = _rnd.nextInt();
            val = bits % n;
        } while (bits - val + (n - 1) < 0);

        return val;
    }

    public static int nextInt() {
        return _rnd.nextInt();
    }

    public static int nextInt(int max) {
        if (max <= 0) {
            return 0;
        }

        return _rnd.nextInt(max);
    }

    public static int nextInt(int min, int max) {
        return _rnd.nextInt(max - min) + min;
    }
}

Related

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