string addBitStrings( string first, string second ) { string result; // To store the sum bits // make the lengths same before adding int length = makeEqualLength(first, second); int carry = 0; // Initialize carry // Add all bits one by one for (int i = length-1 ; i >= 0 ; i--) { int firstBit = first.at(i) - '0'; int secondBit = second.at(i) - '0'; // boolean expression for sum of 3 bits int sum = (firstBit ^ secondBit ^ carry)+'0'; result = (char)sum + result; // boolean expression for 3-bit addition carry = (firstBit&secondBit) | (secondBit&carry) | (firstBit&carry); } // if overflow, then add a leading 1 if (carry) result = '1' + result; return result; }
InfInt karatsubaMult(string x, string y) { InfInt *result = new InfInt(0); int m = makeEqualLength(x, y); if(m == 0) return *result; size_t sz = 0; if( x.length() == 1 || y.length() == 1 ) { result = new InfInt(stoull(x, &sz, 0) * stoull(y, &sz, 0)); return *result; } // m2 + m2Rest = m int m2 = m/2; int m2Rest = m - m2; string xl = x.substr(0, m2); string xr = x.substr(m2, m2Rest); string yl = y.substr(0, m2); string yr = y.substr(m2, m2Rest); InfInt z0 = karatsubaMult(xr, yr); InfInt z1 = karatsubaMult(add(xl, xr), add(yl, yr)); InfInt z2 = karatsubaMult(xl, yl); *result = (z2 * basePower(*INFINTBASE10, 2*m2) + ((z1-z2-z0) * basePower(*INFINTBASE10, m2)) + z0); return *result; }
char *addBitStrings(char *n1,char *n2) { makeEqualLength(n1,n2); // puts(n1); // puts(n2); int length = strlen(n1); char *result = malloc(length + 2); strcpy(result,""); int carry = 0; for(int i = length - 1;i >= 0; --i) { int first_bit = n1[i] - '0'; int second_bit = n2[i] - '0'; int sum = (first_bit ^ second_bit ^ carry) + '0'; char t[] = {sum,'\0'}; char *temp = malloc(length + 1); strcpy(temp,""); strcat(temp,t); strcat(temp,result); strcpy(result,temp); carry = (first_bit & second_bit) | (second_bit & carry) | (first_bit & carry); } if(carry) { char *temp = malloc(length + 1); strcpy(temp,""); strcat(temp,"1"); strcat(temp,result); strcpy(result,temp); } return result; }