之前也写过输出斐波那契数的程序,当然也只是前几十位。所以也没注意到当输出大于47位之后 ,就发生溢出了。直到某一天,老师让我们输出47位之后的数我才发现这个问题。于是就花了一点时间写了出来。
其实这个问题归根到底就是一个大数相加的问题,当然网上也能搜到很多关于大于数加减乘除的模版。我现在就换另外一种方法来计算大数相加的问题。思路就是分别用两个字符串来保存两个数,然后对应位分别相加,满10进1,就行了。理论上是没有上限的(不会溢出),但受计算机的限制,在我自己的电脑上也只能输出几万项斐波那契数。不多说,上代码。
//定义了一个大数类
#ifndef BIGNUM_H
#define BIGNUM_H
#include <iostream>
using namespace std;
class BigNum
{
private:
string num;
int length;
public:
BigNum()
:num("NULL")
,length(0)
{}
BigNum(string &n)
:num(n)
,length(n.size())
{}
BigNum(string n,int l)
:num(n)
,length(l)
{}
void getNum() const;
const void clear();
const BigNum &operator +(const BigNum & n);
const BigNum &operator =(const BigNum & n);
};
#endif // BIGNUM_H
#include "bignum.h"
using namespace std;
void BigNum::getNum()const
{
cout<<num<<" "<<length<<endl;
}
const void BigNum::clear()
{
num.clear();
length = 0;
}
const BigNum &BigNum::operator =(const BigNum & n)
{
num = n.num;
length = n.length;
return *this;
}
const BigNum &BigNum::operator +(const BigNum & n)
{
// num += n.num;
// length +=n.length;
// return *this;
BigNum maxNum = n ,minNum = *this,sumNum;
sumNum.num.clear();
int temp;
int reamain = 0;
if(length > n.length)
{
maxNum = *this;
minNum = n;
}
// cout<<endl; cout<<endl;
// maxNum.getNum();
// minNum.getNum();
// cout<<endl;
int maxLen = maxNum.length - 1,minLen = minNum.length - 1;
for(int i = 0; i < minNum.length; i++)
{
temp = (maxNum.num[maxLen] - '0') + (minNum.num[minLen] - '0') + reamain;
sumNum.num += (temp % 10 + '0');
reamain = temp / 10;
maxLen --;
minLen --;
sumNum.length ++;
// cout<<"r1 = "<<reamain<<" ";
// sumNum.getNum();
}
//cout<<" maxLen = "<<maxLen<<
// " minLen = "<<minLen<<
// " reamain = "<<reamain<<
// " temp = "<<temp<<endl;
// cout<<"---------"<<endl;
for(int j = maxLen; j >= 0; j--)
{
temp = maxNum.num[j] - '0' + reamain;
sumNum.num += temp % 10 + '0';
reamain = temp / 10 ;
sumNum.length ++;
//cout<<"r2 = "<<reamain<<" ";
// sumNum.getNum();
}
//cout<<endl<<"---------"<<endl;
if(reamain != 0)
{
sumNum.num += (reamain + '0');
sumNum.length++;
// cout<<"r3 = "<<reamain<<" ";
}
// cout<<endl;
string s(sumNum.num.rbegin(),sumNum.num.rend());
num = s;
length = sumNum.length;
return *this;
}
#include <iostream>
#include "bignum.h"
using namespace std;
void Swap(BigNum &a, BigNum &b)
{
BigNum temp;
temp = a;
a = b;
b = temp;
}
const BigNum &Fibonacci(int n, BigNum &temp)
{
BigNum a("1",1);
BigNum b("1",1);
temp.clear();
// a.getNum();
// cout<<"==========";
for(int i = 3; i <= n; i++)
{
a + b;
temp = a;
Swap(a,b);
// cout<<"a = ";
// a.getNum();
// cout<<"b = ";
//b.getNum();
}
// cout<<"=========="<<endl;
return temp;
}
int main()
{
int num;
BigNum f;
for(;;)
{
cout<<"input:";
cin>>num;
cout<<endl;
if(num == 1 || num == 2)
{
cout<<"the num is: "<<1<<endl;
}
else
{
f = Fibonacci(num,f);
cout<<"the num is: ";
f.getNum();
cout<<endl;
}
}
return 0;
}