2.斐波那契额数列_递推法

                                     斐波那契额数列_递推法

斐波那契数列指的是这样一个数列:1,1,2,3,5,8,13,21,34……起始的两项是1、1,之后的每一都等于前面两项。

下面用一个简单的题来进行叙述,这个题用递归是有可能时间超限的,因为递归的时间复杂度比较难以计算。而递推则可以快速的输出结果。

递推的主要还是for循环的应用,首先需要确定一个数组里的前两个数或者前几个是确定的。

然后就可以进行其他的计算。下面是对题的描述:

Your objective for this question is to develop a program which will generate a fibbonacci number. The fibbonacci function is defined as such: 

f(0) = 0 
f(1) = 1 
f(n) = f(n-1) + f(n-2) 

Your program should be able to handle values of n in the range 0 to 50. 

Input

Each test case consists of one integer n in a single line where 0≤n≤50. The input is terminated by -1.

Output

Print out the answer in a single line for each test case.

Sample Input

 

3 4 5 -1

Sample Output

 

2 3 5

Hint

Note:
          you can use 64bit integer: __int64 

红字一定要注意哦~~

emmmm,英文的,其实我也不怎么懂,看中文吧。

来来来我们闲话少说,直接上代码,干就完了。

#include<stdio.h>
int main()
{
    long long  f(long long n);
    long long n,i,a[50],j;
    a[0]=0;
    a[1]=1;
    while(scanf("%lld",&n))
    {
        if(n==-1)
            return 0;
        if(n==0)
            printf("0\n");
        else if(n==1)
            printf("1\n");
        else
        {
            for(i=2; i<=n; i++)
            {
                a[i]=a[i-1]+a[i-2];
            }
            printf("%lld\n",a[n]);
        }
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_41886231/article/details/81118530