-1

I am trying to divide a number by an integer as suggested in the title, and i am having a hard time doing so. I was thinking about inserting the big number's digits into a vector then repeatedly substracting said digit from the vector until it is null. However, i cannot find the code to do it. Here is what i have been trying so far:

   #include <fstream>
using namespace std;
int v[100],r[100];  //In v i store the initial number,in r i store the result
int main()
{
FILE*fin=fopen("imp.in","r");
FILE*fout=fopen("imp.out","w");
int n,x,c,w,k,m=2;
fscanf(fin,"%d",&n); //Reads the number of digits the number has
for(;n>0;--n)
{
    fscanf(fin,"%d",&x);
    v[n]=x;
}
fscanf(fin,"%d",&c); //Reads the digit it has to be divided by
while(v[n]!=0)
{
   k=0;
   while(v[1]>=c)
   {
        v[1]-=c;
        ++k;
   }//As long as the first position in vector can be substracted, increase k
   --v[2];
   v[1]+=10;
    /* Because first position will be negative, take one from second                    position and add ten in the first*/
   w=2;
   while(v[w]<0)
   {
       v[w]=9;
       --v[w+1];
       ++w;
   }
   /*When, for example, you substract one from 1000,it will become 999. This loop helps do that*/
   r[1]+=k;
   if(r[1]>9)
   {
       r[1]-=10;
       w=2;
       ++r[2];
       while(r[w]>9)
       {
           ++r[w+1];
           r[w]=0;
           ++w;
           if(w>m)m=w;
       }
   }
   /*If statement and the line of code above it inserts the result into r[100]*/
}
for(;w>0;--w)fprintf(fout,"%d",r[w]);
return 0;
}
  • I would strongly recommend using a big-number library to do this, rather than writing your own implementation. Search Google for "128-bit division C++." – Cody Gray - on strike Mar 05 '16 at 16:03
  • Don't do that use Boost.Multiprecision. http://www.boost.org/doc/libs/1_60_0/libs/multiprecision/doc/html/index.html – mustafagonul Mar 05 '16 at 16:08
  • Well i need numbers with up to 2000 digits. I know in the code i only used 100 digits but i can change that anytime. Therefore, i need to write myself the implementation. – w4teraddict Mar 05 '16 at 16:09

1 Answers1

2

You can use GMP rather than write it yourself from scratch. It will take you less time to download the GMP sources, build it, and learn how to use it, than to write it yourself.

Pencil and paper division in base 2^32, or 2^64, would be a lot more efficient than "division by subtraction" and I believe that GMP employs a better algorithm than that.

With GMP you'd write:

mpz_class a("134897563047067890568704560457984059182035823590780968094759123590346040967804956029586405960249562895760983475187459073406984560900123895702851034560016405716045613495619456196450196450165901268051620465016405634056104951923845902387581");
std::cout << a / 7 << std::endl;
BitWhistler
  • 1,439
  • 8
  • 12