Problem Statement  
NOTE: This problem statement contains subscripts that may not display properly if viewed outside of the applet. Let's consider an infinite sequence A defined as follows:
 
Definition  
 
Notes  
  [x] denotes the floor function of x which returns the highest integer less than or equal to x. For example, [3.4] = 3, [0.6] = 0.  
Constraints  
  n will be between 0 and 10^13, inclusive.  
  p and q will both be between 2 and 10^9, inclusive.  
  x and y will both be between 0 and 10^9, inclusive.  
Examples  
0)  
 
1)  
 
2)  
 
3)  
