为什么乘法比求平方根快很多倍?

2023-12-07

我对以下算法有几个问题来判断一个数字是否是素数,我也知道随着埃拉托斯特尼筛法可以得到更快的响应。

  1. 为什么计算速度更快i i * sqrt (n)次。比sqrt (n)就一次 ?
  2. Why Math.sqrt()比我的快sqrt()方法 ?
  3. 这些算法的复杂度分别是O(n)、O(sqrt(n))、O(n log(n))?

    public class Main {
    
    public static void main(String[] args) {
    
    // Case 1 comparing Algorithms
    long startTime = System.currentTimeMillis(); // Start Time
    for (int i = 2; i <= 100000; ++i) {
        if (isPrime1(i))
            continue;
    }
    long stopTime = System.currentTimeMillis(); // End Time
    System.out.printf("Duracion: %4d ms. while (i*i <= N) Algorithm\n",
            stopTime - startTime);
    
    // Case 2 comparing Algorithms
    startTime = System.currentTimeMillis();
    for (int i = 2; i <= 100000; ++i) {
        if (isPrime2(i))
            continue;
    }
    stopTime = System.currentTimeMillis();
    System.out.printf("Duracion: %4d ms. while (i <= sqrt(N)) Algorithm\n",
            stopTime - startTime);
    
    // Case 3 comparing Algorithms
    startTime = System.currentTimeMillis();
    for (int i = 2; i <= 100000; ++i) {
        if (isPrime3(i))
            continue;
    }
    stopTime = System.currentTimeMillis();
    System.out.printf(
              "Duracion: %4d ms. s = sqrt(N) while (i <= s) Algorithm\n",
              stopTime - startTime);
    
    // Case 4 comparing Algorithms
    startTime = System.currentTimeMillis();
    for (int i = 2; i <= 100000; ++i) {
        if (isPrime4(i))
            continue;
    }
    stopTime = System.currentTimeMillis();
    System.out.printf(
              "Duracion: %4d ms. s = Math.sqrt(N) while (i <= s) Algorithm\n",
              stopTime - startTime);
    }
    
    public static boolean isPrime1(int n) {
        for (long i = 2; i * i <= n; i++) {
            if (n % i == 0)
                return false;
        }
        return true;
    }
    
    public static boolean isPrime2(int n) {
        for (long i = 2; i <= sqrt(n); i++) {
            if (n % i == 0)
                return false;
        }
        return true;
    }
    
    public static boolean isPrime3(int n) {
        double s = sqrt(n);
        for (long i = 2; i <= s; i++) {
            if (n % i == 0)
                return false;
        }
        return true;
    }
    
    public static boolean isPrime4(int n) {
        // Proving wich if faster between my sqrt method or Java's sqrt
        double s = Math.sqrt(n);
        for (long i = 2; i <= s; i++) {
            if (n % i == 0)
                return false;
        }
        return true;
    }
    
    public static double abs(double n) {
        return n < 0 ? -n : n;
    }
    
    public static double sqrt(double n) {
        // Newton's method, from book Algorithms 4th edition by Robert Sedgwick
        // and Kevin Wayne
        if (n < 0)
            return Double.NaN;
    
        double err = 1e-15;
        double p = n;
    
        while (abs(p - n / p) > err * n)
            p = (p + n / p) / 2.0;
    
        return p;
    }
    }
    

这也是我的代码的链接:http://ideone.com/Fapj1P


1. Why is faster to compute i*i, sqrt (n) times. than sqrt (n) just one time ?看看下面的复杂性。计算平方根的额外成本。

2. Why Math.sqrt() is faster than my sqrt() method ?
Math.sqrt() 委托对 StrictMath.sqrt 的调用,这是在硬件或本机代码中完成的。

3. What is the complexity of these algorithms?
您描述的每个函数的复杂性

i=2 .. i*i<n O(平方(n))

i=2 .. sqrt(n) O(sqrt(n)*log(n))

