I have written some java code to determine the sum of what three cubes give you a given number. (Sorry I'm really not sure how to explain what it does, the code is rather simple though.) And the problem is, when searching for numbers between -100 and 100 the code runs very quick. But when searching a bigger area, (thousands or ten-thousands etc) It starts to run very slow, even when looking for small numbers. What I am asking are for ways to optimize it, and maybe ways to have it search more systematically, starting at small integers and working its way up to bigger ones, rather than how it does it now which is to pick random ones and check them with the answer.
Here is the code:
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);
}
}
}
}
Aucun commentaire:
Enregistrer un commentaire