Recursive and non-recursive implementation of Nth Fibonacci number

Topic description:

To find the nth Fibonacci number, two methods are described in this blog:
One is to use recursive call function to achieve,
One is a non-recursive loop implementation
First of all, we need to understand what the Fibonacci sequence is. The Fibonacci sequence is characterized by the first two numbers being 1, and the latter number being the sum of the first two numbers, such as

write picture description here

write picture description here

A recursive implementation

#include<stdio.h>
#include<stdlib.h>
int fib(int n)
{
    if(n<=2)
    {
        return 1;   //前两个数为1
    }
    else
    {
        return fib(n-1)+fib(n-2);  //第n个数值为前两数之和,形成函数调用
    }
}
int main()
{
    int n = 0;
    int ret = 0;
    printf("请输入要求的斐波那契项数n:\n");
    scanf("%d",&n);
    ret = fib(n);
    printf("第n个斐波那契数为:%d\n",ret);
    system("pause");
    return 0;
}

The recursive calling program code looks simple and clear at a glance, but if the number sequence is required to be large, the function is called repeatedly in the stack, and finally returns, the calculation time is long and the efficiency is low, so we must use recursion selectively.

In order to improve efficiency and avoid repeated calls, the code running overhead is too large. Let's use a loop to implement it. Save the data each time to avoid repeated calculations.

write picture description here

2. Cyclic realization

#include<stdio.h>
#include<stdlib.h>
int fib(int n)
{
    int a = 1;    //前两项均为1
    int b = 1;
    int c = 0;
    c = a + b;
    b = a ; 
    c = b ;
    while(n>2)   //循环条件
    {
        c = a + b;
        a = b;    //a,b均为前两项
        b = c;
        n--;
    }
    return c;
}
int main()
{
    int n = 0;
    int ret = 0;
    printf("请输入要求的斐波那契项数n:\n");
    scanf("%d",&n);
    ret = fib(n);
    printf("第n个斐波那契数为:%d\n",ret);
    system("pause");
    return 0;
}

operation result
write picture description here

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325758361&siteId=291194637