What’s wrong with this recursion in Java?
public class findPyt
{
public static int sum = 0;
public static void main(String[] args)
{
findP(3, 4, 5);
}
public static void findP(int a, int b, int c)
{
sum = a+b+c;
if (sum == 1000)
{
System.out.println("The Triplets are: "+ a +","+ b +","+ c);
}
else
{
findP(a*2, b*2, c*2);
}
}
}
I get this exception:
Exception in thread "main" java.lang.StackOverflowError
at hello.findP(hello.java:12)
at hello.findP(hello.java:19)
When I try to do the same in Ruby, I get this:
SystemStackError: stack level too deep
def pythagoreanTriples(a=3, b=4, c=5)
if (a+b+c) == 1000
puts "The Triplets are: "+ a +","+ b +","+ c
else
pythagoreanTriples(a*2, b*2, c*2)
end
end
Try changing
sum == 1000tosum >= 1000. There is no triple that sums to exactly 1000, so it’s skipping over the terminating condition.Also, your Ruby code doesn’t match your Java code (you’re missing
else). Even if it did find a sum of 1000, it would print the message, and keep recursing until it crashed.