I’m solving this problem:
G(n) is defined as G(n) = G(n-1) + f(4n-1) , for n > 0 and G(0) = 0 f(i) is ith Fibonacci number. Given n you need to evaluate G(n)modulo 1000000007.
Input First line contains number of test cases t (t<40000). Each of the next tlines contain an integer n ( 0 <= n <
2^51).Output For each test case print G(n) modulo 1000000007. Example Input: 2 2 4 Output: 15 714
This is the code I’ve written:
typedef long long type;
#define check 1000000007
type x;
type y;
type f(type n)
{
return(ceil((pow(1.618,n) - pow(-0.618,n))/((sqrt(5)*1.0))));
}
type val(type n)
{
if(n==0)
return 0;
else
return (val(n-1)+f(4*n-1));
}
int main()
{
cin>>x;
while(x--)
{
cin>>y;
cout<<val(y)%check<<endl;
}
//getch();
return 0;
}
Can you suggest any improvements?
Sometimes such problems can be tackled with mathematical tricks,
instead of brute force solutions.
The large value of
nand modulo, in my opinion, are indications thata clever solution exists. Of course figuring out the solution is the hard part.
(I’m not sure if this is ideal in your case, I’m only pointing you an alternative way)
For example, in the Art of Computer Programming, Volume 1: Fundamental Algorithms
Knuth uses “generating functions”, a clever way for constructing a closed form
for the Fn fibonacci number.
For more info read Generating Functions (pdf)