My current assignment is to create a basic algorithm that finds the magic number (which is 1). The magic number can be found by either dividing an even number by 2 until it's magic, or multiplying an odd number by 3, adding 1, the dividing by 2 until 1. We must do this for each positive integer from 3 up until 5 billion.
MAGIC = 1;
DIV = 2;
START = 3;
MAX = 5000000000;
bool isOdd(int x);
void isMagic(int x);
int main () {
clock_t startTime = clock();
cout << "Beginning loop" << endl;
for (int i = START; i < MAX; i++)
{
if ( isOdd(i) == false )
isMagic(i);
else if ( isOdd(i) == true )
isMagic(i);
}
clock_t finishTime = clock();
cout << "Looping took " << double(finishTime - startTime) / CLOCKS_PER_SEC << " seconds" << endl;
return 0;
}
bool isOdd(int x) {
if( x % DIV == 0 )
return false;
else
return true;
}
void isMagic(int x) {
if( isOdd(x) == false ) //Is even
{
while( x > MAGIC )
{
x /= DIV;
};
}
else if( isOdd(x) == true ) //Is odd
{
while( x > MAGIC )
{
x *= START;
x += MAGIC;
x /= DIV;
};
}
return;
}
This works, however, it is rather slow. Even with the -o3
flag in my makefile
it takes around 115 seconds to complete the task. My professor stated that a decent time would be ~60 seconds. How would I be able to optimize this?
I think you misunderstood the assignment. The "either dividing an even number by 2 until it's magic, or multiplying an odd number by 3 and adding 1" should be implemeneted as
Assuming the validity of Collatz conjecture, this can be further optimized as