【发布时间】:2017-02-20 13:02:06
【问题描述】:
我目前正在尝试解决ProjectEuler problem 问题,除了速度之外,我已经把所有东西都搞定了。我几乎可以肯定程序执行如此缓慢的原因是由于嵌套循环。我想就如何加快速度提供一些建议。我是一个新手程序员,所以我对很多更高级的方法/主题并不熟悉。
public class Problem12 {
public static void main(String[] args) {
int num;
for (int i = 1; i < 15000; i++) {
num = i * (i + 1) / 2;
int counter = 0;
for (int x = 1; x <= num; x++) {
if (num % x == 0) {
counter++;
}
}
System.out.println("[" + i + "] - " + num + " is divisible by " + counter + " numbers.");
}
}
}
编辑:下面是速度更快的新代码。也删除了恒定行打印以加快速度。
public class Problem12 {
public static void main(String[] args) {
int num;
outerloop:
for (int i = 1; i < 25000; i++) {
num = i * (i + 1) / 2;
int counter = 0;
double root = Math.sqrt(num);
for (int x = 1; x < root; x++) {
if (num % x == 0) {
counter += 2;
if (counter >= 500) {
System.out.println("[" + i + "] - " + num + " is divisible by " + counter + " numbers.");
break outerloop;
}
}
}
}
}
}
【问题讨论】:
-
尝试使用更快的语言,如 C,并尝试使用位移而不是除法和乘法,如果它们在 Java 中可用
-
这个算法真的有效吗?就像如果
i=3然后num=6然后counter=4这是不正确的 -
@ShaheAnsar 如果你不知道是否支持位移,你怎么能假设 C 比 Java 快?
-
@afsafzal 你的意思是“这是正确的”。 6 的预期值为
1, 2, 3, 6,如 OP 链接到的问题的描述中所示 -
您将打印 15000 行。任何打印都比简单的语句花费更多的时间,所以如果你想计时,首先注释掉打印。
标签: java performance loops nested-loops