Long Integer Operations
Long Int Addition or Subtraction
#include<iostream>
using namespace std;
int main() {
int a[] = {9, 8, 5, 2, 8};
int i = sizeof(a)/sizeof(int);
int b[] = {0, 1, 7, 4};
int j = sizeof(b)/sizeof(int);
int c[((i>j)? (i+1): (j+1))], k = ((i>j)? i: j);
int carry = 0, remainder, quotient;
for (i -= 1, j -= 1; i >= 0 && j >= 0; i--, j--) {
remainder = (a[i] + b[j] + carry) % 10;
quotient = (a[i] + b[j] + carry) / 10;
c[k--] = remainder;
carry = quotient;
}
if(j >= 0) {
for (; j >= 0 ; j--) {
c[k--] = (b[j] + carry) % 10;
carry = (b[j] + carry) / 10;
}
}
else if(i >= 0) {
for (; i >= 0 ; i--) {
c[k--] = (a[i] + carry) % 10;
carry = (a[i] + carry) / 10;
}
}
c[0] = carry;
int size = sizeof(c)/sizeof(int);
for (i = 0; i < size; i++) {
cout << c[i] << ' ';
}
return 0;
}
Long Int Multiplication
#include<iostream>
using namespace std;
int main() {
int a[] = {7, 2, 9, 5, 6};
int b[] = {7, 5, 1, 3};
int i = sizeof(a)/sizeof(a[0]);
int j = sizeof(b)/sizeof(b[0]);
const int rows = j;
const int col = (j * 2) + 1;
int p = j*2,
k = 0,
sum ;
int twoD[rows][col] = {0};
for (int i = 0; i < rows; i++) {
for (int j = 0; j < col; j++) {
twoD[i][j] = 0 ;
}
}
for ( j -= 1; j >= 0; j--) {
int carry = 0, q = 0;
for (int r = i-1; r >= 0; r--) {
sum = ((b[j] * a[r]) + carry);
twoD[k][p-q] = sum % 10;
carry = sum / 10;
q++;
}
twoD[k][p-q] = carry;
k++;
p--;
}
for (int i = 0; i < rows; i++) {
for (int j = 0; j < col; j++) {
cout << twoD[i][j] << " ";
}cout << endl;
}
int carry = 0;
int res[col]; k = col-1;
for (int i = col-1; i >= 0; i--) {
sum = 0;
for (int j = rows-1; j >= 0; j--) {
sum += twoD[j][i];
}
sum += carry;
res[k] = sum % 10;
carry = sum / 10;
k--;
}
res[0] = sum;
cout << "-----------------"<< endl;
for (int i = 0; i < col; i++) {
cout << res[i] << " ";
}
}
Last updated
Was this helpful?