Trouble with the carry over when adding 2 arrays together - c++

I'm writing a program that adds two large integers (up to 20 digits) together. I've had no problems so far in storing the two numbers as strings then sorting them into two arrays.
So far, I have half of the addition part working. When the sum of the two digits does not exceed double digits, it works fine.
The issue arises when the sum of the arrays hits double digits. I'm trying to work in the carry over, but it messes with the digits (adding in where it shouldn't.) In addition to that, I'm not sure how to get the carry to appear ahead of the final digits. For example: 9+9 outputs to 8.
Here's my code (please excuse all the letter variables in the for loops.)
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str1;
string str2;
int array1[20];
int array2[20];
int array3[20];
string num3[20];
int i;
int j = 0;
int k;
int l;
int m = 0;
int n;
int o;
int carry = 0;
cout<<"Please enter the first number: "<<endl;
cin>>str1;
for (int i = str1.length() - 1; i >= 0; i--)
{
array1[j] = str1[i];
j++;
}
for (int k = str1.length()-1; k >=0; k--)
{
array1[k] = static_cast<int>(str1[k]) - static_cast<int>('0');
}
cout<<"Please enter the second number: "<<endl;
cin>>str2;
for (int l = str2.length() - 1; l >= 0; l--)
{
array2[m] = str2[l];
m++;
}
for (int n = str2.length()-1; n >=0; n--)
{
array2[n] = static_cast<int>(str2[n]) - static_cast<int>('0');
}
//Where the addition begins
for (int o = 0; o < str1.length(); o++)
{
if (array1[o] + array2[o] > 9)
{
array3[o] = array1[o] + array2[o] + carry;
array3[o] = array3[o] % 10;
carry = 1;
}
else
{
array3[o] = array1[o] + array2[o] + carry;
carry = 0;
}
cout<<array3[o];
}
return 0;
}
I think one thing I have to fix is how this line of code works:
array3[o] = array3[o] % 10;
Which keeps a second digit from appearing in the output. I would imagine if I disabled it once we reach the final numbers in the arrays, it would allow the final carry to show up. Unfortunately, everything I've tried hasn't worked.
Again, thank you!

Try this:
for (int o = 0; o < str1.length(); o++)
{
if (array1[o] + array2[o] + carry > 9)
{
array3[o] = array1[o] + array2[o] + carry;
array3[o] = array3[o] % 10;
carry = 1;
}
else
{
array3[o] = array1[o] + array2[o] + carry;
carry = 0;
}
cout<<array3[o];
}

Modify your for loop for Addition. In condition you need to add carry also
if (array1[o] + array2[o] + carry > 9)
The final for loop will be as below:
for (int o = 0; o < str1.length(); o++)
{
if (array1[o] + array2[o] + carry > 9)
{
array3[o] = array1[o] + array2[o] + carry;
array3[o] = array3[o] % 10;
carry = 1;
}
else
{
array3[o] = array1[o] + array2[o] + carry;
carry = 0;
}
cout<<array3[o];
}

My suggestions:
You can fill up the numbers from the input string in one loop. No need to use two loops.
for (int i = str1.length() - 1; i >= 0; i--)
{
array1[j] = str1[i] - '0';
j++;
}
Similarly for the other loop.
When computing the total you have iterate until the length of the longest string. If the first input is 12 and the second input is 4567, you have to make sure that your iteration stops at 4, not at 2.
The algorithm for computing the sum can be simplified to:
for (int o = 0; o < len+1; o++)
{
array3[o] = array1[o] + array2[o] + carry;
carry = array3[o]/10;
array3[o] %= 10;
}
where len is the maximum of the lengths.
Here's the final code I came up with:
#include <iostream>
#include <string>
using namespace std;
void printNumber(int array[])
{
// Skip the leading zeros.
int i = 19;
for ( ; i >= 0; i-- )
{
if ( array[i] > 0 )
{
break;
}
}
for ( ; i >= 0; i--)
{
cout << array[i];
}
}
int main()
{
string str1;
string str2;
int array1[20] = {0};
int array2[20] = {0};
int array3[20] = {0};
int i;
int j = 0;
int k;
int l;
int m = 0;
int n;
int o;
int carry = 0;
int len = 0;
cout<<"Please enter the first number: "<<endl;
cin>>str1;
len = str1.length();
for (int i = str1.length() - 1; i >= 0; i--)
{
array1[j] = str1[i] - '0';
j++;
}
cout<<"Please enter the second number: "<<endl;
cin>>str2;
if ( len < str2.length() )
{
len = str2.length();
}
for (int l = str2.length() - 1; l >= 0; l--)
{
array2[m] = str2[l] - '0';
m++;
}
//Where the addition begins
for (int o = 0; o < len+1; o++)
{
array3[o] = array1[o] + array2[o] + carry;
carry = array3[o]/10;
array3[o] %= 10;
}
// Print the result.
printNumber(array3);
cout << endl;
return 0;
}

