I would be surprised if this question hasn't appeared before so apologies in advance if answering a duplicate
We'll do question 2 first
Because $p$ and $q$ are coprime, each of $q, 2q,\ldots,(p-1)q$ will leave a different non-zero remainder when divided by $p$ and this set exhausts all possible remainders apart from zero. Hence, if we require a number of pencils, $x$ which is larger than $(p-1)q$ we can form that number by first identifying the appropriate remainder when $x$ is divided by $p$ and then adding an appropriate multiple of $p$ pencils to achieve $x$.
Since the remainder of $(p-1)q$ is the last to be picked up, the highest number of pencils which we cannot buy is $(p-1)q - p = pq-p-q$
This means the answer to question 1 is
$(38 \times 31) - 38 - 31 = 1109$
And question 3
If $p$ and $q$ are not relatively prime, then they share a common factor $d > 1$ so any number of pencils not divisible by $d$ cannot be bought and there is no highest number.