【问题标题】:Setting the length of random BigInteger in java在java中设置随机BigInteger的长度
【发布时间】:2014-03-02 08:00:57
【问题描述】:

假设我从用户那里输入“8”,我应该能够生成一个长度为 8 位的随机 BigInteger。假设我输入“20”,我应该能够生成一个长度为 20 位的随机 BigInteger。我怎样才能做到这一点?

我有以下从示例中引用的代码。

int SIZE = 512;
p = new BigInteger(SIZE, 15, new Random());
q = new BigInteger(SIZE, 15, new Random());

谁能告诉我这些论点是什么意思?或者您能建议一种更简单的方法来实现这一点吗?

【问题讨论】:

标签: java biginteger


【解决方案1】:

BigInteger(int bitLength, int确定性, 随机 rnd)

构造一个随机生成的正 BigInteger,它可能是素数,具有指定的 bitLength。 建议优先使用 probablePrime 方法而不是此构造函数,除非迫切需要指定确定性。

参数:

bitLength - 返回的 BigInteger 的 bitLength。

确定性 - 衡量调用者愿意容忍的不确定性。新的 BigInteger 表示素数的概率将超过 (1 - 1/2certainty)。这个构造函数的执行时间与这个参数的值成正比。

rnd - 用于选择要测试素性的候选者的随机位源。

直接取自 Oracles 网站,希望这就是您想要的。

【讨论】:

    【解决方案2】:

    整数解

    public static int randInt(int min, int max) {
    
        // Usually this can be a field rather than a method variable
        Random rand = new Random();
    
        // nextInt is normally exclusive of the top value,
        // so add 1 to make it inclusive
        int randomNum = rand.nextInt((max - min) + 1) + min;
    
        return randomNum;
    }
    

    所以如果你需要8位随机数

    调用此函数,范围为 8 位 i.e 最小的 8 位 # 和最大的 8 位数字。

    例如

    randInt(10000000, 99999999)

    来源:范围随机数的代码取自这里

    How do I generate random integers within a specific range in Java?

    您也可以查看nextLong()。这些是统一生成的随机数

    http://docs.oracle.com/javase/6/docs/api/java/util/Random.html#nextLong()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-06-04
      • 2015-02-10
      • 2011-07-20
      • 2015-06-12
      • 1970-01-01
      • 2017-12-31
      • 2017-11-19
      相关资源
      最近更新 更多