c++ 大數加法 乘法 除法 (模板)
阿新 • • 發佈:2018-11-11
#include <cstdio> #include <cstring> #include <algorithm> #include <cstdlib> #include <string> #include <iostream> #include <utility> #include <cstdio> const int N = 100009; using namespace std; string ans[110]; char str[N]; struct Node { int d[N]; int len; Node() {memset(d, 0, sizeof(d));len=1;} Node(char *s) { memset(d, 0, sizeof(d)); len = strlen(s); int i = 0; while(s[i] != '\0') { d[len-i-1] = s[i] - '0'; ++i; } } int cmp(const Node &t) { int l = this->len - t.len; if(l < 0) return -1; int i; for(i=t.len-1;i>=0;i--) { if(this->d[i+l] < t.d[i]) break; else if(this->d[i+l] > t.d[i]) { return l; } } if(i < 0) return l; return l-1; } void change(int pos) { this->d[pos] += 1; int i = pos; while(this->d[i] > 9) { this->d[i] -= 10; this->d[i+1]++; ++i; } if(i+1 > this->len) this->len = i+1; } Node operator / (const Node &t) { Node ans; while(1) { int p = this->cmp(t); if(p == -1) break; else { ans.change(p); for(int i=0;i<t.len;i++) { this->d[i+p+1]--; this->d[i+p] = this->d[i+p]+10-t.d[i]; if(this->d[i+p] > 9) { this->d[i+p] -= 10; this->d[i+1+p]++; } } while(this->len > 1 && this->d[this->len - 1] == 0) this->len--; } } return ans; } }; string sum(string s1,string s2) //大數加法 { if(s1.length()<s2.length()) { string temp=s1; s1=s2; s2=temp; } int i,j; for(i=s1.length()-1,j=s2.length()-1;i>=0;i--,j--) { s1[i]=char(s1[i]+(j>=0?s2[j]-'0':0)); //注意細節 if(s1[i]-'0'>=10) { s1[i]=char((s1[i]-'0')%10+'0'); if(i) s1[i-1]++; else s1='1'+s1; } } return s1; } string Mult(string s,int x) //大數乘以整形數 { reverse(s.begin(),s.end()); int cmp=0; for(int i=0;i<s.size();i++) { cmp=(s[i]-'0')*x+cmp; s[i]=(cmp%10+'0'); cmp/=10; } while(cmp) { s+=(cmp%10+'0'); cmp/=10; } reverse(s.begin(),s.end()); return s; } string Multfa(string x,string y) //大數乘法 { string ans; for(int i=y.size()-1,j=0;i>=0;i--,j++) { string tmp=Mult(x,y[i]-'0'); for(int k=0;k<j;k++) tmp+='0'; ans=sum(ans,tmp); } return ans; } void chu(string xx,string yy) { char x[9999],y[9999]; for(int k=0;k<xx.size();k++) x[k]=xx[k]; for(int k=0;k<yy.size();k++) y[k]=yy[k]; strcpy(str,x); Node a(str); strcpy(str,y); Node b(str); Node ans = a / b; int e=0;char ss[9999]; for(int i=ans.len-1;i>=0;i--)//商 ss[e++]=ans.d[i]+'0'; ss[e]=0; puts(ss); return ; } int main() { string a,b; cin>>a>>b; cout<<Multfa(a,b)<<endl;//乘法 chu(a,b);//除法 cout<<sum(a,b)<<endl;//加法 return 0; }