高精度运算类bign
来源:互联网 发布:福建广电网络集团副总 编辑:程序博客网 时间:2024/05/22 21:48
#ifndef BIGN_H_INCLUDED#define BIGN_H_INCLUDED#include <cstring>#include <iostream>#include <string>using namespace std;#define MAX_N 1000 //最大位数//大数struct bign { char s[MAX_N]; int len; bign() { memset(s, 0, sizeof(s)); len = 1; } bign(int num) { *this = num; } bign(const char *num) { *this = num; } bign operator = (const char *num) { len = strlen(num); for(int i=0; i<len; i++) { s[i] = num[len-1-i] - '0'; } return *this; } bign operator = (int num) { char s[MAX_N]; sprintf(s, "%d", num); *this = s; return *this; } bign operator + (const bign &b) const { bign c; int m = len > b.len ? len : b.len; int i, g, sum; for(i=0, g=0; g || i< m; i++) { sum = g; if(i < len) sum += s[i]; if(i < b.len) sum += b.s[i]; c.s[i] = sum%10; g = sum / 10; } c.len = i; return c; } bign operator += (const bign &b) { *this = *this + b; return *this; } bool operator < (const bign &b) const { if(b.len != len) return len < b.len; int i; for(i=len-1; i>=0; i--) { if(s[i] != b.s[i]) return s[i] < b.s[i]; } return false; } bool operator > (const bign &b) const { return b < *this;} bool operator <= (const bign &b) const {return !(*this > b);} bool operator >= (const bign &b) const {return !(*this < b);} bool operator != (const bign &b) const {return (*this < b) || (*this > b);} bool operator == (const bign &b) const {return !(*this < b) && !(*this > b);}};ostream& operator << (ostream& outstream, const bign& b){ for(int i=b.len-1; i>=0; i--) { outstream << (int)b.s[i] << ""; } return outstream;}istream& operator >> (istream& instream, bign& b){ string s; instream >> s; b = s.c_str(); return instream;}#endif // BIGN_H_INCLUDED