Fibonacci数列第n项

简介

斐波那契数列指的是这样一个数列 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ...

特别指出:第0项是0,第1项是第一个1。

这个数列从第二项开始,每一项都等于前两项之和。

斐波那契数列的发明者,是意大利数学家列昂纳多·斐波那契(Leonardo Fibonacci)

输出其中第N项的方法

方法1

#include <iostream>
using namespace std;


class Fibonacci{
    public:
            Fibonacci(void):first(0), second(1){}
            int getElement(const int &n);
    private:
            const int first;
            const int second;
};

int Fibonacci::getElement(const int &n){
    if(0 == n)
        return first;
    if(1 == n)
        return second;
    int prev   = prev;
    int curr   = second;
    int cnt  = n - 1;
    while(cnt--){
            int record = curr;
            curr = prev + record;
            prev = record;
    }
    return curr;
}

方法2

#include <iostream>
using namespace std;


class Fibonacci{
    public:
            Fibonacci(void):first(0), second(1){}
            int getElement(const int &n);
    private:
            const int first;
            const int second;
};

int Fibonacci::getElement(const int &n){
    if(0 == n)
        return first;
    if(1 == n)
        return second;
    return (getElement(n - 1) + getElement(n -2));
}






转载于:https://my.oschina.net/u/572632/blog/287362

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值