算出一个很大的数是否能被另一个数整除

Figure out if a very large number is divisible by another

本文关键字:是否 另一个 一个      更新时间:2023-10-16

我正在处理一个编程问题,我需要将一个非常大的数字(10^50000的数量级)除以另一个数量级为1000的数量级,以确定一个是否可以被另一个整除。所以我需要使用字符串来存储这个大数字

我不知道任何方法来除以一个数字的字符串。谁能给我指个算法?

这是一个算法的开始。它似乎做了你所要求的:它在4个字符块中执行"长除法",并跟踪其余部分。它在最后打印剩余的部分。您应该能够使其适应您的具体需求。注意-在4字节块中执行此操作使其比传统的一次一个字符的算法快得多,但它确实依赖于b足够小以适合int(因此有4个字符块)。

#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 %dn", a);
  rem = a % b;
  for(ap = as + (l%4); ap < as + l; ap += 4) {
//  printf("remainder = %dn", rem);
  sscanf(ap, "%4d", &a);
//  printf("a is now %dn", a);
  rem = (a + 10000*rem) %b;
  }
  printf("remainder is %dn", rem);
  return 0;
}
输出:

remainder is 3

这需要一些清理,但我希望你能明白。

相关文章: