Hanoi towers time exeeded I am having problem with a simple Hanoi tower program.  I need to do something to reduce its time.

#include &lt;stdio.h&gt;
#include &lt;fstream&gt;

using namespace std;

int hanojus(int n, char a, char b, char c) {

    ofstream fr("hanoj.out",ios::app);
    if (n == 1)
        fr&lt;&lt;a&lt;&lt; " -&gt; " &lt;&lt;c&lt;&lt;endl;
    else {
         hanojus(n-1, a, c, b);
         fr&lt;&lt;a&lt;&lt; " -&gt; " &lt;&lt;c&lt;&lt;endl;
         hanojus(n-1, b, a, c);
        }
}
int main()
{
    ifstream fd("hanoj.in");
    int sk;
    fd&gt;&gt;sk;
    hanojus(sk, 'A', 'B', 'C');
}
Try moving the ofstream outside of the method so that you're not creating it every time you make a recursive call.

Like this:

#include &lt;stdio.h&gt;
#include &lt;fstream&gt;

using namespace std;

int hanojus(int n, char a, char b, char c, ofstream&amp; fr)
{
    if (n == 1)
        fr&lt;&lt;a&lt;&lt; " -&gt; " &lt;&lt;c&lt;&lt;endl;
    else
    {
        hanojus(n-1, a, c, b, fr);
        fr&lt;&lt;a&lt;&lt; " -&gt; " &lt;&lt;c&lt;&lt;endl;
        hanojus(n-1, b, a, c, fr);
    }
}

int main()
{
    ifstream fd("hanoj.in");
    ofstream fr("hanoj.out",ios::app);
    int sk;
    fd&gt;&gt;sk;
    hanojus(sk, 'A', 'B', 'C', fr);
}