【发布时间】:2019-06-25 17:49:55
【问题描述】:
这是我为问题 5 Project Euler 寻找性能良好的算法的尝试 - 找到可均匀整除 x 的最小可能数和 x 以下的所有数。
我尝试使用一个循环生成 #s 和另一个循环来测试该数字是否可以被 x 和所有低于 x 的 #s 整除
System.out.println("This program finds the smallest positive "
+ "number that");
System.out.println("is evenly divisible by all of the numbers "
+ "from 1 to N.");
System.out.print("Enter N: ");
int N=kb.nextInt();
long bigN=1;
for(int i=1;i<=N;i++){
bigN=bigN*i;
/*bigN serves as a definite end for our loop
when trying to find all #s divisible from 1 to n
*/
}
long smallestAnswer=bigN;
int count=0;
for(long i=1;i<=bigN;i++){//# being tested
for(int j=1;j<=N;j++){//test
if(i%j==0){
count++;
}
if(count==N && i<smallestAnswer){
smallestAnswer=i;//should catch only the first/smallest answer
break;
}
}
count=0;
}
System.out.printf("\nThe smallest # evenly divisible by all of the "
+ "numbers from 1 to N");
System.out.printf("\nis %,d\n",smallestAnswer);
}
代码有效。没有运行/编译时间错误。只是太慢了。如果用户输入一个大于 11 的#,代码就基本冻结了
【问题讨论】:
-
我投票决定将此问题作为离题结束,因为要求改进运行代码的问题属于 codereview.stackexchange.com
-
@Andreas 我不同意。这是纯粹的算法。这不是一个简单的代码审查问题。
-
在哪里:比这里的帮助台学习 codereview 帮助台要多得多。了解如何提出社区范围内的问题。
-
@AlexandarPetrov 如果有关于算法的问题,请使用Computational Science Stack Exchange
-
@GhostCat 通过提供示例解决方案,他已经证明他已经做出了努力。
标签: java algorithm performance