Hi! I have written a code to subtract 2 large integers stored in arrays! But the problem is, its not working when the minuend is smaller than the subtrahend, i.e, when the answer would be negative. I am taking 2 char arrays as parameters, converting them to int arrays, working with them, storing the result in a char array & returning it! Can somebody please point out the optimizations needed in the code!

#include<iostream.h>
#include<conio.h>
#include<string.h>

class Sub{
 public:
 char *subArray(char a[], char b[])
 {
  int i, j, k, diff[255], borr, size1=0, size2=0, x[255], y[255];
  char temp[255], *p;
  cout<<"\nNuM1: "  ;
  for(i=0; a[i]!=NULL; i++)
  {
    x[i]=a[i]-'0';                 //conversion into int array 
    size1++;                     
    cout<<x[i];
  }
  cout<<"\nNuM2: "  ;
  for(i=0; b[i]!=NULL; i++)
  {
    y[i]=b[i]-'0';                //conversion into int array 
    size2++;
    cout<<y[i];
  }
  if(size1<size2)                
  {
    p=subArray(b, a);
        p[0]=-p[0];               //not printing the correct value
    return p;
  }
  else
  {
     for(j=0; j<size2; j++)
     {
      y[j]=-y[j];
     }
     k=borr=0;

     for(i=size1-1, j=size2-1;i>=0 && j>=0; i--, j--, k++)
     {
      diff[k]=x[i]+y[j]-borr;
     if(diff[k]<0)
     {
      diff[k]+=10;
      borr=1;
     }
     else
     borr=0;
     }
     if(i>=0)
    {
     for(;i>=0;i--,k++)
     {
      diff[k]=x[i]-borr;
      if(diff[k]<0)
      {
        diff[k]+=10;
        borr=1;
      }
      else
      borr=0;
    }
  }

  i=j=0;
  for(i=k-1; i>=0; i--)
  {
     if(diff[i]<0)
     {
      temp[j++]='-';
      temp[j++]=-(diff[i])+'0';
     }
     else
     temp[j++]=diff[i]+'0';
  }
  temp[j]='\0';
  return temp;
  }
 }
};
void main()
{
 Sub s;
 char num1[255], num2[255], *diff;
 cout<<"NuM1: ";
 cin>>num1 ;
 cout<<"\nNuM2: ";
 cin>>num2;
 diff = s.subArray(num1, num2);
 cout<<"\nDifference: ";
 while(*diff != NULL)
 {
  cout<<*diff;
  diff++;
 }
}

Well one way to fix that is to see what is bigger and if the number that is being subtracted is larger than the number it is being subtracted from switch them around. Then do your normal subtraction and add a "-" to the result.

10 - 100 = -90

Swap 10 and 100 and add the negitive

100 - 10 = 90 * -1 = -90

Edited 3 Years Ago by NathanOliver

My first suggestion is to try and subsection your code a little. Your code is complex and a bit difficult to read.
If you split it out, it will be easier to understand.

Secondly, your logic fails when a and b are of equal length when b is larger than a.
Example: a = 12345; b = 54321

To check which is larger, I suggest you check each character individually, starting with the left-most character and find which is larger. As soon as one is larger than the other, you will know which way around you have to do your subtraction.

This article has been dead for over six months. Start a new discussion instead.