Hey all. So the code I am posting works fine, but I am unsure how to make it recursive. Anytime i change the return to "return collatz(n*3+1)" or "return collatz(n/2)" I just always end up with "1" which is the final product, but none of the numbers in-between. Any ideas?
I am trying to print out each number as it is calculated. Correct output would be
What number do you want to begin with? 15
46,23,70,35,106,53,160,80,40,20,10,5,16,8,4,2,1
If z = 15.
I'm assuming I am going about recursion the wrong way, so any tips would help. I'm not looking for a solution - I want to do it myself - I've just been trying for the past few hours with no results.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
|
#include <iostream>
using namespace std;
int collatz (int n)
{
if (n == 1 || n == 2)
{
return 1;
}
else
if (n%2 == 1)
{
return (n*3+1);
}
else
if (n%2 != 1)
{
return (n/2);
}
}
int main()
{
int z;
cout <<"What number do you want to begin with?";
cin >> z;
do{
z = collatz(z);
cout << z;
if (z > 1)
{
cout << ",";
}
}
while (z > 1);
return 0;
}
|