Consider only the range [1, K*(b-a+1)] from the values of Q. Among this range, if we divide it into b-a+1 equal parts each of size K, then for any integer in the 1st part i.e. [1, K] we return 1, for 2nd part [K+1, 2K] return 2 and so on.
Thus int((Q-1)/K)+1 will return random integer in the rang...