给个我以前写的(顺便说一下,如果最大40项的话,根本用不到long long)
程序代码:
#include <stdio.h>
unsigned long long fibonacci( unsigned first, unsigned second, size_t n )
{
// a *= b
#define MUL(a,b) do {\
unsigned long long t00 = a##00*b##00+a##01*b##10;\
unsigned long long t01 = a##00*b##01+a##01*b##11;\
unsigned long long t10 = a##10*b##00+a##11*b##10;\
unsigned long long t11 = a##10*b##01+a##11*b##11;\
a##00=t00, a##01=t01, a##10=t10, a##11=t11;\
} while(0)
unsigned long long r00=1,r01=0,r10=0,r11=1;
for( unsigned long long v00=0,v01=1,v10=1,v11=1; n!=0; n/=2 )
{
if( n%2 == 1 )
MUL(r,v); // r*=v
MUL(v,v); // v*=v;
}
return r00*first + r01*second;
#undef MUL
}
int main( void )
{
printf( "%llu\n", fibonacci(1,1,39) ); // fibonacci数列第40项的值是 102334155
return 0;
}