int main()
{
char A[20],B[20],C[22]={0};
int carry,len_a,len_b,x=20,i,j,a,b;
printf("First Number");
gets(A);
printf("Second Number");
gets(B);
len_a=strlen(A);
len_b=strlen(B);
for(i=len_a-1;i>=0;i--)
{
carry=0;
b=(int)B[i]-48;
a=(int)A[len_b-1]-48;
C[x]=C[x]+a+b;
if(C[x]>9)
{
C[x]=C[x]%10;
C[x-1]+=1;
}
x--;
len_b--;
}
int flag=0;
printf("Result :");
for(j=0;j<=20;j++)
{
if(C[j]!=0)
{
printf("%d",C[j]);
flag=1;
}
else if(C[j]==0 && flag==1)
printf("%d",C[j]);
}
if(flag==0)
printf("0");
getch();
return 0;
}

If I were you, would do exactly what I have done here:
inline bigint &bigint::operator+( const bigint & _expr )
{
vector<uint8_t> left = this->_digits;
vector<uint8_t> right = _expr._digits;
vector<uint8_t> sum;
uint8_t carry = 0;
process_operands( left, right ); // makes the two operands have the same length and fills them with leading zeros
for( auto lit = left.cbegin(), rit = right.cbegin(); lit != left.cend(), rit != right.cend(); ++lit, ++rit )
{
uint8_t temp_sum = ( *lit + *rit + carry ) % 10;
carry = ( *lit + *rit + carry ) / 10;
sum.push_back( temp_sum );
}
if( carry ) sum.push_back( carry );
this->_digits = sum;
return *this;
}
To make things look a little bit more clear:
bigint is my class for big integers, and looks something like this:
class bigint
{
private:
vector<uint8_t> _digits;
typedef vector<uint8_t>::size_type size_type;
bigint( vector<uint8_t> & in );
public:
bigint() : _digits() {}
bigint( const string &number );
// ...
};
So you should actually stop using the built-in arrays, since they are error-prone, and because we have better things offered by STL, like std::vector. I am using std::vector<uint8_t> to store the digits of my number, and so, it becomes easier to cycle through the digits: we can use either the range for (for(uint8_t & c : _digits) { }) or the iterators.
Attaching the leading zeros will become easier, since you ony have to do:
_digits.push_back( 0 );
in a for loop.

Related

C++ Long arithmetic

The program reads 2 variables a and b and displays their sum. The size of the numbers can go up to 10^100.
Program almost works. When we add 11 and 11, outputs correctly 22. But for example when 15 and 15, instead of 30 displays 20.
What is the problem?
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
int main()
{
string str1, str2;
cin>>str1>>str2;
int len1 = str1.length();
int len2 = str2.length();
char mas1[101], mas2[101];
int mas3[101], mas4[101];
for(int i=0; i<len1; i++)
{
strcpy(mas1, str1.c_str());
int ia = mas1[i] - '0';
mas3[i] = ia;
}
for(int i=0; i< len2; i++)
{
strcpy(mas2, str2.c_str());
int ia = mas2[i] - '0';
mas4[i] = ia;
}
int length;
if (len1 > len2)
length = len1 + 1;
else
length = len2 + 1;
for (int ix = 0; ix < length; ix++)
{
mas4[ix] += mas3[ix];
mas4[ix + 1] += (mas4[ix] / 10);
mas4[ix] %= 10;
}
if (mas4[length - 1] == 0)
length--;
for(int i=0;i<len2;i++)
{
cout<<mas4[i];
}
return 0;
}
You add integers to your array in the same order they appear in the string:
for(int i=0;i<len1;i++) {
strcpy(mas1, str1.c_str());
int ia = mas1[i] - '0';
mas3[i] = ia;
}
for(int i=0;i<len2;i++) {
strcpy(mas2, str2.c_str());
int ia = mas2[i] - '0';
mas4[i] = ia;
}
And then you add up the digits in the same order, from low index to high index:
for (int ix = 0; ix < length; ix++) {
mas4[ix] += mas3[ix];
mas4[ix + 1] += (mas4[ix] / 10);
mas4[ix] %= 10;
}
So you are basically adding up the tens, then the ones, and are incorrectly carrying from the tens into the ones. If you think about how you add two numbers on paper, you will see this is not correct. You need to start with the ones, and carry to the tens, and so on. So either reverse the order you save the integers in your array, or reverse the order in which you add them, being careful if you need to create a new digit place due to carry from the largest digit.

C++ - Finding x Factor of a math expression

