Search code examples
c++stringdivisioninteger-division

Figure out if a very large number is divisible by another


I am dealing with a programming question where I need to divide a very big number, of the order of 10^50000 by another of the order of 1000, in order to figure out if one is divisible by the other. So I need to use strings to store this large number.

I don't know any method to divide a string by a number. Can anyone point me to an algorithm?


Solution

  • Here is a start of an algorithm. It seems to do what you are asking for: it performs "long division" in 4 character chunks, and keeps track of the remainder. It prints the remainder at the end. You should be able to adapt this to your specific needs. Note - doing this in 4 bytes chunks makes it significantly faster than conventional one-character-at-a-time algorithms, but it does rely on b being small enough to fit in an int (hence the 4 character chunks).

    #include <stdio.h>
    #include <string.h>
    
    int main(void) {
      char as[]="123123123123126";
      int l = strlen(as);
      int rem;
      int lm = l % 4; // the size of the initial chunk (after which we work in multiples of 4)
      char *ap=as;    // a pointer to keep track of "where we are in the string"
      int b=123;      // the divisor
      int a;
      sscanf(ap, "%4d", &a);
      while(lm++ < 4) a /= 10;
    //  printf("initial a is %d\n", a);
      rem = a % b;
    
      for(ap = as + (l%4); ap < as + l; ap += 4) {
    //  printf("remainder = %d\n", rem);
      sscanf(ap, "%4d", &a);
    //  printf("a is now %d\n", a);
      rem = (a + 10000*rem) %b;
      }
      printf("remainder is %d\n", rem);
      return 0;
    }
    

    Output:

    remainder is 3
    

    This needs some cleaning up but I hope you get the idea.