给定'n'数字,任务是生成斐波那契数列,直到从0到n开始为止,其中整数的斐波那契数列的形式为
0, 1, 1, 2, 3, 5, 8, 13, 21, 34
其中,整数0和1将具有固定的空格,例如,在加上两个数字后,
0+1=1(3rd place) 1+1=2(4th place) 2+1=3(5th place) and So on
斐波那契数列的序列F(n)的递归关系定义为-
Fn = Fn-1 + Fn-2 Where, F(0)=0 and F(1)=1 are always fixed
可以使用多种方法来生成fiboacce系列-
递归方法-在这种情况下,方法函数将在每个整数值之后对其自身进行调用。它很容易实现,但是会导致指数时间复杂性,使这种方法无效。
使用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
#include<stdio.h>
void fibonacci(int n){
int a=0,b=1,c,i;
printf("fibonacci series till %d is ",n);
printf("\n%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