高精度求助
  • 板块学术版
  • 楼主Alorithm
  • 当前回复2
  • 已保存回复2
  • 发布时间2022/9/27 16:58
  • 上次更新2023/10/27 09:46:33
查看原帖
高精度求助
736738
Alorithm楼主2022/9/27 16:58

写的高精度模板把A+B和A×B给过了,可是写阶乘之和用同个模板却过不了,求各位巨佬看一下代码

#include<iostream>
#include<string>
using namespace std;

class hp
{
	private:
		int num[100001];
	public:
		hp(); //
		hp(int); //
		hp(string); //
		
		hp operator+(const hp &) const; //
		hp operator-(const hp &) const;
		hp operator*(const hp &) const;
		hp operator/(const hp &) const;
		
		hp operator=(const hp &); //
		hp operator=(const int &); //
		hp operator=(const string &); //
		
		bool operator>(const hp &) const;
		bool operator<(const hp &) const;
		bool operator==(const hp &) const;
		
		friend ostream & operator<<(ostream &,hp &); //
		friend istream & operator>>(istream &,hp &); //
};

hp::hp()
{
	num[0]=1;
}

hp::hp(int a)
{
	num[0]=0;
	do
	{
		num[++num[0]]=a%10;
		a/=10;
	}while(a);
}

hp::hp(string a)
{
	num[0]=a.length();
	for(int i=1;i<=num[0];i++)
		num[i]=a[num[0]-i]-'0';
}

hp hp::operator=(const hp &a)
{
	num[0]=a.num[0];
	for(int i=1;i<=num[0];i++)
		num[i]=a.num[i];
	return *this;
 } 
 
hp hp::operator=(const int &a)
{
	*this=hp(a);
	return *this;
}

hp hp::operator=(const string &a)
{
	*this=hp(a);
	return *this;
}

ostream &operator<<(ostream &os,hp &a)
{
	for(int i=a.num[0];i>=1;i--)
		os<<a.num[i];
	return os;
}

istream &operator>>(istream &is,hp &a)
{
	string b;
	is>>b;
	a=hp(b);
	return is;
}

hp hp::operator+(const hp &a) const
{
	hp w;
	w.num[0]=max(num[0],a.num[0]);
	for(int i=1;i<=w.num[0];i++)
	{
		w.num[i]+=num[i]+a.num[i];
		w.num[i+1]+=w.num[i]/10;
		w.num[i]%=10;
	}
	while(w.num[w.num[0]+1])
		w.num[0]++;
	return w;
}

hp hp::operator*(const hp &a) const
{
	hp w;
	for(int i=1;i<=num[0];i++)
		for(int j=1;j<=a.num[0];j++)
		{
			w.num[i+j-1]+=num[i]*a.num[j];
			w.num[i+j]+=w.num[i+j-1]/10;
			w.num[i+j-1]%=10;
		}
	w.num[0]=num[0]+a.num[0];
	while(w.num[w.num[0]]==0 && w.num[0]>1)
		w.num[0]--;
	return w;
}

int n;
hp ans,f=1;

int main()
{
	cin>>n;
	for(int i=1;i<=n;i++)
	{
		f=f*hp(i);
		ans=ans+f;
	}
	cout<<ans;
	return 0;
 } 
2022/9/27 16:58
加载中...