首页  >  文章  >  后端开发  >  在C语言中编写的斐波那契数列程序

在C语言中编写的斐波那契数列程序

WBOY
WBOY转载
2023-09-05 18:53:061051浏览

在C语言中编写的斐波那契数列程序

给定'n'个数字,任务是生成从0到n的斐波那契数列,其中整数的斐波那契数列形式为

0, 1, 1, 2, 3, 5, 8, 13, 21, 34

其中,整数0和1将有固定的空格,然后添加两位数字,例如,

将原文翻译为中文后,保留HTML代码如下:

其中,整数0和1将有固定的空格,然后添加两位数字,例如,

0+1=1(3<sup>rd</sup> place)
1+1=2(4<sup>th</sup> place)
2+1=3(5<sup>th</sup> place) and So on

斐波那契数列的序列F(n)将具有定义为−的递归关系。

Fn = Fn-1 + Fn-2
Where, F(0)=0 and F(1)=1 are always fixed

可以使用多种方法来生成斐波那契数列 −

递归方法 − 在这种方法中,函数在每个整数值之后都会调用自身。它简单易行,但会导致指数级的时间复杂度,使得这种方法不够有效。

使用for循环 − 通过使用for循环来生成斐波那契数列,可以将时间复杂度降低到O(n),使得这种方法更加有效。

示例

Input-: n=10
Output-: 0 1 1 2 3 5 8 13 21 34

算法

Start
Step 1 -> Declare function for Fibonacci series
   Void Fibonacci(int n)
      Declare variables as int a=0,b=1,c,i
      Print a and b
      Loop For i=2 and i<n and ++i
         Set c=a+b
         Print c
         Set a=b
         Set b=c
      End
Step 2 -> In main()
   Declare int as 10
   Call Fibonacci(n)
Stop

Example

的中文翻译为:

示例

#include<stdio.h>
void fibonacci(int n){
   int a=0,b=1,c,i;
   printf("fibonacci series till %d is ",n);
   printf("</p><p>%d %d",a,b);//it will print 0 and 1
   for(i=2;i<n;++i) //loop starts from 2 because 0 and 1 are the fixed values that series will take{
      c=a+b;
      printf(" %d",c);
      a=b;
      b=c;
   }
}
int main(){
   int n=10;
   fibonacci(n);
   return 0;
}

输出

fibonacci series till 10 is
0 1 1 2 3 5 8 13 21 34

以上是在C语言中编写的斐波那契数列程序的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文转载于:tutorialspoint.com。如有侵权,请联系admin@php.cn删除