PE 25 1000-digit Fibonacci number

寻找斐波那契数列第1000位的索引
本文介绍了一个通过使用C++编程实现斐波那契数列的方法,并通过迭代计算找到了数列中第1000位的索引。
#include <iostream>
#include <list>

typedef char Digit;

class BigInt
{
public:
	BigInt () { };
	BigInt (unsigned int i);
	BigInt (const char* i);
	BigInt operator+ (const BigInt& big);
	int size() const { return number.size(); }
	
private:
	std::list<Digit> number;
};

BigInt::BigInt (unsigned int i)
{
    while (i) { number.push_front (i % 10); i/=10; }
}

BigInt::BigInt (const char* i)
{
    for(const char* it=i;*it != 0; it++)
		number.push_back(*it-'0');
}

BigInt
BigInt::operator+ (const BigInt& big)
{
    char carry = 0;
    char tmp;
    BigInt result;
    std::list<Digit>::reverse_iterator it;
    std::list<Digit>::const_reverse_iterator it2;
    for (it = number.rbegin(), it2 = big.number.rbegin();
	it != number.rend() || it2 != big.number.rend();
	it != number.rend() ? it++ : it, it2 != big.number.rend() ? it2++ : it2)
    {
        tmp = (it != number.rend() ? *it:0) +
			(it2 != big.number.rend() ? *it2:0) +
			carry;
        if (tmp > 9)
        {
            tmp = tmp - 10;
            carry = 1;
        }
        else
        {
            carry = 0;
        }
        result.number.push_front(tmp);
    }
    if (carry) result.number.push_front(1);
    return result;
}

int main(void)
{
    BigInt prev2 = 1;
    BigInt prev1 = 1;
    BigInt current = prev1 + prev2;
    int term = 3;
	
    while (current.size() != 1000)
    {
        term++;
        prev2 = prev1;
        prev1 = current;
        current = prev1 + prev2;
    }
	
    std::cout << "Solution:" << term << std::endl;
	return 0;
}



Answer:
4782

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值