I am making a recursive method that reports if a number is a Magic number (sum of 2 cubed numbers). How can I handle this error with an exception when it is thrown like this:
Here the code of the class.
public static boolean Recursivo_esH(int num, int i, int j){
if(j>=num) { return false; }
if(i>=num){
return false;
}
double numero1,numero2;
numero1= Math.pow(i, 3);
numero2= Math.pow(j, 3);
if(numero1+numero2==num){
return true;
}
else {
return Recursivo_esH(num,i,j+1);
}
}
These are the parameters that I am sending from the "main":
public static void main(String []args) throws noEs_HardyException{
boolean vigia = false;
vigia= (Recursivo_esH(56453,1,1));
if(vigia==true) {
JOptionPane.showMessageDialog(null,"El numero es H");
}
else {
JOptionPane.showMessageDialog(null,"El numero NO Es H");
}
}
The error occurs because the recursive function is called too many times and that produces the
StackOverflowError
.The solution to that would be to bound the maximum values of i and j so that they are not greater than the cube root of the number being tested: