So I'm not sure what is going on here.
I have a function which is supposed to solve this problem, except that while typing out the elements of an array in main() I get different results:
- 0 if I cout it in the same line with the function
- the correct result if i write it out below
Here's the code:
#include <bits/stdc++.h>
using namespace std;
int a[100100],mx=0,bg;
int collatz(int n){
a[1] = 1;
for(int i=2; i<=n; i++){
int p = 0;
int j=i;
while(j!=1 && j>=i){
if(j%2==0) j/=2, p++;
else if(j%2==1) j=3*j+1,
}
a[i] = p + a[j];
if(mx<a[i]) mx = a[i], bg = i;
}
return mx;
}
int main()
{
for(int i=1; i<=10000; i++) a[i] = 0;
cout << collatz(1000) << " " << a[1] << " " << a[2] << " " << a[3]<< "\n";
cout << a[1] << " " << a[2] << " " << a[3] << " ";
return 0;
}
And here's what I get:
The compiler I use is CodeBlocks, though I've tested it on others and it's the same issue!
Thanks