Generate Fibonacci sequence

Introduction to the Fibonacci sequence

  1. In the Fibonacci sequence, except that the first and second numbers are 1, the subsequent numbers are the sum of the previous two numbers;
  2. Mathematically expressed as: F(0)=1, F(1)=1; N>=2; F(N) = F(N-1)+F(N-2);
  3. The resulting Fibonacci sequence is as follows:
    1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, …

Code

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <string>
#include <iostream>
#include <vector>

using namespace std;
/************************************************************************/
/* 生成斐波拉契数列,seq输入必须是空的vector,count是需要产生的数列长度;
产生的数列保存在seq中,运行正常返回实际产生的数列长度,异常返回0*/
/************************************************************************/
unsigned Fibonacci_Seq_Gen(vector<long long> &seq, unsigned count)
{
    unsigned idx = 2;
    long long tempNum = 0;

    if(count <= 2)
    {
        cout<<"The input parameter is illegal"<<endl;
        return 0;
    }

    seq.push_back(1);
    seq.push_back(1);
    do 
    {
        tempNum = seq[idx-1]+seq[idx-2];
        seq.push_back(tempNum);
        idx++;
    } while (idx<count);

    return count;
}

int main(int argc, char* argv[])
{
    //vector元素类型为long long,因为unsigned很容易就越界;
    vector<long long> seq;
    cout<<"The Fibonacci_Seq_Gen out:"<<Fibonacci_Seq_Gen(seq, 50)<<endl;

    for(int i = 0;i<seq.size();i++)
    {
        cout<<seq[i]<<endl;
    }
    return 0;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325628683&siteId=291194637