4阶斐波那契序列如下:f0=f1=f2=0, f3=1,…,fi=fi-1+fi-2+fi-3+fi-4,
利用容量为k=4的循环队列,构造序列的前n+1项(f0, f1 , f2 ,… fn ),要求满足fn ≤200而fn+1 >200。
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 4
typedef struct {
int *base;
int front;
int rear;
int length;
}SqQueue;
SqQueue* InitQueue(){
SqQueue *Q = (SqQueue*)malloc(sizeof(SqQueue));
Q->base = (int*)malloc(sizeof(int)*MAXSIZE);
if(!Q->base)
exit(0);
Q->front = 0;
Q->rear = 0;
Q->length = 0;
return Q;
}
void EnQueue(SqQueue *Q, int e){
if(Q->length >= MAXSIZE) return ; //队列已满
Q->base[Q->rear] = e;
Q->rear = (Q->rear+1) % MAXSIZE;
Q->length++;
}
int Delete(SqQueue *Q){
if(Q->length == 0) return 0;//队列为空
int e = Q->base[Q->front];
Q->front = (Q->front+1) % MAXSIZE;
Q->length--;
return e;
}
int Fib_4(SqQueue *Q, int n){
if(n < 0) return -1;
if(n < 3) return 0;
if(n == 3) return 1;
int cnt = 1;
int temp = 0;
while(cnt <= n-3){
temp = Q->base[0] + Q->base[1] + Q->base[2] + Q->base[3];
Delete(Q);
EnQueue(Q, temp);
cnt++;
}
return temp;
}
int Fib_4_digui(int n){ //不采用队列,用递归实现
if(n < 0) return -1;
if(n < 3) return 0;
if(n == 3) return 1;
return (Fib_4_digui(n-1) + Fib_4_digui(n-2) + Fib_4_digui(n-3) + Fib_4_digui(n-4));
}
int main()
{
/* int n = 0;
while(Fib_4_digui(n-1) < 200){
printf("Fib_4_dugui(%d)=%d
", n, Fib_4_digui(n));
n++;
}*/
SqQueue *Q = InitQueue();
EnQueue(Q, 0);
EnQueue(Q, 0);
EnQueue(Q, 0);
EnQueue(Q, 1);
int temp = 0;
printf("0 0 0 1");
while(temp <= 200){
temp = Q->base[0]+Q->base[1]+Q->base[2]+Q->base[3];
printf(" %d", temp);
Delete(Q);
EnQueue(Q, temp);
}
return 0;
}