java - 什么是 java.util.Random.next(n) 的 O(n)

标签 java time-complexity

我想知道 java.util.Random.next(n) 是否与 n 成线性关系还是一个常数?有人可以帮我解决这个问题,或者告诉我如何确定复杂性吗?

最佳答案

来自文档:

Random.nextInt(n) uses Random.next() less than twice on average- it uses it once, and if the value obtained is above the highest multiple of n below MAX_INT it tries again, otherwise is returns the value modulo n (this prevents the values above the highest multiple of n below MAX_INT skewing the distribution), so returning a value which is uniformly distributed in the range 0 to n-1.

根据文档,java.util.Random.next 实现如下

synchronized protected int next(int bits) {
   seed = (seed * 0x5DEECE66DL + 0xBL) & ((1L << 48) - 1);
   return (int)(seed >>> (48 - bits));
 }

所以复杂度是O(1)

旁注:-

您可以使用多种工具来衡量微基准的复杂性。您可以在 here 上找到一个列表.但是,如果运行时复杂性对您很重要,您可以使用 Fast Mersenne Twister .(这是一个外部库,用于衡量运行时的复杂性,因为 Java 的随机数生成器非常快,但在统计上很糟糕)

关于java - 什么是 java.util.Random.next(n) 的 O(n),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20764300/

相关文章:

java - Android webview.postUrl(url,Encodingutils.getBytes(postData ,"BASE64")) 从 postdata 字符串中删除 "+"

javascript - 链接多个 Array.prototype.*function* 的性能问题是什么?

algorithm - Sieve of Eratosthenes 算法的时间复杂度

algorithm - 算法的时间复杂度

Java:线程主java.lang.NoClassDefFoundError中的异常

java - 如何通过java邮件将ZipInputStream作为附件发送?

java - PrintWriter 创建文件但不写入

java - 检查整数是否有重复数字。没有字符串方法或数组

python - 在 python 中获取子字符串是 O(n) 操作吗?

python - python 中文本分析器代码的时间复杂度