探寻C/C++中更快的大数(自然数集)模板

本文系fcbruce个人原创整理,转载请注明出处http://blog.csdn.net/u012965890/article/details/40432511,谢谢!


我们知道在C/C++中int型可处理-2^31~2^31-1(32位及以上编译器),long long型可处理-2^63~2^63-1的数据,这实际上是非常有限的,在很多情况下,我们往往会处理范围更大的数据。Java中有BigInteger类,python中想要多大就有多大(取决于内存),但是C/C++就显得有些乏力,这时候我们会手写大数类,用一个数组记录一个数,来模拟竖式计算。通常我们会一位一位地储存数据,这样易于实现,逻辑清晰,方便理解,但是一定程度上牺牲了效率,浪费了资源,那么能否多位存储数据并操作呢,显然是可以的。


我们知道int类型能表示的最大数量级为10^9左右,为了避免乘法溢出,我们不妨用一个int存储4位数字(10^4),可以轻易写下如下代码(仅含加、减、乘和比较操作):

/*
 *
 * Author : fcbruce <[email protected]>
 *
 * Time : Fri 24 Oct 2014 02:43:41 PM CST
 *
 */
#include <cstdio>
#include <iostream>
#include <sstream>
#include <cstdlib>
#include <algorithm>
#include <ctime>
#include <cctype>
#include <cmath>
#include <string>
#include <cstring>
#include <stack>
#include <queue>
#include <list>
#include <vector>
#include <map>
#include <set>
#define sqr(x) ((x)*(x))
#define LL long long
#define itn int
#define INF 0x3f3f3f3f
#define PI 3.1415926535897932384626
#define eps 1e-10

#ifdef _WIN32
  #define lld "%I64d"
#else
  #define lld "%lld"
#endif

#define maxm 
#define maxn 

using namespace std;

const int maxl = 233;
struct bign
{
  static int width;
  static int mod;
  int len,s[maxl];

  bign()
  {
    memset(s,0,sizeof s);
    len=1;
  }

  bign(int num)
  {
    *this=num;
  }

  bign(long long num)
  {
    *this=num;
  }

  bign(const char *s)
  {
    *this=s;
  }

  bign operator = (int num)
  {
    char s[maxl];
    sprintf(s,"%d",num);
    *this=s;
    return *this;
  }

  bign operator = (long long num)
  {
    char s[maxl];
    sprintf(s,lld,num);
    *this=s;
    return *this;
  }

  bign operator = (const char *s)
  {
    int l=strlen(s);
    len=0;
    for (int i=l-1;i>=0;i-=width,len++)
    {
      (*this).s[len]=0;
      for (int j=max(0,i-width+1);j<=i;j++)
        (*this).s[len]=(*this).s[len]*10+s[j]-'0'
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值