高精度加法和乘法
2015-08-22 20:39
316 查看
今天偶然看了一下某大神的模板,不经意翻到这个就顺便“借”了一下
上代码吧:
上代码吧:
[code]/* Date : 2015-8-21 晚上 Author : ITAK Motto : 今日的我要超越昨日的我,明日的我要胜过今日的我; 以创作出更好的代码为目标,不断地超越自己。 */ #include <iostream> #include <cstdio> #include <cstring> using namespace std; /** 如何用: 1、变量声明:可以给初值,如:BigInt ans=100; 可以不给初值(默认为0),如BigInt ans; 2、计算:可以连个BigInt对象相乘,相加;ans+ans*ans; 也可以和整数相乘相加,如:ans+78*ans; */ struct BigInt { const static int mod = 10000; const static int DLEN = 4; int a[600],len; BigInt() { memset(a,0,sizeof(a)); len = 1; } BigInt(int v) { memset(a,0,sizeof(a)); len = 0; do { a[len++] = v%mod; v /= mod; } while(v); } BigInt(const char *s) { memset(a,0,sizeof(a)); int L = strlen(s); len = L/DLEN; if(L%DLEN) len++; int index = 0; for(int i=L-1; i>=0; i-=DLEN) { int t = 0; int k = i-DLEN+1; if(k<0) k = 0; for(int j=k; j<=i; j++) t = t*10+s[j]-'0'; a[index++] = t; } } BigInt operator +(const BigInt &b)const { BigInt res; res.len = max(len,b.len); for(int i=0; i<=res.len; i++) { res.a[i] = 0; } for(int i=0; i<res.len; i++) { res.a[i] += ((i<len)?a[i]:0)+((i<b.len)?b.a[i]:0); res.a[i+1] += res.a[i]/mod; res.a[i] %= mod; } if(res.a[res.len]>0) res.len++; return res; } BigInt operator *(const BigInt &b)const { BigInt res; for(int i=0; i<len; i++) { int up = 0; for(int j=0; j<b.len; j++) { int temp = a[i]*b.a[j]+res.a[i+j]+up; res.a[i+j] = temp%mod; up = temp/mod; } if(up != 0) res.a[i+b.len] = up; } res.len = len+b.len; while(res.a[res.len-1]==0 && res.len>1)res.len--; return res; } void output() { printf("%d",a[len-1]); for(int i=len-2; i>=0; i--) printf("%04d",a[i]); printf("\n"); } };
相关文章推荐
- C++设计模式——组合模式
- Solr 查询参数
- 给定一棵二叉树,创建含有某一深度上所有结点的链表
- OC分数作业
- Java字符串操作、基本运算方法等优化策略
- 解决Android SDK Manager下载速度慢的方法
- A1015. Reversible Primes (20)
- bash变量-数值运算与运算符/变量测试与内容替换/环境变量配置文件
- Matlab中函数句柄@的作用及介绍
- Java 注解的简单学习与应用 Annotation
- 对网上文档中表格的操作
- ssh界面传对象到controller-页面和controller代码
- delegate
- java.lang.ClassNotFoundException: oracle.jdbc.driver.OracleDriver
- LeetCode(4)Median of Two Sorted Arrays
- NBUT 1452 Ezreal
- css--960框架
- LeetCode(4)Median of Two Sorted Arrays
- bash变量-位置参数与预定义变量
- poj2388 排序