I'm trying to get the x factor of an input math expression, but it seems buggy.
Here is my code:
#include<iostream>
#include<math.h>
using namespace std;
int main(){
char a[100];
int res = 0; // final answer
int temp = 0; // factor of the x we are focused on - temporarily
int pn = 0; // power of 10 - used for converting digits to number
int conv; // used for conversion of characters to int
cout<< "Enter a: ";
cin>> a; //input expression
for(int i=0; i<100; i++){
// checking if the character is x - then get the factor
if(a[i]=='x'){
for(int j=1; j<=i+1; j++){
conv = a[i-j] - '0'; // conversion
if(conv>=0 && conv<=9){ // check if the character is a number
temp = temp + conv*pow(10, pn); // temporary factor - using power of 10 to convert digit to number
pn++; // increasing the power
}
else{
if(a[i-j]=='-'){
temp = -temp; // check if the sign is - or +
}
break;
}
if(i-j==0){
break;
}
}
res = res+temp; // adding the x factor to other ones
pn = 0;
temp = 0;
}
}
cout<< res;
return 0;
}
It doesn't work for some inputs, for example:
100x+3x gives 102 and 3x+3997x-4000x gives -1
But works for 130x and 150x!
Is there a problem with my code, or is there an easier way to do this?
I think you're not parsing the +. There may be some other problem I can't see in the original code, probably not. Here's the X-File:
int main(){
char a[100];
int res(0);
cout << "Enter a: ";
cin >> a;
for(int i = 0; i < 100; i++){
if(a[i] == 'x'){
int temp(0);
int pn(0);
for(int j = 1; j <= i; j++){
int conv = a[i - j] - '0';
if(conv >= 0 && conv <= 9){
temp += conv*pow(10, pn);
pn++;
} else if(a[i - j] == '-') {
temp = -temp;
break;
} else if(a[i - j] == '+') {
break;
} else {
// what to do...
}
}
res += temp;
}
}
cout << res;
return 0;
}

Given an integer N, print numbers from 1 to N in lexicographic order

