- 注册时间
- 2007-12-26
- 最后登录
- 1970-1-1
- 威望
- 星
- 金币
- 枚
- 贡献
- 分
- 经验
- 点
- 鲜花
- 朵
- 魅力
- 点
- 上传
- 次
- 下载
- 次
- 积分
- 92611
- 在线时间
- 小时
|
发表于 2008-7-10 20:11:07
|
显示全部楼层
更加优化的算法
下面的代码可以遍历全部的64bit内的完全平方数,且效率非常高:- #include <stdlib.h>
- #include <stdio.h>
-
- #include "../../../HugeCalc_API/CppAPI/Include/HugeCalc.h" // 公共接口
-
- #pragma message( "automatic link to ../../../HugeCalc_API/CppAPI/Lib/HugeCalc.lib" )
- #pragma comment( lib, "../../../HugeCalc_API/CppAPI/Lib/HugeCalc.lib" )
-
-
- #define TEN_POW2 100UL
- #define TEN_POW4 10000UL
-
- int main( void )
- {
- const UINT32 cycleDelta[ 4 ] = { 1, 3, 3, 2 }; // 0, 1, 4, 7
- UINT32 table[ TEN_POW4 ];
- UINT32 mark[ 9*4*5 + 1 ];
- UINT32 value[ 5 ], delta[ 5 ];
- UINT32 * p = table;
-
- UINT32 i, j, k, m, s;
- UINT32 i2, i3, i4, s2, s3;
-
- HugeCalc::EnableTimer();
- HugeCalc::ResetTimer();
-
- for ( i4 = 0; i4 < 10; ++i4 )
- {
- for ( i3 = 0; i3 < 10; ++i3 )
- {
- s3 = i4 + i3;
- for ( i2 = 0; i2 < 10; ++i2 )
- {
- s2 = s3 + i2;
- for ( i = 0; i < 10; ++i )
- {
- *p++ = s2 + i;
- }
- }
- }
- }
-
- memset( mark, 0, sizeof( mark ));
- memset( value, 0, sizeof( value ));
- memset( delta, 0, sizeof( delta ));
-
- k = 1;
- j = TEN_POW2;
- value[ 0 ] = 0;
- delta[ 0 ] = 1;
- m = 1;
- for ( ; ; )
- {
- s = 0;
- for ( i = 0; i < m; ++i )
- {
- value[ i ] += delta[ i ];
- if ( value[ i ] >= TEN_POW4 )
- {
- value[ i ] -= TEN_POW4;
- ++value[ i + 1 ];
- }
-
- s += table[ value[ i ] ];
- }
- if ( 0 == mark[ s ] )
- {
- mark[ s ] = k;
- }
-
-
- if ( j == ++k )
- {
- if ( 0 == k )
- {
- break;
- }
-
- j *= ( 5 == ++m ) ? 0 : TEN_POW2;
- }
-
- delta[ 0 ] += 2;
-
- i = 0;
- while ( delta[ i ] >= TEN_POW4 )
- {
- delta[ i ] -= TEN_POW4;
- ++delta[ ++i ];
- }
- }
-
- HugeCalc::EnableTimer( FALSE );
-
-
- s = 0;
- i = 0;
- while ( s < 9*4*5 )
- {
- s += cycleDelta[ i ];
- if ( 4 == ++i )
- {
- i = 0;
- }
-
- if ( 0 != mark[ s ] )
- {
- if ( mark[ s ] <= 0xFFFF )
- {
- printf( "X = %u\tS = %u\n", s, mark[ s ] * mark[ s ] );
- }
- else
- {
- printf( "X = %u\tS = %I64u\n", s, UInt32x32To64( mark[ s ], mark[ s ] ));
- }
- }
- else
- {
- printf( "X = %u\n", s );
- }
- }
-
- printf( HugeCalc::GetTimerStr( FT_DOT06SEC_s ) );
- printf( "\n" );
-
- return 0;
- }
复制代码 备注:代码中,仅调用了 HugeCalc 的高精度计时部分。 |
|