2
$\begingroup$

I fail to use PrimeQ in Solve. Simple example:

Solve[PrimeQ[p] && 0 < p < 5, p, Integers]

yields {} rather than {{p -> 2}, {p -> 3}}.

How can this be fixed (for more complex problems)?


There's the same issue with OddQrather than PrimeQ, but I know workarounds, like

Solve[p == 2 k + 1 && 0 < p < 5, {p, k}, Integers]
$\endgroup$
0

1 Answer 1

8
$\begingroup$

PrimeQ is a predicate that only ever evaluates to True or False. It does not indicate that $p$ should be a prime number. It shares this behavior with all other *Q predicates, like OddQ.

Instead, you could use either one of the following options:

Solve[{0 < p < 5, p ∈ Primes}, p]
Solve[0 < p < 5, p, Primes]

(* Out: {{p -> 2}, {p -> 3}} *)

To see what is happening in your attempt, take a look at the Trace results:

Solve[{PrimeQ[p], 0 < p < 5}, p] // Trace

trace output showing that primeq[p] is immediately evaluated to false

As you can see, PrimeQ[p] is immediately evaluated to False because p is not manifestly a prime number. This behavior is also indicated in the documentation of PrimeQ.

$\endgroup$
1
  • $\begingroup$ p ∈ Primes or Element[p, Primes] rather than PrimeQ[p], that's great! $\endgroup$
    – fgrieu
    Commented Jan 2, 2023 at 10:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.