-4

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?

Floris
  • 45,857
  • 6
  • 70
  • 122
gravitas
  • 21
  • 1
  • 4
  • Are both numbers that large? What precision do you need in the final result? How large do you expect the result to be? Is this integer division? Google bigdecimal. – Floris May 28 '14 at 12:37
  • it's basically finding out whether one big number of the specified order is divisible by another of the order 1000. – gravitas May 28 '14 at 12:41
  • OK - that is actually a very different problem than the one you are stating; and quite a bit easier. – Floris May 28 '14 at 12:45
  • yeah, I realized that, and edited the question. if you can help.. – gravitas May 28 '14 at 12:46
  • While the duplicate indicated talks about bignum division, none of the answers really provide the kind of specific help that would get the OP's question answered - especially after clarification (needs to find out if A is divisible by B). Also - none of the answers in the dup were accepted, and that question is almost 3 years old. I have updated the question and vote for it to be re-opened. – Floris May 28 '14 at 13:11
  • 1
    @Floris I agree it is not a duplicate. That question asks how to improve performance on a bignum division *algorithm* (which incidentally uses strings, but this detail is not relevant), whereas this question asks *how* to do bignum division on a *string*. – JBentley May 28 '14 at 13:28

1 Answers1

1

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.

Floris
  • 45,857
  • 6
  • 70
  • 122