Hey guys , i’m new to competitive . I know this problem requires fermat little theorem and i know it very well . My question is how to figure out values of p and q and hence p/q i.e to calculate possible values which is p and total values which is q.

Thanks in advance.