Find the sum of the nth term and the first n term of the Fibonacci sequence

Find the sum of the nth term and the first n term of the Fibonacci sequence

Insert picture description here

The Fibonacci sequence means that every term from the third term is equal to the sum of its first two
terms. There are two common methods for finding the nth term and the first n terms of the Fibonacci sequence, namely recursion and array
( A) Recursion

#include<stdio.h>
int Fibon(int n)
{
    if(n <= 2)
    {
        return 1;
    }
    else
    {
        return Fibon(n - 2) + Fibon(n - 1); //这一项等于它前两项之和
    }
}
int Sum(int n)
{
    int sum = 0;
    sum = Fibon(n + 2) - 1; //斐波那契数列前n项和公式
    return sum;
}
int main()
{
    int n;
    printf("请输入项数:");
    scanf("%d",&n);
    printf("第%d项是:%d\n",n,Fibon(n));
    printf("前%d项是:%d\n",n,Sum(n));
    return 0;
}

Insert picture description here
(Two) array

#include <stdio.h>
void Fibon(int n)//1 1 2 3 5 8 13 21 
{
    int sum  = 0;
    int F[100];
    F[1] = 1;
    F[2] = 1;
    int i ;
    for(i =3;i <=n;i++)
    {
        F[i] = F[i - 2] + F[i - 1];
        sum += F[i];         
    }
    printf("第%d项是:%d\n",n,F[n]);
    printf("前%d项是:%d\n",n,sum + 2);   //因为循环是从第三项2开始的,所以要加2
}
int main()
{ 
    int n;
    scanf("%d",&n);
    Fibon(n);
    return 0;
}

Insert picture description here

Guess you like

Origin blog.csdn.net/qq_43579888/article/details/88938177