Hi,
This is my first post here so hi all and bear with me.
I am trying to solve problem 14 on Project Euler to find the longest Collatz sequence under 1000000. I have come up with the following code.
public void solution14() { for(int i=1; i<1000000; i++) { collatz(i); } } public int collatz(int n) { count++; if(n==1) { return 1; } if(n%2==0) { n=n/2; } else { n=n*3+1; } collatz(n); return count; }
The problem is that I am getting stack overflow error when I run the solution14 method and have the call to collatz(i) inside the for loop. If I call collatz(1000000) or any other number, I get the right answer with no errors.
If I reduce the loop from 1000000 to 100000 it will work fine. Can anyone help please
Thanks
Sam