Recursion problem.

I've written the following recursive function. But when I give large value in it, it crushes. Why? How to fix it?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <iostream>

using namespace std;

int recur(int n1, int n2, int n3)
{
    if(n1>n2 && n1>n3)
        return recur(n1-1, n2, n3);
    else if(n2>n1 && n2>n3)
        return recur(n1, n2-1, n3);
    else if(n3>n1 && n3>n2)
        return recur(n1, n2, n3-1);
    else
        return (n1+n2+n3);
}


int main()
{
    ios::sync_with_stdio(false);cin.tie(0);

    int n1,n2,n3;

    while(cin>>n1>>n2>>n3)
    {
        cout<<recur(n1,n2,n3)<<endl;
    }

    return 0;
}

The operating system usually allocates a relatively small amount of memory to the stack (where function parameters and local variables are stored). If there are large differences between n1, n2 and n3, then your program will make many many recursive calls which will use up all the space on the stack. If you enter 1000000 2 3, I suspect it will crash.

It's possible to tell the linker to allocate more space to the stack, but the details depend on the compiler itself. With this function, a large enough input will almost certainly kill the program. Try restricting your inputs to numbers less than 100. That should let you see how the recursion works.
Then which technique will fix the problem? Where should I make change?
you can try following non-recursive function.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>

int non_recur( int n1, int n2, int n3){	

  if(n1<n2 && n2<n3) 
  	return n1+2*n2;  	  
  
  else if(n1<n2 && n3<=n2) 
  	return n1+2*n3;  
  
  else if(n2<n1 && n1<n3) 
  	return n2+2*n1;
  	
  else if(n2<n1 && n3<=n1)	
  	return n2+2*n3;
  
  else if(n3<n1 && n1<n2)
  	return n3+2*n1;

  else if(n3<n1 && n2<=n1)
  	return n3+2*n2;		
  
  else  return (n1+n2+n3);
}


int main(){       
	std::cout << non_recur(5,3,4) << std::endl; 
    return 0;
}
Topic archived. No new replies allowed.