I am having problem with a simple Hanoi tower program.  I need to do something to reduce its time.#include <stdio.h>#include <fstream>using namespace std;int hanojus(int n, char a, char b, char c) {    ofstream fr(hanoj.out,ios::app);    if (n == 1)        fr<<a<<  ->  <<c<<endl;    else {         hanojus(n-1, a, c, b);         fr<<a<<  ->  <<c<<endl;         hanojus(n-1, b, a, c);        }}int main(){    ifstream fd(hanoj.in);    int sk;    fd>>sk;    hanojus(sk, 'A', 'B', 'C');}
Hanoi towers time exeeded
c++;performance;recursion
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 <stdio.h>#include <fstream>using namespace std;int hanojus(int n, char a, char b, char c, ofstream& fr){    if (n == 1)        fr<<a<<  ->  <<c<<endl;    else    {        hanojus(n-1, a, c, b, fr);        fr<<a<<  ->  <<c<<endl;        hanojus(n-1, b, a, c, fr);    }}int main(){    ifstream fd(hanoj.in);    ofstream fr(hanoj.out,ios::app);    int sk;    fd>>sk;    hanojus(sk, 'A', 'B', 'C', fr);}