0

i'm havin trouble with a code that is returning a nunber that is bigger than that C can handle. I installed the GMP library but with all the tutorials that i found on the internet i can't seem to make it work. Here is the code with the GMP library's functions. Currently, im trying to make it work by reading the manuals from this site: https://gmplib.org/manual/ The Program simply crashes, i think that it is because im returning a mpz_t integer from a Int Function. how can i solve this?

EDIT: i edited the code to what Antoine said, and now i have no errors, but the program crashes when i run it.

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

typedef struct Vector{
int *v;
}vetor;

int nextPow2(int n);
int Multiplicacao(mpz_t r, int *x, int *y, int n);

int main(){

int n = 100;
vetor *x = malloc(sizeof(vetor));
vetor *y = malloc(sizeof(vetor));

srand( (unsigned)time(NULL) );
int i;

int c = 0;
i=0;
c = nextPow2(n);

x->v = malloc(sizeof(int)*c);
y->v = malloc(sizeof(int)*c);

for(i=0; i<c; i++){
    x->v[i] = 0;
    y->v[i] = 0;
}

int d = c-n;
i = c;
while(i>=d){
    x->v[i] = rand()%2;
    y->v[i] = rand()%2;
    i--;
}

printf("\n Vetor X\n");

for(i=0; i<c; i++){
    printf("%i", x->v[i]);
}

printf("\n Vetor Y\n");

for(i=0; i<c; i++){
    printf("%i", y->v[i]);
}

mpz_t r;
mpz_inits(r);

mpz_set(r, Multiplicacao(r, x->v, y->v, c));

printf("\n\n RESULTADO \n\n");
gmp_printf ("%Zd\n", r);
mpz_clear(r);

return 0;
}

int Multiplicacao(mpz_t r, int *x, int *y, int n){
if(n==1)
    return x[0]*y[0];
else{
    vetor *Xe = malloc(sizeof(vetor));
    vetor *Xd = malloc(sizeof(vetor));
    vetor *Ye = malloc(sizeof(vetor));
    vetor *Yd = malloc(sizeof(vetor));
    int j;
    Xe->v = malloc(sizeof(int)*n/2);
    Xd->v = malloc(sizeof(int)*n/2);
    Ye->v = malloc(sizeof(int)*n/2);
    Yd->v = malloc(sizeof(int)*n/2);

    for(j=0; j<n/2; j++){
        Xe->v[j]=x[j];
        Ye->v[j]=y[j];
    }
    int k=0;
    for(j=n/2; j<n; j++){
        Xd->v[k]=x[j];
        Yd->v[k]=y[j];
        k++;
    }

    mpz_t p1, p2, p3, p4, a, b;
    mpz_inits(p1, p2, p3, p4, a, b);

    mpz_ui_pow_ui(a, 2, n);
    mpz_ui_pow_ui(b, 2, n/2);


    mpz_set(p1, Multiplicacao(r, Xe->v, Ye->v, n/2));
    mpz_set(p2, Multiplicacao(r, Xe->v, Yd->v, n/2));
    mpz_set(p3, Multiplicacao(r, Xd->v, Ye->v, n/2));
    mpz_set(p4, Multiplicacao(r, Xd->v, Yd->v, n/2));

    mpz_mul(p1, p1, a);
    mpz_mul(p2, p2, b);
    mpz_mul(p3, p3, b);

    mpz_add(p1, p1, p2);
    mpz_add(p3, p3, p4);
    mpz_add(p1, p1, p3);

    return p1;
}
}

int nextPow2(int n)
{
if ( n <= 1 ) return n;
double d = n-1;
return 1 << ((((int*)&d)[1]>>20)-1022);
}
Hamilton D
  • 11
  • 3

0 Answers0