至于 N,它可以大到 179。
例如,我能够为 n 最多 32 位执行此操作:
new Random().nextInt(2^n-1)+1
Run Code Online (Sandbox Code Playgroud)
nextLong() 是不可能的,因为我不能向它传递一个值,它只能生成一个高达 48 位的随机值。
使用 BigInteger 创建一个随机数。如果它恰好为零,请重试。
public static BigInteger randomForBitsNonZero(int numBits, Random r) {
BigInteger candidate = new BigInteger(numBits, r);
while(candidate.equals(BigInteger.ZERO)) {
candidate = new BigInteger(numBits, r);
}
return candidate;
}
Run Code Online (Sandbox Code Playgroud)
这将随机分配比特数。if 语句不太可能触发一个显着的高,numBits但保护有利于竞争力,因为numBits有时你可能会经常抛出0 的低。