这两种检查数字是否为素数的方法有什么区别? [英] What is the difference between these two methods for checking if a number is a prime?

查看:53
本文介绍了这两种检查数字是否为素数的方法有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一个方法来检查一个数是否是素数:

I wrote a method for checking if a number is a prime:

static boolean isPrime(int x) {
        for (int i = 2; i <= Math.sqrt(x); i++) {
            if (x % i == 0)
                return false;    
        }
        return true;
    }

在我们学习的一系列练习中,解决方案是:

In a collection of exercises we're learning from, the solution is:

static boolean isPrime(int x) {
    boolean hasDivisors = false;
    for (int i = 2; i <= Math.sqrt(x); i++) {
      if (x % i == 0) {
        hasDivisors = true;
        break;
      }
    }
    return !hasDivisors;
}

在我的情况下,如果我找到一个除数,我会返回该数字不是素数(return false),并且在第二个替换了 break 的需要方法.唯一的另一个明显原因是第二种方法只使用了一个 return 语句.

In my case, If i find a divisor, I return that the number is not a prime (return false) and that replaces the need for a break in second method. The only other obvious reason is that the second method only uses a single return statement.

是否有原因(速度/内存方面)?

Is there a reason for this (speed/memory wise)?

推荐答案

由于您已经确定的所有原因,这两种解决方案都有效并且都有效.好分析.正如其他人所指出的,差异纯粹是风格上的.这是一个关于单返回语句的 有趣的讨论java中的样式.

Both solutions work and both are valid for all the reasons you have already identified. Good analysis. As others have noted, the differences are purely stylistic. Here is an interesting discussion about the single return statement style in java.

在性能方面,我认为这两种方法之间不会有显着差异.但是,如果您想确定,请执行基准测试.如果你想要真正的性能提升,你可以通过替换来消除对 Math.sqrt() 的昂贵调用:

Performance-wise, I wouldn't expect a significant difference between the 2 approaches. But if you want to be certain, perform a benchmark test. If you want a real performance boost, you can eliminate the expensive call to Math.sqrt() by replacing:

for (int i = 2; i <= Math.sqrt(x); i++) {

for (int i = 2; i*i <= x; i++) {

这篇关于这两种检查数字是否为素数的方法有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