C++ MPIR: Looking for example usage for mpz_sizeinbase();

1.4k Views Asked by At

This is the first time I am using MPIR library. I have to do some calculations on bigintegers. Actually those numbers can have a maximum of 2048 bits. The first task I have to implement is to find the total number of bits in teh entered decimal value. Thsi erquires a the use of logarithm.

In MPIR library I found that this is a simple function that gives the total number of digit in a given base, an alternative to finding logarithm which is not available in MPIR:

size_t mpz_sizeinbase (mpz t op, int base)

Return the size of op measured in number of digits in the given base. base can vary from 2 to 36. The sign of op is ignored, just the absolute value is used. The result will be either exact or 1 too big. If base is a power of 2, the result is always exact. If op is zero the return value is always 1. This function can be used to determine the space required when converting op to a string. The right amount of allocation is normally two more than the value returned by mpz_sizeinbase, one extra for a minus sign and one for the null-terminator. It will be noted that mpz_sizeinbase(op,2) can be used to locate the most significant 1 bit in op, counting from 1. (Unlike the bitwise functions which start from 0, See Section

I am trying to use this function as follows in my program:

#include < cstdio>
#include < stdlib.h>
#include < gmpxx.h>
#include < iostream>
#include <mpirxx.h>
#include <math.h>
#include <windows.h>
void main()
{
  mpz_t opt; 
  size_t nob;
  opt=200; 
  nob= mpz_sizeinbase(opt, 10);
  cout << nob<<"\n";


}

The answer should be 3.

But I am getting the following error during compilation:

Error 13 error C2440: '=' : cannot convert from 'int' to 'mpz_t' logicaloperations.cpp 27 1 logicaloperations

Error 14 error C2664: '__gmpz_sizeinbase' : cannot convert parameter 1 from 'int' to 'mpz_srcptr' logicaloperations.cpp 28 1 logicaloperations **

This is just for testing , in my actual code I will be having values like this:

mpz_t opt= 111111111111111111111111111111111111111111111111999999999999999999999999999999999999999999999999999999999999999999999999999999999999999; 

Can you give some pointers how to use the parameters of this function correctly?

An example would be sufficient.

1

There are 1 best solutions below

2
On

Well I was able to solve this myself. This might be required in future by someone so I am posting it here.

int main()
{
 mpz_t a, b ;
 size_t nob; 
mpz_init (a); mpz_init (b);  //initialization 
mpz_set_str (b, "61754454545545454545454", 10); //large things work in strings in this world 
nob = mpz_sizeinbase(b, 2); //find how many bits are there in the binary 
cout<<nob<<"\n"; 
return 0; 

}

Now I got the point!

If someone can improve it further it will be of great help