2013年10月6日 星期日

UVa 138 - Street Numbers

Problem link

Keyword: brute force, math

Algorithm:

Try street length from 1 and increment it by 1 each time. Check if this length has the attribute specified by this problem. End the program when we found 10 solutions.
*Use math equations to find out if there's a solution at certain length.

Code:
#include<cstdio>
#include<cmath>
long long int sq( long long int a ) { return a*a; }

int main()
{
    long long int out = 0, root;
    for( long long int i = 6; out < 10; ++i )
        if( sq( root = (long long int)sqrt( 8*i*i + 1 ) ) == i*i*8 + 1 && root % 2 )
            printf( "%10lld%10lld\n", i, ( root-1 ) / 2 ), out++;

    return 0;
}

沒有留言:

張貼留言