gpt4 book ai didi

使用大数时 GMP 溢出

转载 作者:行者123 更新时间:2023-12-04 05:55:52 28 4
gpt4 key购买 nike

我正在开发一个程序,用于在 C++ 中分解非常大的数字(20 位或更多),并且正在使用 GMP 来处理溢出问题。我的程序对于大约 10 位或更少的数字运行良好,但是当我向它抛出一个 15 位数字时,它会爆炸。我将把我的程序简化为这样一行:

#include <iostream>
#include <stdio.h>
#include <gmp.h>
#include <gmpxx.h>

using namespace std;

int main()
{
mpz_class n = 48112959837082048697; //this blows up
return 0;
}

如果我用
mpz_class n = 12623773;

然后一切正常。

这是错误:
$ g++ -o main main.cpp  -lgmpxx -lgmp
main.cpp: In function ‘int main()’:
main.cpp:21:19: error: conversion from ‘long long int’ to ‘mpz_class’ is ambiguous
/usr/include/gmpxx.h:1563:3: note: candidates are: __gmp_expr<__mpz_struct [1], __mpz_struct [1]>::__gmp_expr(double)
/usr/include/gmpxx.h:1562:3: note: __gmp_expr<__mpz_struct [1], __mpz_struct [1]>::__gmp_expr(float)
/usr/include/gmpxx.h:1560:3: note: __gmp_expr<__mpz_struct [1], __mpz_struct [1]>::__gmp_expr(long unsigned int)
/usr/include/gmpxx.h:1559:3: note: __gmp_expr<__mpz_struct [1], __mpz_struct [1]>::__gmp_expr(long int)
/usr/include/gmpxx.h:1557:3: note: __gmp_expr<__mpz_struct [1], __mpz_struct [1]>::__gmp_expr(short unsigned int)
/usr/include/gmpxx.h:1556:3: note: __gmp_expr<__mpz_struct [1], __mpz_struct [1]>::__gmp_expr(short int)
/usr/include/gmpxx.h:1554:3: note: __gmp_expr<__mpz_struct [1], __mpz_struct [1]>::__gmp_expr(unsigned int)
/usr/include/gmpxx.h:1553:3: note: __gmp_expr<__mpz_struct [1], __mpz_struct [1]>::__gmp_expr(int)
/usr/include/gmpxx.h:1551:3: note: __gmp_expr<__mpz_struct [1], __mpz_struct [1]>::__gmp_expr(unsigned char)
/usr/include/gmpxx.h:1550:3: note: __gmp_expr<__mpz_struct [1], __mpz_struct [1]>::__gmp_expr(signed char)

有人知道如何解决这个问题以便我可以使用大数字吗?我认为 GMP 应该允许 500 位数字,加号或减号。

谢谢!

最佳答案

您试图分配给 n 的号码显然太大而无法放入任何标准整数类型,这解释了 gmp 的使用,但这也意味着您(您的程序)将无法在任何容量(包括初始化/赋值函数)中将该数字用作整数.将大数分配给 mpz 的最简单方法是通过使用该数字的字符串文字表示:

mpz_class n;
n = "48112959837082048697";

请注意,组合初始化/分配将不起作用,即:
mpz_class n = "48112959837082048697";  // Error converting

旁注:您不需要包含 stdio.hgmp.h ,因为它们来自 iostreamgmpxx.h分别。

关于使用大数时 GMP 溢出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9528732/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com