Raveesh_Kumar
Raveesh_Kumar

Reputation: 41

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...

Upvotes: 4

Views: 3002

Answers (3)

dsarvan
dsarvan

Reputation: 39

A return of an mpz_t doesn't return the object, only a pointer, and this is almost certainly not what's wanted.

Here's an example accepting an mpz_t parameter, doing a calculation, and storing the result to the indicated parameter.

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

mpz_t *sum_upto(mpz_t *sum, int max) {
    mpz_t nval;
    mpz_init(nval);

    for (int i = 0; i < max; i++) {
        mpz_ui_pow_ui(nval, 2, i); /* nval = pow(2, i) */
        mpz_add(*sum, *sum, nval); /* sum = sum + nval */
    }

    return sum;
}

int main() {

    mpz_t sum;
    mpz_init_set_ui(sum, 0);

    gmp_printf("%Zd\n", sum_upto(&sum, 1000));
    mpz_clear(sum);

    return 0;
}

Upvotes: -1

heuristicus
heuristicus

Reputation: 1138

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

Upvotes: 9

ablaeul
ablaeul

Reputation: 2798

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.

Upvotes: -1

Related Questions