1

I recently wrote this simple C++ program and I was wondering if it would process faster if it was in a recursion. However, I did not manage to find a way to successfully write it in recursion so I am asking if you could help me with making it with recursion.

#include<iostream> using namespace std; int main() { for (int i1 = 1; i1 <= 45; i1++) { for (int i2 = i1 + 2; i2 <= 46; i2++) { for (int i3 = i2 + 2; i3 <= 47; i3++) { for (int i4 = i3 + 2; i4 <= 48; i4++) { cout<<i1<<" "<<i2<<" "<<i3<<" "<<i4<<endl; } } } } return 0; } 
8
  • It won't be faster with recursion. Commented Nov 22, 2013 at 17:37
  • Recursion doesn't change the number of steps required; it only changes the way you think about the process. Commented Nov 22, 2013 at 17:38
  • Recursion has no positive effects on the performance. Commented Nov 22, 2013 at 17:39
  • So there is no need of it, i just thought it would benefit from the recursion. Anyway do you have any idea why this code is running for 4.3 secs when written in c# and for 38 when in c++? Is it the debugger/compiler? Commented Nov 22, 2013 at 17:39
  • General rule of thumb: if it doesn't feel like you can do something easily, question strongly if you should do it. In this case, if you don't see any way to make this function recursive, question if making it recursive is the solution. You're doing 4100625 iterations. It won't be fast. But this isn't a problem that can be turned recursive, let alone benefit from it. Commented Nov 22, 2013 at 17:40

1 Answer 1

2

Recursion probably won't make it faster, but changing

cout<<i1<<" "<<i2<<" "<<i3<<" "<<i4<<endl; 

to

cout<<i1<<" "<<i2<<" "<<i3<<" "<<i4<<"\n"; 

almost certainly will. This is because by default cout stores its output in a buffer, and only writes ("flushes") it occasionally. However, if you add endl it will write the buffer immediately, which is slower.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.