c++ - Basic Algorithm Optimization -
my current assignment create basic algorithm finds magic number (which 1). magic number can found either dividing number 2 until it's magic, or multiplying odd number 3, adding 1, dividing 2 until 1. must each positive integer 3 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; (int = start; < 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 { 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, rather slow. -o3
flag in makefile
takes around 115 seconds complete task. professor stated decent time ~60 seconds. how able optimize this?
i think misunderstood assignment. "either dividing number 2 until it's magic, or multiplying odd number 3 , adding 1" should implemeneted as
while( x > 1 ) { if( iseven(x) ) { x /= 2; } else { x *= 3; x += 1; } }
assuming validity of collatz conjecture, can further optimized as
x = 1;
Comments
Post a Comment