Last active
December 19, 2015 17:28
-
-
Save bongtrop/5991144 to your computer and use it in GitHub Desktop.
Big Number add and multi
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#define OVERFLOW 2 | |
#define ROW b_len | |
#define COL a_len+b_len+OVERFLOW | |
using namespace std; | |
string add (string &s1, string &s2){ | |
int carry=0,sum,i; | |
string min=s1, | |
max=s2, | |
result = ""; | |
if (s1.length()>s2.length()){ | |
max = s1; | |
min = s2; | |
} else { | |
max = s2; | |
min = s1; | |
} | |
for (i = min.length()-1; i>=0; i--){ | |
sum = min[i] + max[i + max.length() - min.length()] + carry - 2*'0'; | |
carry = sum/10; | |
sum %=10; | |
result = (char)(sum + '0') + result; | |
} | |
i = max.length() - min.length()-1; | |
while (i>=0){ | |
sum = max[i] + carry - '0'; | |
carry = sum/10; | |
sum%=10; | |
result = (char)(sum + '0') + result; | |
i--; | |
} | |
if (carry!=0){ | |
result = (char)(carry + '0') + result; | |
} | |
return result; | |
} | |
int getCarry(int num) { | |
int carry = 0; | |
if(num>=10) { | |
while(num!=0) { | |
carry = num %10; | |
num = num/10; | |
} | |
} else carry = 0; | |
return carry; | |
} | |
int num(char a) { | |
return int(a)-48; | |
} | |
string mult(string a, string b) { | |
string ret; | |
int a_len = a.length(); | |
int b_len = b.length(); | |
int mat[ROW][COL]; | |
for(int i =0; i<ROW; ++i) { | |
for(int j=0; j<COL; ++j) { | |
mat[i][j] = 0; | |
} | |
} | |
int carry=0, n,x=a_len-1,y=b_len-1; | |
for(int i=0; i<ROW; ++i) { | |
x=a_len-1; | |
carry = 0; | |
for(int j=(COL-1)-i; j>=0; --j) { | |
if((x>=0)&&(y>=0)) { | |
n = (num(a[x])*num(b[y]))+carry; | |
mat[i][j] = n%10; | |
carry = getCarry(n); | |
} else if((x>=-1)&&(y>=-1)) mat[i][j] = carry; | |
x=x-1; | |
} | |
y=y-1; | |
} | |
carry = 0; | |
int sum_arr[COL]; | |
for(int i =0; i<COL; ++i) sum_arr[i] = 0; | |
for(int i=0; i<ROW; ++i) { | |
for(int j=COL-1; j>=0; --j) { | |
sum_arr[j] += (mat[i][j]); | |
} | |
} | |
int temp; | |
for(int i=COL-1; i>=0; --i) { | |
sum_arr[i] += carry; | |
temp = sum_arr[i]; | |
sum_arr[i] = sum_arr[i]%10; | |
carry = getCarry(temp); | |
} | |
for(int i=0; i<COL; ++i) { | |
ret.push_back(char(sum_arr[i]+48)); | |
} | |
while(ret[0]=='0'){ | |
ret = ret.substr(1,ret.length()-1); | |
} | |
return ret; | |
} | |
int main (){ | |
string a,b; | |
cin >> a >> b; | |
cout << "Add: " << add(a,b) << endl; | |
cout << "Multi: " << mult(a,b) << endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment