برنامه ضرب و جمع اعداد بزرگ
پنجشنبه, ۱۸ خرداد ۱۳۹۶، ۱۱:۵۶ ب.ظ
#include "stdafx.h"
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
class l_int
{
vector <int> vec;
protected:
void fix(l_int & temp)
{
if(vec.size()<temp.vec.size())
for(int i=vec.size();i<temp.vec.size();i++)
vec.push_back(0);
else if(vec.size()>temp.vec.size())
for(int i=temp.vec.size();i<vec.size();i++)
temp.vec.push_back(0);
}
void zero(l_int & temp)
{
for(int i=0;i<temp.vec.size();i++)
temp.vec.at(i)=0;
}
public:
l_int(const string txt="0")
{
vec.resize(txt.length());
for(int i=0;i<txt.length();i++)
vec.at(i)=txt[txt.length()-1-i]-48;
}
l_int(l_int &temp )
{
/*
vec.resize(temp.vec.size());
for(int i=0;i<temp.vec.size();i++)
vec.at(i)=temp.vec.at(i);
*/
vec.reserve(temp.vec.size());
copy(temp.vec.begin(),temp.vec.end(),back_inserter(vec));
}
~l_int()
{
vec.clear();
}
l_int operator + (l_int &temp)
{
fix(temp);
l_int Sum;
Sum.vec.resize(vec.size());
zero(Sum);
int sum=0;
for(int i=0;i<vec.size();i++)
{
Sum.vec.at(i)= ( vec.at(i) + temp.vec.at(i) +sum) %10;
sum=( vec.at(i) + temp.vec.at(i) +sum ) /10;
if(i==vec.size()-1 && sum>0)
Sum.vec.at(vec.size())=sum;
}
return Sum;
}
l_int operator *(l_int &temp)
{
vec.push_back(0);
temp.vec.push_back(0);
int sum;
l_int Mult;
Mult.vec.resize(temp.vec.size()+vec.size());
zero(Mult);
for(int i=0;i<temp.vec.size();i++)
{
sum=0;
for(int j=0;j<vec.size();j++)
{
Mult.vec.at(i+j)+=(vec.at(j)*temp.vec.at(i)+sum)%10;
if(Mult.vec.at(i+j)>9)
{
Mult.vec.at(i+j)=Mult.vec.at(i+j)%10;
Mult.vec.at(i+j+1)++;
}
sum=(vec.at(j)*temp.vec.at(i)+sum)/10;
}
}
return Mult;
}
l_int& operator =(const l_int &temp)
{
vec.resize(temp.vec.size());
for(int i=0;i<temp.vec.size();i++)
vec.at(i)=temp.vec.at(i);
return *this;
}
l_int& operator =(const string txt)
{
vec.resize(txt.length());
for(int i = 0 ; i<vec.size() ;i++)
vec.at(i)=txt[txt.length()-1-i]-48;
return *this;
}
friend ostream& operator <<(ostream &out,l_int &temp);
friend istream& operator >>(istream &in,l_int &temp);
};
ostream& operator <<(ostream &out,l_int &temp)
{
bool Check=false;
for(int i=temp.vec.size()-1;i>=0;i--)
if(temp.vec.at(i)>0 || Check==true)
{
cout<<temp.vec.at(i);
Check=true;
}
if(Check==false)
cout<<"0";
return out;
}
istream& operator >>(istream &in,l_int &temp)
{
string txt;
cin>>txt;
temp.vec.resize(txt.length());
for(int i = 0 ; i<temp.vec.size() ;i++)
temp.vec.at(i)=txt[txt.length()-1-i]-48;
return in;
}
int _tmain(int argc, _TCHAR* argv[])
{
l_int A="20";
l_int B="10";
//cin>>A>>B;
//A="5";
l_int C;
l_int D;
C=A+B;
D=A*B;
cout<<"A+B:"<<C<<endl;
cout<<"A*B:"<<D<<endl;
system("pause");
return 0;
}
- ۹۶/۰۳/۱۸