mardi 5 mai 2015

Multiplication of Big Numbers using Self-Made Flexible Array Struct

I have an assignment due in just a few hours for which I have to make a "big number" calculator that essentially allows me to apply mathematical operations to integers larger than can be stored in the primitive integer type. The numbers are inputted as strings and each digit is saved into a flexible array. I have my flexible array working and my big number calculator can do addition and subtraction on positive numbers, but I need it also to multiply and divide. I attempted to follow a friend's code to write my multiplication method, but it's coming out very, very, wrong (in the given example, it prints out 243495757575755575350-336-336-336-336-336-336-336-336-33656) and I really don't have it in me to attempt to rewrite it without having a better idea of what to do or where I'm going wrong. If any more of the code is needed, just let me know in a comment and I'd be happy to post the rest. Thanks so much in advance.

The string assignment method:

 void bigint::assign(string a)
  {    
      int size = a.length();
          int pos = 0;
          for (int i = size-1; i >= 0; i--)
          { 
              digits.set(pos, a[i]-48);
              pos++;  
          }  
  }

The multiplication method:

 void bigint::multiply (const bigint & a)
 {      
         int size = digits.get_size();
         int asize = a.digits.get_size();
         int maxsize;
         if (asize > size)
             maxsize = 2*asize;
         else
             maxsize = 2*size;
         bigint temp;
         for (int i=0; i<asize; i++)
         {    
             int carry = 0;
             for (int j = 0; j<size; j++)
             {    if (a.get(i) == '0')
                      break;
                  else if (((a.get(i)-48)*(get(j)-48)+carry)<10)
                  {      
                      temp.digits.set(i+j, (a.get(i)-48)*(get(j)-48)+carry+48);
                      carry=0;   
                  }
                  else   
                  {
                      temp.digits.set(i+j, ((a.get(i)-48)*(get(j)-48)+carry)%10+48);
                      carry = ((a.get(i)-48)*(get(j)-48)+carry)/10; 
                  }
                  if (j == size-1 && carry>0)
                  {
                      temp.digits.set(size+i, carry + 48);
                      break;
                  }
             }
             assign(temp);
         }
}

A sample main test:

void main()
{    bigint a, b;
     a.assign("20");
     b.assign("2");
     a.multiply(b);
     a.print();  //the end result should just be "40" printed on the screen
}

Aucun commentaire:

Enregistrer un commentaire