tags:

views:

8

answers:

1

I have a problem in which I need to be prepared to explore a larger range of numbers than an unsized long long can represent (the range being represented by 3^(n*n) ). I have been advised by this community to use GMP for multiple-precision numbers. Since I need to iterate through the range one number at a time, I need a way to increment my counter easily.

My impulse is to use "mpz_add_ui(my_counter, my_counter, 1UL);", but I am worried that passing my counter as both the return argument and as an addend may cause the result to be corrupted. If the function changes the return operator while it calculates the answer, it may change the number in such a way that the answer will turn out wrong. It is unlikely that incrementing will cause any trouble, but what about adding two large mpz_t's? Or multiplying, or even exponentiation? The documentation has nothing to either calm or confirm my concerns. I've tried looking at the source code, but the combination of macros, sparse comments, and leaping from one file to another has lead me to conclude I am not good enough a programmer yet to follow it.

To be safe, I have written a function that shows the format I am fairly certain will work, but I would much rather avoid it because I am certain it will slow my program down:

void mpz_increment(mpz_t) {  
    mpz_t temp;  
    mpz_init(temp);  
    mpz_add_ui(temp, a, 1UL);  
    mpz_set(a, temp);  
    mpz_clear(temp);  
}

So, my question is this. Is it safe to pass a multiple-precision type to a GMP arithmetic function as both the return argument and one of the operands, or will doing so result in corrupted results?

+1  A: 

Yes, you can pass the same instance as a input and output parameter. This is stated explicitly in the "Variable Conventions" section of the documentation:

GMP lets you use the same variable for both input and output in one call. For example, the main function for integer multiplication, mpz_mul, can be used to square x and put the result back in x with

 mpz_mul (x, x, x);
Matthew Flaschen
Ha ha, so it does. Thanks for pointing that out!
gamecoder