Saturday, January 21, 2012

Fibbonnacci_Divide And Conquer

#include<stdio.h>


long fib(long n)
{
long i,j,k,h,t;


i=h=1;
j=k=0;


while(n>0)
{
if(n%2==1)
{
t = j*h;
j = i*h + j*k + t;
i = i*k + t;
}


t = h*h;
h = 2*k*h + t;
k = k*k+t;
n = long(n/2);


}


return j;
}


int main()
{
long n,res;


while(scanf("%ld",&n)==1)
{
res = fib(n);
printf("%ld\n",res);


}
return 0;
}
/*
Input:
20
57
345
Output:
6765
365435296162
563963353180680437428706474693749258212475354428320807161115873039415970
*/

No comments:

Post a Comment