C++中两个大十六进制数的mod [复制]

q0qdq0h2  于 2023-11-19  发布在  其他
关注(0)|答案(2)|浏览(153)

此问题在此处已有答案

Mod of two large numbers in C++(1个答案)
6天前关闭
我有两个大的十六进制数,每个至少有70位(十进制),我试图计算值hex_a%hex_b:

  1. string hex_a="1133A5DCDEF3216A63EB879A82F5A1DC4490CCF6412492CF1B242DB";
  2. string hex_b="AAB3A5DCDEF3216A6AAA2F5A1DC4490CCF6412492CF1B242DB";

字符串
我尝试用stoi将两个十六进制数转换为十进制数,并将值存储在字符串中:

  1. string a=to_string(stoi(hex_a, 0, 16));


但是我在使用stoi方法时得到一个错误:

  1. terminate called after throwing an instance of 'std::out_of_range'
  2. what(): stoi
  3. Aborted (core dumped)


如何在C++中计算两个大数字的模?

blmhpbnm

blmhpbnm1#

您可以使用boost/multiprecision/cpp_int

  1. #include <boost/multiprecision/cpp_int.hpp>
  2. #include <iostream>
  3. #include <sstream>
  4. #include <string>
  5. using boost::multiprecision::cpp_int;
  6. int main() {
  7. std::string hex_a = "0x1133A5DCDEF3216A63EB879A82F5A1DC4490CCF6412492CF1B242DB";
  8. std::string hex_b = "0xAAB3A5DCDEF3216A6AAA2F5A1DC4490CCF6412492CF1B242DB";
  9. cpp_int a(hex_a), b(hex_b);
  10. cpp_int result = a % b;
  11. std::cout << "Result as int: " << result << '\n';
  12. std::stringstream ss;
  13. ss << std::hex << result;
  14. std::string result_hex = ss.str();
  15. std::cout << "Result as hex: 0x" << result_hex << '\n';
  16. return 0;
  17. }

字符串
或者GNU Multiple Precision Arithmetic Library (GMP),这可能更快:

  1. #include <gmp.h>
  2. int main() {
  3. mpz_t a, b, result;
  4. mpz_init(a);
  5. mpz_init(b);
  6. mpz_init(result);
  7. mpz_set_str(a, "1133A5DCDEF3216A63EB879A82F5A1DC4490CCF6412492CF1B242DB", 16);
  8. mpz_set_str(b, "AAB3A5DCDEF3216A6AAA2F5A1DC4490CCF6412492CF1B242DB", 16);
  9. mpz_mod(result, a, b);
  10. gmp_printf("Result as int: %Zd\n", result);
  11. gmp_printf("Result as hex: Ox%Zx\n", result);
  12. mpz_clear(a);
  13. mpz_clear(b);
  14. mpz_clear(result);
  15. return 0;
  16. }

输出:

  1. Result as int: 887778964514700662847592530576646032246936850244260028835776
  2. Result as hex: 0x8d6e6cdeb792c9d42b257481c738989f678484c94fd6b567c0


在Python中确认相同的结果:

  1. >>> hex_a = "0x1133A5DCDEF3216A63EB879A82F5A1DC4490CCF6412492CF1B242DB"
  2. >>> hex_b = "0xAAB3A5DCDEF3216A6AAA2F5A1DC4490CCF6412492CF1B242DB"
  3. >>> a = int(hex_a, 16)
  4. >>> b = int(hex_b, 16)
  5. >>> result = a % b
  6. >>> print(f'Result as int: {result}')
  7. Result as int: 887778964514700662847592530576646032246936850244260028835776
  8. >>> print(f'Result as hex: 0x{result:x}')
  9. Result as hex: 0x8d6e6cdeb792c9d42b257481c738989f678484c94fd6b567c0

展开查看全部
l2osamch

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

相关问题