算出一个很大的数是否能被另一个数整除
Figure out if a very large number is divisible by another
我正在处理一个编程问题,我需要将一个非常大的数字(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
这需要一些清理,但我希望你能明白。
相关文章:
- 在 Windows 上,是否可以让 dll 在不使用 PATH 环境变量的情况下在另一个文件夹中查找依赖项?
- 检查注册表项是否链接到(或副本)另一个注册表项
- 检查一个类型是否直接派生自"enable if"上下文中的另一个类型(是其子类型)
- 是否可以使用一个类来控制 C++ 中另一个类的对象?(阿杜伊诺)
- 检查 2D 网格的某个元素是否与另一个元素共享对角线、水平线或垂直线
- 如何巧妙地编写两个函数——一个用于检查是否存在解决方案,另一个用于获取所有解决方案
- 检查路径是否包含C++中的另一个路径
- 是否可以使用分配器对象来释放另一个分配器分配的内存?
- 是否可以使用智能指针成员设置具有另一个结构的结构?
- 计时器是否从另一个线程启动?
- 在销毁期间从另一个线程调用对象上调用方法是否未定义行为?
- 从另一个线程发出信号是否安全?
- 在没有任何锁的情况下加入另一个线程后是否需要内存围栏?
- 在C++中,是否可以"overload"作为另一个类成员的对象?
- 如何检查一个模板是否是另一个模板的类成员
- 如何检查一个字符是否与字符数组中的另一个字符匹配?
- 是否可以将子进程的 stdout 重定向到父进程中的另一个文件?
- 如何构造一个类型特征,可以判断一个类型的私有方法是否可以在另一个类型的构造函数中调用?
- 是否可以将带有捕获和参数的 lambda 传递给另一个函数?如果是这样,如何?
- 对于存储另一个类所需信息的类,例如其构造,是否有设计模式?