Possible Duplicate:
I want to generate the nth term of the sequence 1,3,8,22,60 ,164 in Order(1) or order of (nlogn)
Calculate the nth term of the sequence 1,3,8,22,60,164,448,1224…?
I have a recurrence relation f(n) = 2 * (f(n-1) + f(n-2)). I have to solve for f(k) mod 1000000007 where k is the input. The range of k is 1 <= k <= 1000000000?. I have tried implementing it through simple recursive function, but apparently it causes overflow for large k and hence I encounter a runtime error. I am new to algorithms and stuff, so need to know whether there exists concrete and efficient ways to solve such problems?
#include<stdio.h>
#define M 1000000007
long long unsigned res(long long unsigned n){
if(n==1)
return 1;
else {
if(n==2)
return 3;
else return (2*(res(n-1)%M+res(n-2)%M));
}
}
int main(){
int test;
scanf("%d",&test);
while(test--){
long long unsigned n;
scanf("%llu",&n);
printf("%llu\n",res(n));
}
getch();
return 0;
}