您的位置:首页 > 产品设计 > UI/UE

Fibonacci sequence of k order

2012-09-05 22:39 260 查看
The Fibonacci Number  that are defined recursively as below:   f0=0 , f1=0 , …, fk-2=0 , fk-1=1,   fn = fn-1 + fn-2 +…+ fn-k      (n=k,k+1,…)
Please write a program that lists n+1 items of Fibonacci Number of k order(f0, f1 , f2 ,… fn )  using circular queue,satisfying that fn ≤max and fn+1 >max ,where max is a given constant(Note the capacity of the circular queue is k, the numbers left in the circular queue after running the program is the last k numbers fn-k+1 ,… fn ) .
Let the capacity of the circular queue be k +1, and use the following formula: 
fi+1 = 2*fi - fi-k 
do the same problem.
 

#include<stdio.h>
#include <stdlib.h>

#define MAXNUMBER 100

struct CircleQueue
{
int elem[MAXNUMBER];
int rear;
};

struct CircleQueue *cq;

int main()
{
void fb(int, int);  //the prototype of the function
int k;
int max;

cq = (struct CircleQueue *) malloc(sizeof(struct CircleQueue));
if (cq == (struct CircleQueue *) NULL)  /* check the address */
{
printf("\nCould not allocate the requested space\n");
exit(1);
}

printf("Please enter the order of Fibonacci sequence:");
scanf("%d",&k);
printf("\nPlease enter a max number:");
scanf("%d",&max);

fb(k, max);

return 0;
}

//this function is for create a fibonacci sequence
void fb(int k, int max)
{
int f[MAXNUMBER];
int i, n, j;

//evaluate front k-2 numbers of the fibonacci sequence
for(i=0;i<=k-2;i++)
{
f[i]=0;
cq->elem[i]=0;
}

cq->elem[k-1]= cq->elem[k]= 1;
cq->rear=k;
n=k+1;
f[k-1]=f[k]=1;

//this loop is for evaluating numbers continuously
while(cq->elem[cq->rear]<=max)
{
j= (cq->rear+1)%(k+1);
f
= cq->elem[cq->rear]*2-cq->elem[j];
cq->elem[j]=f
;
cq->rear=j;
n++;
}

if(cq->elem[cq->rear]>max)
{
n=n-2;
}

if (max==0)
{
n=k-2;
}

printf("\nThe Fibonacci sequence is:\n");
for(i=0;i<=n;i++)
{
printf("f[%d] is %d\n", i, f[i]);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: