I'm trying to find maximum the Collatz sequence between 1 and 1000000. I wrote the following code below. I guess it is correct but it is extremely slow. Can you give me a few hints to make it faster? Thanks.
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
bool myfn(int i, int j) { return i<j; }
int collatz(int x);
int main()
{
vector <int> myvector;
for(int i = 1; i < 1000000; i++)
{
myvector.push_back(collatz(i));
}
cout<<*max_element(myvector.begin(),myvector.end(),myfn);
return 0;
}
int collatz(int x)
{
int counter = 1;
while(1)
{
if(x == 1)
break;
if(x % 2 == 0)
{
x = x / 2;
counter++;
}
else
{
x = 3 * x + 1;
counter++;
}
}
return counter;
}
Here are some tips:
Initialize vector to your capacity.
The vector may be expanding while you are pushing elements. Worst case, one reallocation per push_back.
Treat vector as array
After you have initialized your vector to its capacity, you can use the operator [] to access the vector slot instead of calling push_back
.
Optimize collatz
This is probably your bottleneck. Try placing into a separate file and cranking up the compiler optimizations on it.
There may be a more optimal algorithm.