算法高手请进
public class A
{
public static void main(String[] args)
{
int demo;
for (int i = 1; i < 50; i++)
for (int j = i + 1; j < 100; j++)
for (int k = j + 1; k < 100; k++)
for (int l = k + 1; l < 100; l++)
for (int m = l + 1; m < 100; m++)
if ((i + j + k + l + m) == 100)
System.out.println(i,j,k,l,m);
}
}
谁有更好的方法
或者可以将这个程序进行完整修改
希望你的电脑不会死机
------解决方案--------------------楼主原方法改写:
public static void main(String[] args) {
long start = System.currentTimeMillis();
int counter = 0;
int result = 0;
for (int i = 1; i < 50; i++) {
for (int j = i + 1; j < 100; j++) {
for (int k = j + 1; k < 100; k++) {
for (int l = k + 1; l < 100; l++) {
for (int m = l + 1; m < 100; m++) {
if ((i + j + k + l + m) == 100) {
System.out.println(i + " " + j + " " + k + " " + l + " " + m);
result++;
}
counter++;
}
}
}
}
}
long end = System.currentTimeMillis();
System.out.println( "得到 " + result + "个结果; 花费时间: " + (end - start) + "毫秒; 循环次数: " + counter);
}
输出:
得到25337个结果; 花费时间:1547毫秒; 循环次数:69404384
改进后的方法:
public static void main(String[] args) {
long start = System.currentTimeMillis();
int counter = 0;
int result = 0;
for (int i = 1; i < 50; i++) {
for (int j = i + 1; j < 100 && i + j <= 100; j++) {
for (int k = j + 1; k < 100 && i + j + k <= 100; k++) {
for (int l = k + 1; l < 100 && i + j + k + l <= 100; l++) {
for (int m = l + 1; m < 100 && i + j + k + l + m <= 100; m++) {
if ((i + j + k + l + m) == 100) {
System.out.println(i + " " + j + " " + k + " " + l + " " + m);