可能重复:
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…?算法来求解F(N)= 2 *(F(N-1)+ F(N-2))模1000000007
我有一个递归关系f(n)= 2 *(f(n-1)+ f(n-2))。我必须求解f(k)mod 1000000007,其中k是输入。 k的范围是1 < = k < = 1000000000 ?.我试图通过简单的递归函数来实现它,但显然它会导致大k溢出,因此我遇到运行时错误。我对算法和东西很陌生,所以需要知道是否存在具体和有效的方法来解决这些问题?
#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;
}
告诉我们你有什么试过的。什么是基本情况? – Mark
每次有人在评论中发布代码 - 抛出异常... – alfasin
srry!...这是一个错误!我不是故意的,加上互联网在这里吸取 – jigsawmnc