Question

I'm working on a program to factor very large numbers (20 digits or more) in C++ and am using GMP to deal with overflow issues. My program is working well for numbers of about 10 digits or less, but when I throw a 15 digit number at it, it blows up. I'm going to boil my program down to simply one line like this:

#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;
}    

If I replace that line with

mpz_class n = 12623773;

then everything works just fine.

Here is the error:

$ 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)

Anybody know how to fix this so that I can use large numbers? I thought that GMP was supposed to allow something like 500 digits, plus or minus.

Thanks!

Was it helpful?

Solution

The number you are attempting to assign to n is obviously too large to fit into any of the standard integer types, which explains the use of gmp, but this also means you (your program) will be unable to use the number as a integer in any capacity (including initialization/assignment functions). The easiest way to assign a large number to an mpz is by using a string literal representation of that number:

mpz_class n;
n = "48112959837082048697";

Note that combined initialization/assignment will not work, ie:

mpz_class n = "48112959837082048697";  // Error converting

Side note: You do not need to include stdio.h and gmp.h, as they are included from iostream and gmpxx.h respectively.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top