Correct algorithm, wrong result (cout problem?)
Hi everyone,
I am a C++ newbie. Here is the code (3n+1 algorithm) I am having problem with. No matter what the input number is (to the alg function), the result is always the same (namely, 16384). The algorithm seems correct to me, I guess the problem is with the cout in the main function. I don't know how to fix it. THX in advance.
Code:
#include <iostream>
int alg(int, int);
int main() {
using namespace std;
int result = alg(300,1);
cout << result;
cin.get();
}
//counter = 1
int alg(int n, int counter) {
using namespace std;
if (n == 1)
return counter;
else {
if (n % 2 == 1)
alg(3*n+1, ++counter);
else
alg(n/2, ++counter);
}
}