2012-03-02 79 views
2

我正在研究一個程序,用C++計算非常大的數字(20位或更多),並使用GMP來處理溢出問題。我的程序對於大約10位數或更少的數字運行良好,但是當我向它輸入15位數字時,它會爆炸。我會煮我的程序下來只是這樣一行:使用大數字時GMP溢出

#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位數字,加號或減號。

謝謝!

回答

3

您試圖分配給n的數字顯然太大,不適合任何標準整數類型,這解釋了gmp的使用,但這也意味着您(您的程序)將無法使用該數字作爲任何容量的整數(包括初始化/賦值函數)。以大量分配給mpz最簡單的方法是通過使用數字的字符串字面表示:

mpz_class n; 
n = "48112959837082048697"; 

注意結合初始化/分配將無法正常工作,即:

mpz_class n = "48112959837082048697"; // Error converting 

旁註:您不需要包含stdio.hgmp.h,因爲它們分別包含在iostreamgmpxx.h之間。