i=2 .. sqrt (by Newton's method) O(sqrt(n)) + O(log(n))

i=2 .. sqrt (by Math.sqrt) O(平方(n))

牛顿法的复杂度为
http://en.citizendium.org/wiki/Newton%27s_method#Computational_complexity

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

为什么乘法比求平方根快很多倍? 的相关文章

  • Java LostFocus 和 InputVerifier,按反向制表符顺序移动

    我有一个 GUI 应用程序 它使用 InputVerifier 在产生焦点之前检查文本字段的内容 这都是很正常的 然而 昨天发现了一个问题 这似乎是一个错误 但我在任何地方都找不到任何提及它的地方 在我将其报告为错误之前 我想我应该问 我在
  • 数学 - 映射数字

    如何将 a 和 b 之间的数字线性映射到 c 和 d 之间 也就是说 我希望 2 到 6 之间的数字映射到 10 到 20 之间的数字 但我需要广义的情况 我的脑子炸了 如果您的数字 X 位于 A 和 B 之间 并且您希望 Y 位于 C 和
  • 我对线程失去了理智

    我想要这个类的对象 public class Chromosome implements Runnable Comparable
  • 自定义列表字段点击事件

    我正在编写一个应用程序 其中我创建了用于显示列表视图的自定义列表字段 我的 CustomListField 包含连续的一个图像和文本 我正在通过单击列表字段行获取字段更改侦听器 但我也想将字段更改侦听器放在图像上 谁能告诉我我该怎么做 这是
  • 为什么用scala写的代码比用java写的慢6倍?

    我不确定我在编写 scala 代码时是否犯了一些错误 问题是 The four adjacent digits in the 1000 digit number that have the greatest product are 9 9
  • Java中Gson、JsonElement、String比较

    好吧 我想知道这可能非常简单和愚蠢 但在与这种情况作斗争一段时间后 我不知道发生了什么 我正在使用 Gson 来处理一些 JSON 元素 在我的代码中的某个位置 我将 JsonObject 的 JsonElements 之一作为字符串获取
  • 为什么 jar 执行的通配符在 docker CMD 中不起作用?

    我有一个Dockerfile与以下CMD启动我的 Spring Boot 应用程序 FROM java 8 jre CMD java jar app file jar 当我尝试从创建的图像启动容器时 我得到 Error Unable to
  • ThreeTen 向后移植与 JSR-310 的比较

    由于某些原因 我们现在无法使用 java 8 我们仍然停留在 java 7 上 不过 我想使用新的JSR 310 date time APIs现在 使用官方向后移植 ThreeTen http www threeten org threet
  • 为什么在将 String 与 null 进行比较时会出现 NullPointerException?

    我的代码在以下行中出现空指针异常 if stringVariable equals null 在此语句之前 我声明了 stringVariable 并将其设置为数据库字段 在这个声明中 我试图检测该字段是否有null值 但不幸的是它坏了 有
  • Android 认为我没有关闭数据库!为什么?

    我有一个 SQLiteDatabase 数据成员 我在 onCreate 中初始化它 并在 onPause onStop 和 onDestroy 中调用 close 它在 onResume 中重新初始化 它似乎运行得很好 但当我查看调试器时
  • 在java程序中使用c++ Dll

    我正在尝试使用System LoadLibrary 使用我用 C 编写的一个简单的 dll UseDllInJava java import com sun jna Library import com sun jna Native imp
  • 使用 Proguard 通过 Dropbox.com 库混淆 Android 应用程序

    我刚刚创建了一个需要 Dropbox com API 库的 Android 应用程序 我现在尝试在 发布 模式下构建应用程序 并希望在代码上运行混淆器以对其进行混淆 但是 每当我尝试运行 Proguard 时 都会收到以下错误 Progua
  • 类更改(例如字段添加或删除)是否保持 Serialized 的向后兼容性?

    我有一个关于 Java 序列化的问题 在这种情况下 您可能需要修改可序列化类并保持向后兼容性 我有丰富的 C 经验 所以请允许我将 Java 与 NET 进行比较 在我的Java场景中 我需要使用Java的运行时序列化机制序列化一个对象 并
  • Java 8 Stream,获取头部和尾部

    Java 8 引入了Stream http download java net jdk8 docs api java util stream Stream html类似于 Scala 的类Stream http www scala lang
  • 如何向页面添加 HTML 页眉和页脚?

    如何使用 itext 从 html 源添加标题到 pdf 目前 我们已经扩展了 PdfPageEventHelper 并重写了这些方法 工作正常 但当我到达 2 个以上页面时 它会抛出 RuntimeWorkerException Over
  • Android ScrollView,检查当前是否滚动

    有没有办法检查标准 ScrollView 当前是否正在滚动 方向是向上还是向下并不重要 我只需要检查它当前是否正在滚动 ScrollView当前形式不提供用于检测滚动事件的回调 有两种解决方法可用 1 Use a ListView并实施On
  • 确定 JavaFX 中是否消耗了事件

    我正在尝试使用 JavaFX 中的事件处理来做一些非滑雪道的事情 我需要能够确定手动触发事件后是否已消耗该事件 在以下示例中 正确接收了合成鼠标事件 但调用 Consumer 不会更新该事件 我对此进行了调试 发现 JavaFX 实际上创建
  • Java 中清除嵌套 Map 的好方法

    public class MyCache AbstractMap
  • 关闭扫描仪是否会影响性能

    我正在解决一个竞争问题 在问题中 我正在使用扫描仪获取用户输入 这是 2 个代码段 一个关闭扫描器 一个不关闭扫描器 关闭扫描仪 import java util Scanner public class JImSelection publ
  • GAE 无法部署到 App Engine

    我正在尝试从 Eclipse 发布 Web 应用程序 我在 GAE 上创建了四个项目 可以通过登录我的帐户并查看控制台来查看它们 我已经改变了appengine web xml到项目的应用程序 ID 如果我将其更改为 GAE 上第一个创建的

随机推荐