Hat's Fibonacci

本文介绍了一种使用大整数处理方法来计算四阶斐波那契数列的算法。该算法通过递归加前四项来生成序列,并能够处理非常大的数值输入,适用于需要高精度计算的场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Description

A Fibonacci sequence is calculated by adding the previous two members the sequence, with the first two members being both 1.
F(1) = 1, F(2) = 1, F(3) = 1,F(4) = 1, F(n>4) = F(n - 1) + F(n-2) + F(n-3) + F(n-4)
Your task is to take a number as input, and print that Fibonacci number.
 

Input

Each line will contain an integers. Process to end of file.
 

Output

For each case, output the result in a line.
 

Sample Input

100
 

Sample Output

4203968145672990846840663646

#include<stdio.h>
#include<algorithm>
using namespace std;

struct bign{
 int num[2100];
 int len;
 bign(){
  for(int i=0;i<2100;i++)
  {
   num[i]=0;
  }
  len=0;
 }
};
bign x[5];
bign add(bign x,bign y){
 bign c;
 int flag=0,sum;
 int i;
 for(i=0;i<x.len||i<y.len;i++){
  sum=0;
  sum=x.num[i]+y.num[i]+flag;
  c.num[i]=sum%10;
  flag=sum/10;
 }
 c.len=max(x.len,y.len);
 if(flag!=0){
 c.num[i]=flag;
 c.len++;
 }
 return c;
}
bign add2(bign a,bign b,bign c,bign d){
 bign x,y;
 x=add(a,b);
 y=add(c,d);
 return add(x,y);
}
int main()
{
 int n;
 
 while(scanf("%d",&n)!=EOF)
 {
  for(int k=0;k<=3;k++){
   for(int i=0;i<=x[k].len;i++)
   x[k].num[i]=0;
   x[k].num[0]=1;
   x[k].len=1;
       }
  for(int i=5;i<=n;i++){
  x[4]=add2(x[0],x[1],x[2],x[3]);
  for(int i=0;i<4;i++){
   for(int j=0;j<x[i+1].len;j++)
  x[i].num[j]=x[i+1].num[j];
  x[i].len=x[i+1].len;
  }

  }
  for(int i=x[3].len-1;i>=0;i--)
  printf("%d",x[3].num[i]);
  printf("\n");
  }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值