post  long double = crash?!?

iggi (8)   Link to this post
I have this program, it works for MOST numbers entered, but once I enter "123456", the program just exits. Here is my source code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>

using namespace std;

long double function(int n);
int n;

int main() {
while(1) {
    cout << "enter n for computing F(n) (-1 to exit): ";
    cin >> n;
    cout << 2*function(n) << "\n";
    if (n == -1) 
    break;
}
return 0;
}

long double function(int n) {
    if ( n <= 0)
    return 0;
    else
    return n+function(n-1);
}


This program calculates F(n)= 2(1) + 2(2) + ... + 2n.
magicalblender (82)   Link to this post
when you enter 123456, function() is recursively called 123456 times, which is too much. You might want to just use a while loop instead.
iggi (8)   Link to this post
the question posed to me stated I must specifically use recursion.
magicalblender (82)   Link to this post
Some compilers are able to optimize tail-recursion functions, like yours, so that they don't cause stack overflows. Check to see if your compiler has such an option, or find another compiler that does.

This topic is archived - New replies not allowed.