.NET有大数库,但喜欢自己写也不妨。
授人以渔,不授人以鱼。
#include <stdio.h> #include <string.h> #include <assert.h> struct LINT { char s[1221]; }; void LINT_Add( struct LINT* a, const struct LINT* b ) { unsigned int carry = 0; // 进位 for( unsigned i=0; i<sizeof(a->s)/sizeof(a->s[0]); ++i ) { unsigned int t = a->s[i] + carry + b->s[i]; a->s[i] = t%10; carry = t/10; } assert( !carry ); } void LINT_print( const struct LINT a ) { unsigned index; for( index=sizeof(a.s)/sizeof(a.s[0]); index!=0 && a.s[index-1]==0; --index ); for( ; index!=0; --index ) printf( "%d", a.s[index-1] ); printf( "\n" ); } struct LINT foo( unsigned n ) // n<10000 { struct LINT buf[3]; memset( buf, 0, sizeof(buf) ); buf[0].s[0] = 1; buf[1].s[0] = 1; buf[2].s[0] = 1; for( unsigned i=5; i<=n; ++i ) LINT_Add( &buf[(i+1)%3], &buf[(i+2)%3] ); return buf[(n+1)%3]; } int main() { printf( "f(5) = " ); LINT_print( foo(5) ); printf( "f(9) = " ); LINT_print( foo(9) ); printf( "f(160) = " ); LINT_print( foo(160) ); printf( "f(9999) = " ); LINT_print( foo(9999) ); return 0; }输出结果是:
f(5) = 2 f(9) = 5 f(160) = 14259783588075761122 f(9999) = 532692007196403076840086044264255523113714914725252086145326949585837649390243870857959406324793592736972425612431078622475937455583346791205433629410931900797493770245279774910198229460584496988314997671042632704512024742343587220120829419877051261930541767628082507655809853242587233225386542061628556348459136090633670036641627215466003906583021299432556032462067337369377107891435277145238984081213639359946488344186946303604827609917906184642065848574653993271679319211448048568608150422454451753661350958133644615496914749572769142397010151476835399019138797806037315775221716575799617373815695867377717177479911647575592883693303948949915321227437729134435491247398565078258983042195762299575946884187468661324492277001655885133168762929052270227367508629279955407560075483653046555323940297228255122240657440108763129951404924396624995571537985494523928272785337167279084924030103801237616149132354044661946868772838710467253307015210211851491307648768246251701753894940216220435783767200686129793673346343949601237721523242757900283498087839228458702712757201526934514262828326691183606210590730486536260411030273989268755551961441198829618698017478630108071633713948107766636907226105209476954643635913541414033没有对照,不知道是否正确。若有错误,你自己改改