This was a really fun problem, heavily leaning towards the mathematics side. First thing I did, as usual, is make a brute force solution to find S((pm#)^n) which lead to the following OEIS sequences listed below: https://oeis.org/A001047, https://oeis.org/A248225, and https://oeis.org/A248338
It was quite a fun challenge in itself to prove this statement. For those who are interested enjoy the math.
Now, let's get back into the meat of the problem
The next 2 cases are less important
And the final important case
Input an Integer (yourinput)
Code will output Q(yourinput)