当前位置:网站首页>On the non recursive and recursive implementation of finding the nth Fibonacci number respectively
On the non recursive and recursive implementation of finding the nth Fibonacci number respectively
2022-07-28 17:45:00 【Crazy orange】
Fibonacci sequence :1,1,2,3,5,8,13,21,34......
The first two numbers are 1, When n>=2 when , hinder Fibonacci The number is the sum of the first two Fibonacci numbers .
Non recursive method to achieve N Fibonacci Numbers
#include <stdio.h>
int main()
{
int i = 0;
int a = 1;
int b = 1;
int c = a + b;
int n = 2;
scanf("%d", &n);
if (n > 2)//n<3 The output 1,n>3 Enter circulation
{
for (i = 1; i <= n - 3; i++)// As the first 4 Fibonacci Numbers , Only bad circulation 1 Time .
{
a = b; //a=1
b = c; //b=2
c = a + b; //c=3
}
printf("%d\n", c);// Output No 4 Fibonacci Numbers 3
}
else
printf("%d\n", 1);//
return 0;
}The recursive method realizes the N Fibonacci Numbers
#include <stdio.h>
int Fibonacci_number(int n)
{
if (n == 1)
{
return 1;
}
if (n == 2)
{
return 1;
}
else
return Fibonacci_number(n - 1) + Fibonacci_number(n - 2);
}
int main()
{
int n = 0;
scanf("%d",&n);
printf(" The first %d The Fibonacci number is %d\n", n, Fibonacci_number(n));
return 0;
}Recursive drawing demonstration
If scanf Input n yes 4, Get into Fibonacci_number(n) Function body

After calling the function ,return Return value , First return the last recursive function Fibonacci_number(n - 1) The value of is 1, Fibonacci_number(n - 2) yes 1,1+1=2; Return to the second recursive return 2、1, The final return value of the main function is 3.
Final output : The first 4 The Fibonacci number is 3.

边栏推荐
猜你喜欢
随机推荐
点云处理--voxel filter
.net MVC的理解
【C语言进阶】——指针进阶[Ⅰ]
软件测试前景如何?该如何进行学习呢?
【C语言进阶】——函数指针
Can you read the story?
MySQL optimization summary
Talking about test platform -- Discussion on construction mode
[阅读笔记]-2 通过朴素贝叶斯模型学习机器学习分类
医学公共数据库
mmdetection3D---(1)
JS implementation of special prime numbers
The difference between using switch in a loop and using break and continue after executing a condition
MySQL高级-MVCC(超详细整理)
禅道项目管理软件,敏捷开发团队不可或缺的工具
软件测试到底有没有前景和出路?
Random talk on test platform - platform construction ideas (Part 1)
软件测试就业前景怎么样?
软件测试工作内容太简单怎么办?
【p5.js】实战临摹——国际象棋盘



![【C语言进阶】——剖析入微数据在内存中的存储[上]](/img/6a/ac723cee2543cd2403a7e58d556c8e.png)




