在Java中为大整数生成从1到n-1的随机数

在Java中为大整数生成从1到n-1的随机数,java,biginteger,Java,Biginteger,可能重复: 我在JAVA中使用BigInteger类,我想生成从1到x-1的随机数。我不知道该怎么做 我不能使用nextInt() 我知道如果我搜索我可能会找到一些有用的解决方案,但我的时间太短了。(截止日期前2小时) 提前感谢。只需使用随机获取的 Random rnd = new Random(); BigInteger i = new BigInteger(maxNumOfBits, rnd); 如果您想要介于0和某个数字之间,您可以生成与该数字相同的位数,并生成随机数,直到得到一个小于

可能重复:

我在JAVA中使用BigInteger类,我想生成从
1到x-1的随机数。我不知道该怎么做

我不能使用
nextInt()

我知道如果我搜索我可能会找到一些有用的解决方案,但我的时间太短了。(截止日期前2小时)

提前感谢。

只需使用随机获取的

Random rnd = new Random();
BigInteger i = new BigInteger(maxNumOfBits, rnd);
如果您想要介于0和某个数字之间,您可以生成与该数字相同的位数,并生成随机数,直到得到一个小于该数字的位数

(代码未测试)

愿这管用吗

    public static void main(String[] args) {
        BigInteger bigInteger = new BigInteger("9349988899999");
        BigInteger bigInteger1 = bigInteger.subtract(new BigInteger("1"));
        System.out.println(randomBigInteger(bigInteger1));
    }

    public static BigInteger randomBigInteger(BigInteger n) {
        Random rnd = new Random();
        int maxNumBitLength = n.bitLength();
        BigInteger aRandomBigInt;
        do {
            aRandomBigInt = new BigInteger(maxNumBitLength, rnd);
            // compare random number lessthan ginven number
        } while (aRandomBigInt.compareTo(n) > 0); 
        return aRandomBigInt;
    }

我不想输入最大位数。我想从1生成n-1。例如,我有一个93499999,我想找到一个介于1到9349999999-1之间的随机数。如何在大整数中执行此操作?如果大整数的最后一个数字很小,则计算成本非常高
    public static void main(String[] args) {
        BigInteger bigInteger = new BigInteger("9349988899999");
        BigInteger bigInteger1 = bigInteger.subtract(new BigInteger("1"));
        System.out.println(randomBigInteger(bigInteger1));
    }

    public static BigInteger randomBigInteger(BigInteger n) {
        Random rnd = new Random();
        int maxNumBitLength = n.bitLength();
        BigInteger aRandomBigInt;
        do {
            aRandomBigInt = new BigInteger(maxNumBitLength, rnd);
            // compare random number lessthan ginven number
        } while (aRandomBigInt.compareTo(n) > 0); 
        return aRandomBigInt;
    }