Search code examples
pari

How can I know if a number is inside a list in PARI/GP?


I am trying to know if a number is inside a PARI/GP list but I do not know how to do it, this is my code:

mylist = listcreate();

... here I add some numbers with  listput(mylist,XXXX)

/* How can I do the condition in the if... */
if(mynumber in mylist,print("SUCCESS"),print("ERROR"))

I am migrating from Python to PARI/GP some of my scripts and I am lost in those basic things, the manual is a little bit difficult to follow. Thank you!


Solution

  • You can test if a given value is in a list, vector, or column vector like so:

    inList(list, value)=for(i=1,#list, if(list[i]==value, return(i))); 0
    

    or less efficiently like

    inlist(list, value)=#select(n->n==value, list) > 0
    

    Your example would then look like

    if(inList(mylist, mynumber), print("SUCCESS"), print("ERROR"))
    

    But if you're going to be doing a lot of queries, it's worthwhile to use a binary search instead:

    myset = Set(mylist);
    if(setsearch(myset, mynumber), print("SUCCESS"), print("ERROR"))