pari gp return function store in variable

818 views Asked by At

I'm new to pari gp, and just trying out, playing with it. i have an inverse function that goes like this.

inverse (a,n) = 
{
  negative = false;

  if (a < 0, negative = true);
  if (a < 0, a= a*-1);

  i = n;
  v = 0;
  d = 1;

  while (a>0,t=i/a; x =a;
        a = i % x;
        i = x;
        x = d;
        d = v - t*x;
        v = x);
    v %= n;

  if (v < 0, v = (v+n)%n);


  if (negative == true, return (-v));

  return (v);
};

so i have sort of a main function, which consist of something like this.

while (i<n,i++;
    while(j<n,j++;
      // some other codes
      temp1 = inverse(temp,modulus)));

I got an error that says incorrect type in &[] 0Ccompo1ptr [not a vector] (t_INT) i am quite sure that the rest of the code is work fine, since the error only occurred when i place

temp1 = inverse (temp,modulus)

in.

2

There are 2 answers

0
Andrew On

Part of the problem here is that you are not scoping variables in the function. In particular you are using i both inside the function and out. None of this is explained well in the PARI user manual. To make a variable local you need to do something like my(i=n); Some variables are automatically scoped such as arguments to functions and sum(i=1,10,i); vector(10,i,i^2); for(i=1,10,...) etc, but not simple assignments like i=n. Also note PARI does not have boolean constants true and false. Your code works in this case because you are doing negative==true which is just comparing polynomials with the indeterminants of true of and false.

0
Charles On

Replacing your function with one with properly-scoped variables should solve the problem. Try this:

inverse (a,n) = 
{
  if (a < 0, return(-inverse(-a, n)));
  my(i = n, v = 0, d = 1);
  while (a > 0,
    my(x = a, t);
    [t, a] = divrem(i,a);
    i = x;
    [d, v] = [v - t*x, d];
  );
  v % n;
}