Averiguar si un número muy grande es divisible por otro

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?

preguntado el 28 de mayo de 14 a las 13:05

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. -

it's basically finding out whether one big number of the specified order is divisible by another of the order 1000. -

OK - that is actually a very different problem than the one you are stating; and quite a bit easier. -

yeah, I realized that, and edited the question. if you can help.. -

@Floris I agree it is not a duplicate. That question asks how to improve performance on a bignum division algoritmo (which incidentally uses strings, but this detail is not relevant), whereas this question asks cómo to do bignum division on a cadena. -

1 Respuestas

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;
}

Salida:

remainder is 3

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

contestado el 28 de mayo de 14 a las 14:05

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.