简体   繁体   中英

return type while using GMP.h header file

While I'm using gmp.h header file. I need a function which takes inputs of type mpz_t and return mpz_t type too. I'm very beginner of using gmp.h So, Here is snaps follows of my approached code...

mpz_t sum_upto(mpz_t max)  
{    
    mpz_t sum;  
    mpz_init(sum);    
    mpz_init(result);  
    for(int i=0;i<=max-1;i++)    
        mpz_add_ui(sum,sum,pow(2,i));   
    return sum;   
}

but it will show error:

  1. pow has been not used in this scope.", although I have added math.h at the very beginning of the file.
  2. sum_upto declared as function returning an array...

The convention for functions using GMP can be found in the manual . Essentially, you must follow the same conventions that GMP itself does - the function must have a void return type, and you must provide a value into which to put the result as a parameter.

Here is the example given:

 void foo (mpz_t result, const mpz_t param, unsigned long n)
 {
   unsigned long  i;
   mpz_mul_ui (result, param, n);
   for (i = 1; i < n; i++)
     mpz_add_ui (result, result, i*7);
 }

 int main (void)
 {
   mpz_t  r, n;
   mpz_init (r);
   mpz_init_set_str (n, "123456", 0);
   foo (r, n, 20L);
   gmp_printf ("%Zd\n", r);
   return 0;
 }

Try the following:

mpz_t sum_upto(mpz_t max)
{
    mpz_t sum;
    mpz_init(sum);
    mpz_init(result);
    int val = 1;
    for(int i=0;i<=max-1;i++) {
        mpz_add_ui(sum,sum,val);
        val *= 2; //compiler should make a shift operation out of it
    }
    return sum;
}

Furthermore you can possibly drop the math.h header.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM