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 == 1000 to sum >= 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.
Well, if you look at your method that performs the recursion, the only exit condition is when sum == 1000. Your current input values are 3, 4, and 5. That sum is 12. The condition doesn't hold true, so it tries the next set, where sum = 24. Then 48, 96 and so forth. The sum will never be 1000, so the recursion will never end.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With