实现带符号的大数运算的+,-,*,/,mod以及最大公约数和模数的乘法逆元,参考了以前(不知道哪搜集到的)大数运算的代码实现并进行封装。
本人对C++理解不深,如有错误,欢迎指正!
ClassBigInteger.h
/**************************************************************************
Copyright:Xidian University
Author: bluefire1991
Date:2013-11-5
Description:Provide a Class for Computing BigInteger
**************************************************************************/
#ifndef CLASSBIGINT
#define CLASSBIGINT
#include <string>
class BigInteger
{
public:
BigInteger();
BigInteger(const BigInteger &);
BigInteger(std::string num1);
~BigInteger();
private:
std::string _num1;
public:
//静态方法
static int compare(std::string num1,std::string num2);//if num1>num2,return 1,else if num1=num2,return 0,else return -1;
static std::string add(std::string num1,std::string num2);//num1+num2
static std::string minus(std::string num1,std::string num2);//num1-num2
static std::string multiply(std::string num1,std::string num2);//num1*num2
static std::string divide(std::string num1,std::string num2,int floatpoint);//num1/num2
static std::string mod(std::string num1,std::string num2);//num1 mod num2
static std::string gcd(std::string num1,std::string num2);//gcd(num1,num2)
static std::string exgcd(std::string a,std::string b,std::string &x,std::string &y);//if gcd(a,b)=1,a*x+b*y=1,return gcd(a,b),x is inverse of a
//重载操作符
std::string getnumber() const;
BigInteger& operator+(const BigInteger&);//+
BigInteger& operator-(const BigInteger&);//-
BigInteger& operator*(const BigInteger&);//*
BigInteger& operator/(const BigInteger&);///
BigInteger& operator%(const BigInteger&);//mod
};
#endif CLASSBIGINT
ClassBigInteger.cpp
#include "ClassBigInteger.h"
BigInteger::BigInteger()
{
}
BigInteger::BigInteger(std::string num1):_num1(num1)
{
}
BigInteger::BigInteger(const BigInteger &bi)
{
_num1=bi._num1;
}
BigInteger::~BigInteger()
{
}
std::string BigInteger::getnumber() const
{
return _num1;
}
BigInteger& BigInteger::operator+(const BigInteger &bi)
{
_num1=add(_num1,bi._num1);
return *this;
}
BigInteger& BigInteger::operator-(const BigInteger &bi)
{
_num1=minus(_num1,bi._num1);
return *this;
}
BigInteger& BigInteger::operator*(const BigInteger &bi)
{
_num1=multiply(_num1,bi._num1);
return *this;
}
BigInteger& BigInteger::operator/(const BigInteger &bi)
{
_num1=divide(_num1,bi._num1,0);
return *this;
}
BigInteger& BigInteger::operator%(const BigInteger &bi)
{
_num1=mod(_num1,bi._num1);
return *this;
}
int BigInteger::compare(std::string number1,std::string number2)
{
if(number1[0]!='-'&&number2[0]!='-'){
int j;
int length1 = number1.size();
int length2 = number2.size();
if(number1.size() == 0)
number1 = "0";
if(number2.size() == 0)
number2 = "0";
j = 0;
for(int i = 0; i < length1;