我编写了一些java代码来确定给定数字的三个立方体的总和。 (抱歉,我真的不确定如何解释它的作用,但代码相当简单。)问题是,当搜索 -100 到 100 之间的数字时,代码运行得非常快。但是,当搜索更大的区域(数千或一万等)时,即使在寻找较小的数字时,它也会开始运行得很慢。我所要求的是优化它的方法,也许是让它更系统地搜索的方法,从小整数开始,一直到更大的整数,而不是它现在的做法,即随机选择并检查它们并给出答案。
这是代码:
public class test{
public static void main(String[] args)
{
int want = -69;
double test;
boolean found = false;
int answer;
while(found == false)
{
int max = 100;
int min = max / 2;
int a = (int) (Math.random()*max - min);
int b = (int) (Math.random()*max - min);
int c = (int) (Math.random()*max - min);
test = Math.pow(a, 3) + Math.pow(b, 3) + Math.pow(c, 3);
answer = (int) test;
if(answer == want) {
found = true;
System.out.println(a + " " + b + " " + c);
System.out.println(answer);
}
}
}
}
最佳答案
这通常不是一个简单的问题。一种更系统的方法是在给定的 a、b 和 c 值范围内测试 a、b 和 c 的每种可能组合。像这样:
public class Main{
static boolean foundSolution = false;
public static void main(String []args){
int limit = 10;
boolean[][][] alreadyChecked = new boolean[limit*2+1][limit*2+1][limit*2+1];
foundSolution = false;
printCubesOfNum(-69,limit,0,0,0,alreadyChecked);
}
public static void printCubesOfNum(int answer,int limit, int a, int b, int c,boolean[][][] alreadyChecked) {
if(!foundSolution && !alreadyChecked[a+limit][b+limit][c+limit] && a < limit && a > -limit && b < limit && b > -limit && c < limit && c > -limit) {
alreadyChecked[a+limit][b+limit][c+limit] = true;
int test = (int)Math.pow(a, 3) + (int)Math.pow(b, 3) + (int)Math.pow(c, 3);
if(test == answer) {
System.out.println(a + " " + b + " " + c);
System.out.println(answer);
foundSolution = true;
}else{
printCubesOfNum(answer,limit,a+1,b,c,alreadyChecked);
printCubesOfNum(answer,limit,a,b+1,c,alreadyChecked);
printCubesOfNum(answer,limit,a,b,c+1,alreadyChecked);
printCubesOfNum(answer,limit,a-1,b,c,alreadyChecked);
printCubesOfNum(answer,limit,a,b-1,c,alreadyChecked);
printCubesOfNum(answer,limit,a,b,c-1,alreadyChecked);
}
}
}
}
请注意,此代码在找到解决方案后停止。可以有多个解,也可以没有解。
关于java - 如何优化/更改 "searching"程序Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41792595/