【发布时间】:2014-07-20 05:16:09
【问题描述】:
这是我目前正在制作的计算器程序的一部分,这部分确定 b 是否是 a 的因数。我也是 Java 新手,这让我在第三天学习它的语法。无论如何,我想知道哪种方法更有效地确定 b 是否是 a 的一个因素。对我们来说是模数运算符(%)还是我的第二种方法???
如果有比我想出的两种方法更有效的方法,请显示。
// for now I want the result to print out in the console
public class factornot {
public static void main(String args[]) {
int a = 56, b = 3; // just for testing purposes!
if((a != 0) && (a % b) == 0) System.out.println(b + " is a factor of " + a);
else System.out.println(b + " is not a factor of " + a);
// short-circuit and prevents a divide by zero error!
// is this better or worse, faster or slower ???
int d = (a / b), e = (d * b);
if((a - e) == 0) System.out.println(b + " is a factor of " + a);
else System.out.println(b + " is not a factor of " + a);
}
}
【问题讨论】:
-
你应该把这个发到:codereview.stackexchange.com
-
我猜第一个更快,因为现在大多数或所有处理器都有内置的模指令,因此它们不需要先除后乘。但这只是一个猜测。你必须做一个实验才能确定。无论如何,使用
%更具可读性。 -
你不需要检查
a != 0。我们认为每个数字都是0的一个因子。 -
但请务必检查 b 是否为 0!
-
哪个更快并不重要。其他操作主导运行时。所以选择更具可读性的内容。
标签: java factorization