Search code examples
primesparipari-gp

Pari GP - Checking if user keyed in a prime number


I am currently learning how to use Pari GP and right now i am trying to write out a code on checking whether if the user did key in a prime number or not.

Here is my code.

printf("\t%s \n","PrimeNo(P): To check if it is a prime or not");

PrimeNo(p)={

if(isprime(p)||1, print("Prime numbers only"));

if(isprime(p)||0, print("Prime numbers stored"));

print(p);

}

Problem is my first "if" line works by identifying that it was not a prime, but when i key in a prime number, both line appeared.

Would appreciate if anyone can help.


Solution

  • Your if statements have two tests each, so both are true if p is prime (the first if isprime(p) OR 1, the second if isprime(p) OR 0). I think you want something like:

    PrimeNo(p) = { if( isprime(p), print("Yep"), print("Nope") ); print(p); }
    

    Here we're using the if-then-else form of Pari/GP's if, so we do the first item if isprime(p) is true and the second item if it is false. This also has the advantage of only calling isprime once, which is important if your numbers are large (one can also debate ispseudoprime vs. isprime but there is no difference for 64-bit inputs).