[英]How would I speed up this program?
我目前正在尝试解决ProjectEuler问题 ,但除速度外,其他方面我都没有了。 我几乎可以肯定,程序执行如此缓慢的原因是由于嵌套循环。 我希望就如何加快速度提供一些建议。 我是新手程序员,所以我对许多更高级的方法/主题不熟悉。
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;
}
}
}
}
}
}
对于初学者来说,在查看除数时,您不需要走得更远,而不是数字的平方根,因为平方根下方的每个除数在上方都有一个等效项。
n = a * b => a <= sqrt(n) or b <= sqrt(n)
然后,您需要计算除法的另一侧:
double root = Math.sqrt(num);
for (int x = 1; x < root; x++) {
if (num % x == 0) {
counter += 2;
}
}
平方根是特殊的,因为如果它是整数,则仅计数一次:
if ((double) ((int) root) == root) {
counter += 1;
}
您只需要将数字分解即可。 p^a * q^b * r^c
具有(a+1)*(b+1)*(c+1)
除数。 这是使用此想法的一些基本实现:
static int Divisors(int num) {
if (num == 1) {
return 1;
}
int root = (int) Math.sqrt(num);
for (int x = 2; x <= root; x++) {
if (num % x == 0) {
int c = 0;
do {
++c;
num /= x;
} while (num % x == 0);
return (c + 1) * Divisors(num);
}
}
return 2;
}
public static void test500() {
int i = 1, num = 1;
while (Divisors(num) <= 500) {
num += ++i;
}
System.out.println("\nFound: [" + i + "] - " + num);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.