求斐波拉契数列的任一项(如:第110项)

#include<iostream>
using namespace std;

void Fibonacci(int n)
{
    if (n == 1 || n == 2)
    {
        cout << 1 << endl;
    }
    else
    {
        int *f1 = new int[1];
        f1[0] = 1;
        int lenf1=1;

        int *f2 = new int[1];
        f2[0] = 1;
        int lenf2=1;
        int *temp;
        int count;

    for (int i = 3; i <= n; i++)
    {
        int cn = 0;
        int vw = 0;
        count=lenf2+1;
        temp=new int[count];
        temp[0]=0;
        int count1=count;
        int num1=lenf1;
        int num2=lenf2;
        vw = f1[num1 - 1] + f2[num2 - 1] + cn;
        cn = vw / 10;
        temp[count1 - 1] = vw % 10;
        count1--;
        num1--;
        num2--;
    while (num2>=0)
    {
        if(num2==0&&num1==0&&cn!=0)
        {
            vw=cn;
            temp[count1 - 1] = vw % 10;
            count1--;
            num2--;
        }

        else if(num2>0&&num1==0&&cn==0)
        {
            temp[count1 - 1] = f2[num2-1];
            count1--;
            num2--;
        }
      else if(num2>0&&num1==0&&cn!=0)
       {
        vw = f2[num2 - 1]+ cn;
        cn = vw / 10;
        temp[count1 - 1] = vw % 10;
        count1--;
        num2--;
        }
     else if(num2==0&&num1==0&&cn==0)
     {
        break;
     }

        else
        {
        vw = f1[num1 - 1] + f2[num2 - 1] + cn;
        cn = vw / 10;
        temp[count1 - 1] = vw % 10;
        count1--;
        num1--;
        num2--;
        }
    }


    f1 = new int[lenf2];
    for (int j = 0; j < lenf2; j++)
    {
        f1[j] = f2[j];
    }


    if(temp[0]==0)
    {
        f2 = new int[count-1];
        for (int k = 0; k <count-1; k++)
        {
            f2[k]=temp[k+1];
        }
}


    else
    {
        f2 = new int[count];
        for (int k = 0; k <count ; k++)
        {
            f2[k] = temp[k];
        }

    }

      lenf1=lenf2;
      if(temp[0]==0)
      {
        lenf2=count-1;
      }
      else
      {
        lenf2=count;
      }
    }


    if(temp[0]==0)
    {
        for(int j=1;j<count;j++)
        {
            cout<<temp[j];
        }
    }
    else
    {
        for(int j=0;j<count;j++)
        {
            cout<<temp[j];
        }
    }
    cout << endl;
    delete []f1;
    delete[]f2;
    delete[]temp;
    }
}

int main()
{
    int n;
    while(cin >> n)
    {
        Fibonacci(n);
    }
    return 0;
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值