I'm trying to print the numbers from 1 to N in lexicographic order, but I get a failed output. for the following input 100, I get the 100, but its shifted and it doesn't match with the expected output, there is a bug in my code but I can not retrace it.
class Solution {
public:
vector<int> lexicalOrder(int n) {
vector<int> result;
for(int i = 1; i <= 9; i ++){
int j = 1;
while( j <= n){
for(int m = 0; m < j ; ++ m){
if(m + j * i <= n){
result.push_back(m+j*i);
}
}
j *= 10;
}
}
return result;
}
};
Input:
100
Output:
[1,10,11,12,13,14,15,16,17,18,19,100,2,20,21,22,23,24,25,26,27,28,29,3,30,31,32,33,34,35,36,37,38,39,4,40,41,42,43,44,45,46,47,48,49,5,50,51,52,53,54,55,56,57,58,59,6,60,61,62,63,64,65,66,67,68,69,7,70,71,72,73,74,75,76,77,78,79,8,80,81,82,83,84,85,86,87,88,89,9,90,91,92,93,94,95,96,97,98,99]
Expected:
[1,10,100,11,12,13,14,15,16,17,18,19,2,20,21,22,23,24,25,26,27,28,29,3,30,31,32,33,34,35,36,37,38,39,4,40,41,42,43,44,45,46,47
Think about when i=1,j=10 what will happen in
for(int m = 0; m < j ; ++ m){
if(m + j * i <= n){
result.push_back(m+j*i);
}
}
Yes,result will push_back 10(0+10*1),11(1+10*1),12(2+10*1)..
Here is a solution:
#include <iostream>
#include <vector>
#include <string>
std::vector<int> fun(int n)
{
std::vector<std::string> result;
for (int i = 1; i <= n; ++i) {
result.push_back(std::to_string(i));
}
std::sort(result.begin(),result.end());
std::vector<int> ret;
for (auto i : result) {
ret.push_back(std::stoi(i));
}
return ret;
}
int main(int argc, char *argv[])
{
std::vector<int> result = fun(100);
for (auto i : result) {
std::cout << i << ",";
}
std::cout << std::endl;
return 0;
}
You are looping through all 2 digit numbers starting with 1 before outputting the first 3 digit number, so your approach won't work.
One way to do this is to output the digits in base 11, padded out with leading spaces to the maximum number of digits, in this case 3. Output 0 as a space, 1 as 0, 2 as 1 etc. Reject any numbers that have any non-trailing spaces in this representation, or are greater than n when interpreted as a base 10 number. It should be possible to jump past multiple rejects at once, but that's an unnecessary optimization. Keep a count of the numbers you have output and stop when it reaches n. This will give you a lexicographical ordering in base 10.
Example implementation that uses O(1) space, where you don't have to generate and sort all the numbers up front before you can output the first one:
void oneToNLexicographical(int n)
{
if(n < 1) return;
// count max digits
int digits = 1, m = n, max_digit11 = 1, max_digit10 = 1;
while(m >= 10)
{
m /= 10; digits++; max_digit11 *= 11; max_digit10 *= 10;
}
int count = 0;
bool found_n = false;
// count up starting from max_digit * 2 (first valid value with no leading spaces)
for(int i = max_digit11 * 2; ; i++)
{
int val = 0, trailing_spaces = 0;
int place_val11 = max_digit11, place_val10 = max_digit10;
// bool valid_spaces = true;
for(int d = 0; d < digits; d++)
{
int base11digit = (i / place_val11) % 11;
if(base11digit == 0)
{
trailing_spaces++;
val /= 10;
}
else
{
// if we got a non-space after a space, it's invalid
// if(trailing_spaces > 0)
// {
// valid_spaces = false;
// break; // trailing spaces only
// }
val += (base11digit - 1) * place_val10;
}
place_val11 /= 11;
place_val10 /= 10;
}
// if(valid_spaces && (val <= n))
{
cout << val << ", ";
count++;
}
if(val == n)
{
found_n = true;
i += 10 - (i % 11); // skip to next number with one trailing space
}
// skip past invalid numbers:
// if there are multiple trailing spaces then the next run of numbers will have spaces in the middle - invalid
if(trailing_spaces > 1)
i += (int)pow(11, trailing_spaces - 1) - 1;
// if we have already output the max number, then all remaining numbers
// with the max number of digits will be greater than n
else if(found_n && (trailing_spaces == 1))
i += 10;
if(count == n)
break;
}
}
This skips past all invalid numbers, so it's not necessary to test valid_spaces before outputting each.
The inner loop can be removed by doing the base11 -> base 10 conversion using differences, making the algorithm O(N) - the inner while loop tends towards a constant:
int val = max_digit10;
for(int i = max_digit11 * 2; ; i++)
{
int trailing_spaces = 0, pow11 = 1, pow10 = 1;
int j = i;
while((j % 11) == 0)
{
trailing_spaces++;
pow11 *= 11;
pow10 *= 10;
j /= 11;
}
int output_val = val / pow10;
if(output_val <= n)
{
cout << output_val << ", ";
count++;
}
if(output_val == n)
found_n = true;
if(trailing_spaces > 1)
{
i += (pow11 / 11) - 1;
}
else if(found_n && (trailing_spaces == 1))
{
i += 10;
val += 10;
}
else if(trailing_spaces == 0)
val++;
if(count == n)
break;
}
Demonstration
The alternative, simpler approach is just to generate N strings from the numbers and sort them.
Maybe more general solution?
#include <vector>
#include <algorithm>
using namespace std;
// returns true is i1 < i2 according to lexical order
bool lexicalLess(int i1, int i2)
{
int base1 = 1;
int base2 = 1;
for (int c = i1/10; c > 0; c/=10) base1 *= 10;
for (int c = i2/10; c > 0; c/=10) base2 *= 10;
while (base1 > 0 && base2 > 0) {
int d1 = i1 / base1;
int d2 = i2 / base2;
if (d1 != d2) return (d1 < d2);
i1 %= base1;
i2 %= base2;
base1 /= 10;
base2 /= 10;
}
return (base1 < base2);
}
vector<int> lexicalOrder(int n) {
vector<int> result;
for (int i = 1; i <= n; ++i) result.push_back(i);
sort(result.begin(), result.end(), lexicalLess);
return result;
}
The other idea for lexicalLess(...) is to convert integers to string before comparision:
#include <vector>
#include <algorithm>
#include <string>
#include <boost/lexical_cast.hpp>
using namespace std;
// returns true is i1 < i2 according to lexical order
bool lexicalLess(int i1, int i2)
{
string s1 = boost::lexical_cast<string>(i1);
string s2 = boost::lexical_cast<string>(i2);
return (s1 , s2);
}
You need Boost to run the second version.
An easy one to implement is to convert numbers to string, them sort the array of strings with std::sort in algorithm header, that sorts strings in lexicographical order, then again turn numbers to integer
Make a vector of integers you want to sort lexicographically, name it numbers.
Make an other vector and populate it strings of numbers in the first vector. name it strs.
Sort strs array.4. Convert strings of strs vector to integers and put it in vectors
List item
#include <cstdlib>
#include <string>
#include <algorithm>
#include <vector>
#include <iostream>
using namespace std;
string int_to_string(int x){
string ret;
while(x > 0){
ret.push_back('0' + x % 10);
x /= 10;
}
reverse(ret.begin(), ret.end());
return ret;
}
int main(){
vector<int> ints;
ints.push_back(1);
ints.push_back(2);
ints.push_back(100);
vector<string> strs;
for(int i = 0; i < ints.size(); i++){
strs.push_back(int_to_string((ints[i])));
}
sort(strs.begin(), strs.end());
vector<int> sorted_ints;
for(int i = 0; i < strs.size(); i++){
sorted_ints.push_back(atoi(strs[i].c_str()));
}
for(int i = 0; i < sorted_ints.size(); i++){
cout<<sorted_ints[i]<<endl;
}
}
As the numbers are unique from 1 to n, you can use a set of size n and insert all of them into it and then print them out.
set will automatically keep them sorted in lexicographical order if you store the numbers as a string.
Here is the code, short and simple:
void lexicographicalOrder(int n){
set<string> ans;
for(int i = 1; i <= n; i++)
ans.insert(to_string(i));
for(auto ele : ans)
cout <<ele <<"\n";
}

Adding binary numbers in C++

How would I add two binary numbers in C++? What is the correct logic?
Here is my effort, but it doesn't seem to be correct:
#include <iostream>
using namespace std;
int main()
{
int a[3];
int b[3];
int carry = 0;
int result[7];
a[0] = 1;
a[1] = 0;
a[2] = 0;
a[3] = 1;
b[0] = 1;
b[1] = 1;
b[2] = 1;
b[3] = 1;
for(int i = 0; i <= 3; i++)
{
if(a[i] + b[i] + carry == 0)
{
result[i] = 0;
carry = 0;
}
if(a[i] + b[i] + carry == 1)
{
result[i] = 0;
carry = 0;
}
if(a[i] + b[i] + carry == 2)
{
result[i] = 0;
carry = 1;
}
if(a[i] + b[i] + carry > 2)
{
result[i] = 1;
carry = 1;
}
}
for(int j = 0; j <= 7; j++)
{
cout<<result[j]<<" ";
}
system("pause");
}
Well, it is a pretty trivial problem.
How to add two binary numbers in c++. what is the logic of it.
For adding two binary numbers, a and b. You can use the following equations to do so.
sum = a xor b
carry = ab
This is the equation for a Half Adder.
Now to implement this, you may need to understand how a Full Adder works.
sum = a xor b xor c
carry = ab+bc+ca
Since you store your binary numbers in int array, you might want to understand bitwise operation.
You can use ^ for XOR,| operator for OR, & operator for AND.
Here is a sample code to calculate the sum.
for(i = 0; i < 8 ; i++){
sum[i] = ((a[i] ^ b[i]) ^ c); // c is carry
c = ((a[i] & b[i]) | (a[i] & c)) | (b[i] & c);
}
Since you were asking about C++, you deserve a C++ answer. Use bitsets:
#include <bitset>
#include <iostream>
int main() {
std::bitset<5> const a("1001");
std::bitset<5> const b("1111");
// m here is a mask to extract the lsb of a bitset.
std::bitset<5> const m("1");
std::bitset<5> result;
for (auto i = 0; i < result.size(); ++i) {
std::bitset<5> const diff(((a >> i)&m).to_ullong() + ((b >> i)&m).to_ullong() + (result >> i).to_ullong());
result ^= (diff ^ (result >> i)) << i;
}
std::cout << result << std::endl;
}
This works for arbitrarily long bit sets.
You could use "Bitwise OR" operation to reduce the code since
1 or 1 = 1
1 or 0 = 1
0 or 1 = 1
0 or 0 = 0
You could also convert both number to decimal sum and them go back to binary again.
Converting decimal to binary
int toBinary (unsigned int num, char b[32])
{
unsigned int x = INT_MIN; // (32bits)
int i = 0, count = 0;
while (x != 0)
{
if(x & num) // If the actual o bit is 1 & 1 = 1 otherwise = 0
{
b[i] = '1';
count++;
}
else b[i] = '0';
x >>=1; // pass to the left
i++;
}
return count;
}
There is a bug :
if(a[i]+b[i]+carry==1)
{
result[i]=1;
carry=0;
}
Also u might want to print in reverse
for(int j=6; j>=0; j--)
{
cout<<result[j]<<" ";
}
Your arrays are one item too small for your indexing.
int a[3] only has 3 elements, so a[3] = 1 is invalid (it has undefined behaviour) since it's accessing the 4th element, which doesn't exist.
Likewise for the other arrays.
That means that the whole program has undefined behaviour, i.e. it can do anything or nothing at all.
(What's probably happening in your case is that writing outside the arrays is overwriting the other variables.)
You're also not initialising the result array, so its content is just some random data.
Since you only update 4 of its elements but print all of them (and more), the output will be random data as well.
Following were the errors in your code and fixed code is also below"
int a[] was of size 3 so it cannot store at the 3rd index. use int a[4].
if(a[i]+b[i]+carry==1) wrong values were assigned in this check update result[i]=1; carry=0.
The sequence of checks is reversed.
The last carry was not stored in the result.
The addition result stored in the result array was in reverse order so printed it in reverse.
here is the working piece of code:
#include <iostream>
#include <string>
using namespace std;
int main()
{
int a[4];
int b[4];
int carry=0;
int result[5];
a[0]=1;
a[1]=0;
a[2]=0;
a[3]=1;
b[0]=1;
b[1]=1;
b[2]=1;
b[3]=1;
for(int i=0; i<4; i++)
{
if(a[i]+b[i]+carry==3)
{
result[i]=1;
carry=1;
}
if(a[i]+b[i]+carry==2)
{
result[i]=0;
carry=1;
}
if(a[i]+b[i]+carry==1)
{
result[i]=1;
carry=0;
}
if(a[i]+b[i]+carry==0)
{
result[i]=0;
carry=0;
}
}
result[4]=carry;
for(int j=4; j>=0; j--)
{
cout<<result[j];
}
cout<<endl;
return 0;
}
#include <stdio.h>
int main()
{
long binary1, binary2;
int i = 0, remainder = 0, sum[20];
printf("Enter the first binary number: ");
scanf("%ld", &binary1);
printf("Enter the second binary number: ");
scanf("%ld", &binary2);
while (binary1 != 0 || binary2 != 0)
{
sum[i++] =(binary1 % 10 + binary2 % 10 + remainder) % 2;
remainder =(binary1 % 10 + binary2 % 10 + remainder) / 2;
binary1 = binary1 / 10;
binary2 = binary2 / 10;
}
if (remainder != 0)
sum[i++] = remainder;
--i;
printf("Sum of two binary numbers: ");
while (i >= 0)
printf("%d", sum[i--]);
getch();
return 0;
}
Repeatedly do
(x, y) <- ((x & y) << 1, x ^ y)
until x is 0. y is the answer.
you should do this
for(int i = 3; i >= 0; i--)
{
if(a[i] + b[i] + carry == 0)
{
result[i] = 0;
carry = 0;
}
else if(a[i]+b[i]+carry==1)
{
result[i]=1;
carry=0;
}
else if(a[i] + b[i] + carry == 2)
{
result[i] = 0;
carry = 1;
}
else if(a[i] + b[i] + carry > 2)
{
result[i] = 1;
carry = 1;
}
printf("%d",result[i]);
}
A non-conventional solution, but it works:
int main() {
int A[] = { 0, 0, 0, 1, 1, 0, 1, 0};
int B[] = { 0, 0, 0, 0, 1, 1, 0, 0};
int size = sizeof(A)/sizeof(*A);
int C[size+1];
int t = 0;
for(int i = size-1; i > -1; i--){
C[i+1] = A[i]+B[i]+t;
t = C[i+1]/2;
C[i+1] %= 2;
}
C[0] = t;
}
What if their sizes are not the same? Also, you would want to allow the user to input the binary numbers (in this case representing integers) as integers and not as elements of arrays. Here is a piece of code that accomplishes those :-)
#include <iostream>
using namespace std;
// Add two numbers in binary
void sumBinary(int num1, int num2, int* sum12){
int mod1 = 0;
int mod2 = 0;
int carry = 0;
int factor = 1;
int flag = 0;
*sum12 = 0;
while (!flag){
mod1 = num1 % 10;
mod2 = num2 % 10;
num1 /= 10;
num2 /= 10;
if ((carry + mod1 + mod2) == 2){
*sum12 += 0;
carry = 1;
}
else if ((carry + mod1 + mod2) == 3){
*sum12 += factor;
carry = 1;
}
else if ((carry + mod1 + mod2) == 0){
*sum12 += 0;
carry = 0;
}
else{
*sum12 += factor;
carry = 0;
}
factor *= 10;
if ((num1 == 0) && (num2 == 0)){
*sum12 += carry*factor;
flag = 1; }
}
}
void main(){
int num1, num2, sum12;
cout << "Enter the first binary integer number: ";
cin >> num1;
cout << "Enter the second binary integer number: ";
cin >> num2;
sumBinary(num1, num2, &sum12);
cout << "The sum in binary form is :" << sum12 << endl;
}
A simple way :
int getBit(string s, int index)
{
if(index >= 0) return (s[index] - '0');
else return 0;
}
string addBinary(string a, string b)
{
if(a.size() > b.size()) while(a.size() > b.size()) b = "0" + b;
else if(b.size() > a.size()) while(b.size() > a.size()) a = "0" + a;
int l = max(a.size()-1, b.size() - 1);
string result = "";
int s=0;
while(l>=0 || s==1)
{
s += getBit(a, l) + getBit(b, l) ;
result = char(s % 2 + '0') + result;
s /= 2;
l--;
}
return result;
}
int main(){
ios::sync_with_stdio(0); cin.tie(0);
int num1=12, num2=45, sum=0;
bool b1, b2, carry=0;
for(int i=0;i<32;i++){
b1=( 1<<i ) & num1;
b2=( 1<<i ) & num2;
sum = (b1 ^ b2 ^ carry) ? sum ^ (1<<i) : sum;
carry = ((b1 & b2) | (b1 & carry) | (b2 & carry));
}
cout<<sum;
return 0;
}
Easy to understand code
Add Two Binary Numbers (input datatype = int)
#include <iostream>
using namespace std;
int power(int a, int b)
{
int ans = 1;
while (b)
{
ans *= a;
b--;
}
return ans;
}
int main()
{
int n1, n2, carry = 0, ans = 0, rem1, rem2, remsum = 0, i;
cout << "Enter First Number : ";
cin >> n1;
cout << "Enter Second Number : ";
cin >> n2;
for (i = 0; n1 != 0 || n2 != 0; i++, n1 /= 10, n2 /= 10)
{
rem1 = n1 % 10;
rem2 = n2 % 10;
remsum = rem1 + rem2 + carry;
if (remsum == 2)
{
carry = 1;
remsum = 0;
}
else if (remsum == 3)
{
carry = 1;
remsum = 1;
}
else if (remsum == 0)
{
carry = 0;
remsum = 0;
}
else if (remsum == 1)
{
carry = 0;
remsum = 1;
}
ans = remsum * power(10, i) + ans;
}
ans = carry * power(10, i) + ans;
cout << ans;
return 0;
}

long integer multiplication

I am preparing the interview questions not for homework. There is one question about how to multiple very very long integer. Could anybody offer any source code in C++ to learn from? I am trying to reduce the gap between myself and others by learning other's solution to improve myself.
Thanks so much!
Sorry if you think this is not the right place to ask such questions.
you can use GNU Multiple Precision Arithmetic Library for C++.
If you just want an easy way to multiply huge numbers( Integers ), here you are:
#include<iostream>
#include<string>
#include<sstream>
#define SIZE 700
using namespace std;
class Bignum{
int no[SIZE];
public:
Bignum operator *(Bignum& x){ // overload the * operator
/*
34 x 46
-------
204 // these values are stored in the
136 // two dimensional array mat[][];
-------
1564 // this the value stored in "Bignum ret"
*/
Bignum ret;
int carry=0;
int mat[2*SIZE+1][2*SIZE]={0};
for(int i=SIZE-1;i>=0;i--){
for(int j=SIZE-1;j>=0;j--){
carry += no[i]*x.no[j];
if(carry < 10){
mat[i][j-(SIZE-1-i)]=carry;
carry=0;
}
else{
mat[i][j-(SIZE-1-i)]=carry%10;
carry=carry/10;
}
}
}
for(int i=1;i<SIZE+1;i++){
for(int j=SIZE-1;j>=0;j--){
carry += mat[i][j]+mat[i-1][j];
if(carry < 10){
mat[i][j]=carry;
carry=0;
}
else{
mat[i][j]=carry%10;
carry=carry/10;
}
}
}
for(int i=0;i<SIZE;i++)
ret.no[i]=mat[SIZE][i];
return ret;
}
Bignum (){
for(int i=0;i<SIZE;i++)
no[i]=0;
}
Bignum (string _no){
for(int i=0;i<SIZE;i++)
no[i]=0;
int index=SIZE-1;
for(int i=_no.length()-1;i>=0;i--,index--){
no[index]=_no[i]-'0';
}
}
void print(){
int start=0;
for(int i=0;i<SIZE;i++)
if(no[i]!=0){
start=i;
break; // find the first non zero digit. store the index in start.
}
for(int i=start;i<SIZE;i++) // print the number starting from start till the end of array.
cout<<no[i];
cout<<endl;
return;
}
};
int main(){
Bignum n1("100122354123451234516326245372363523632123458913760187501287519875019671647109857108740138475018937460298374610938765410938457109384571039846");
Bignum n2("92759375839475239085472390845783940752398636109570251809571085701287505712857018570198713984570329867103986475103984765109384675109386713984751098570932847510938247510398475130984571093846571394675137846510874510847513049875610384750183274501978365109387460374651873496710394867103984761098347609138746297561762234873519257610");
Bignum n3 = n1*n2;
n3.print();
return 0;
}
as you can see, it's multiply 2 huge integer :) ... (up to 700 digits)
Try this:
//------------DEVELOPED BY:Ighit F4YSAL-------------
#include<iostream>
#include<string>
#include<sstream>
#define BIG 250 //MAX length input
using namespace std;
int main(){
int DUC[BIG][BIG*2+1]={0},n0[BIG],n1[BIG],i,t,h,carry=0,res;
string _n0,_n1;
while(1){
//-----------------------------------get data------------------------------------------
cout<<"n0=";
cin>>_n0;
cout<<"n1=";
cin>>_n1;
//--------------------string to int[]----------------------------------------
for(i=_n0.length()-1,t=0;i>=0,t<=_n0.length()-1;i--,t++){
n0[i]=_n0[t]-'0';
}
i=0;
for(i=_n1.length()-1,t=0;i>=0,t<=_n1.length()-1;i--,t++){
n1[i]=_n1[t]-'0';
}
i=0;t=0;
//--------------------------produce lines of multiplication----------------
for(i=0;i<=_n1.length()-1;i++){
for(t=0;t<=_n0.length()-1;t++){
res=((n1[i]*n0[t])+carry);
carry=(res/10);
DUC[i][t+i]=res%10;
}
DUC[i][t+i]=carry;
carry=0;
}
i=0;t=0;res=0;carry=0;
//-----------------------------add the lines-------------------------------
for(i=0;i<=_n0.length()*2-1;i++){
for(t=0;t<=_n1.length()-1;t++){
DUC[BIG-1][i]+=DUC[t][i];
//cout<<DUC[t][i]<<"-";
}
res=((DUC[BIG-1][i])+carry);
carry=res/10;
DUC[BIG-1][i]=res%10;
//cout<<" ="<<DUC[BIG-1][i]<<endl;
}
i=0;t=0;
//------------------------print the result------------------------------------
cout<<"n1*n0=";
for(i=_n0.length()*2-1;i>=0;i--){
if((DUC[BIG-1][i]==0) and (t==0)){}else{cout<<DUC[BIG-1][i];t++;}
//cout<<DUC[BIG-1][i];
}
//-------------------------clear all-------------------------------------
for(i=0;i<=BIG-1;i++){
for(t=0;t<=BIG*2;t++){
DUC[i][t]=0;
}
n0[i]=0;n1[i]=0;
}
//--------------------------do it again-------------------------------------
cout<<"\n------------------------------------------------\n\n";
}
return 0;
}
This solution is good for very very big numbers but not so effective for factorial calculation of very big numbers. Hope it will help someone.
#include <iostream>
#include <string>
using namespace std;
string addition(string a, string b) {
string ans = "";
int i, j, temp = 0;
i = a.length() - 1;
j = b.length() - 1;
while (i >= 0 || j >= 0) {
if (i >= 0 && a[i])
temp += a[i] - '0';
if (j >= 0 && b[j])
temp += b[j] - '0';
int t = (temp % 10);
char c = t + '0';
ans = ans + c;
temp = temp / 10;
i--;
j--;
}
while (temp > 0) {
int t = (temp % 10);
char c = t + '0';
ans = ans + c;
temp = temp / 10;
}
string fnal = "";
for (int i = ans.length() - 1;i >= 0;i--) {
fnal = fnal + ans[i];
}
return fnal;
}
string multiplication(string a, string b) {
string a1, b1 = "0";
int i, j, temp = 0, zero = 0;
i = a.length() - 1;
int m1, m2;
while (i >= 0) {
a1 = "";
m1 = a[i] - '0';
j = b.length() - 1;
while (j >= 0) {
m2 = b[j] - '0';
temp = temp + m1*m2;
int t = temp % 10;
char c = t + '0';
a1 = a1 + c;
temp = temp / 10;
j--;
}
while (temp > 0) {
int t = (temp % 10);
char c = t + '0';
a1 = a1 + c;
temp = temp / 10;
}
string fnal = "";
// reverse string
for (int i = a1.length() - 1;i >= 0;i--) {
fnal = fnal + a1[i];
}
a1 = fnal;
//add zero
for (int p = 0;p < zero;p++)
a1 = a1 + '0';
b1 = addition(a1, b1);
i--;
zero++;
}
return b1;
}
// upto 50 is ok
int factorial(int n) {
string a = "1";
for (int i = 2;i <= n;i++) {
string b = to_string(i);
a = multiplication(a, b);
}
cout << a << endl;
return a.length();
}
int main() {
freopen("in.txt", "r", stdin);
freopen("out.txt", "w", stdout);
int n;
cin >> n;
//cout << factorial(n) << endl;
string a, b;
a = "1281264836465376528195645386412541764536452813416724654125432754276451246124362456354236454857858653";
b = "3767523857619651386274519192362375426426534237624548235729562582916259723586347852943763548355248625";
//addition(a, b);
cout << multiplication(a, b);
return 0;
}