此问题在此处已有答案:
Mod of two large numbers in C++(1个答案)
6天前关闭
我有两个大的十六进制数,每个至少有70位(十进制),我试图计算值hex_a%hex_b:
string hex_a="1133A5DCDEF3216A63EB879A82F5A1DC4490CCF6412492CF1B242DB";
string hex_b="AAB3A5DCDEF3216A6AAA2F5A1DC4490CCF6412492CF1B242DB";
字符串
我尝试用stoi将两个十六进制数转换为十进制数,并将值存储在字符串中:
string a=to_string(stoi(hex_a, 0, 16));
型
但是我在使用stoi方法时得到一个错误:
terminate called after throwing an instance of 'std::out_of_range'
what(): stoi
Aborted (core dumped)
型
如何在C++中计算两个大数字的模?
2条答案
按热度按时间blmhpbnm1#
您可以使用
boost/multiprecision/cpp_int
:字符串
或者GNU Multiple Precision Arithmetic Library (GMP),这可能更快:
型
输出:
型
在Python中确认相同的结果:
型
l2osamch2#
首先,你不能把这么大的数字转换成“int”、“long”、“long long”、“double”等。
第一种方法是在字符串上实现基本的数学运算(+,-,乘16或移位),然后自己实现除法算法。
第二种方法是使用和“任意精度算术库”:https://en.wikipedia.org/wiki/List_of_arbitrary-precision_arithmetic_software
例如https://www.boost.org/doc/libs/1_83_0/libs/multiprecision/doc/html/index.html