2013年9月28日 星期六

UVA 386 - Perfect Cubes

Problem link

Keyword: brute force

Algorithm:

Ran through all N from 1 to 200(but you may also start from 6 because it's the minimum sum) and see if it's composed of three cubic numbers.
Use a O(N^2) alg. instead of a O(N^3) one to get higher performance.

Code:
#include<cstdio>
#include<cmath>
inline int cube( int i ) { return i*i*i; }
bool Cub[ 8000000 ] = { false };

int main()
{
    for( int i = 0; i < 200; ++i )
        Cub[ cube( i ) ] = true;
    for( int i = 6; i <= 200; ++i )
        for( int j = 2; j < i; ++j )
            for( int k = j; k < i; ++k )
            {
                int tmp = cube( i ) - cube( j ) - cube( k );
                if( tmp > 0 && Cub[ tmp ] && cbrt( tmp ) >= k )
                    printf( "Cube = %d, Triple = (%d,%d,%.0f)\n", i, j, k, cbrt( tmp ) );
            }
    return 0;
}

沒有留言:

張貼留言