Naive approach: Run a loop from 1 to N + 1 and return all the unique remainders found when dividing N by any integer from the range. But this approach is not efficient for larger values of N.
Efficient approach: It can be observed that one part of the answer will always contain numbers between 0 to ceil(sqrt(n)). It can be proven by running the naive algorithm on smaller values of N and checking the remainders obtained or by solving the equation ceil(N / k) = x or x ≤ (N / k) < x + 1 where x is one of the remainders for all integers k when N is divided by k for k from 1 to N + 1. The solution to the above inequality is nothing but integers k from (N / (x + 1), N / x] of length N / x – N / (x + 1) = N / (x2 + x). Therefore, iterate from k = 1 to ceil(sqrt(N)) and store all the unique N % k. What if the above k is greater than ceil(sqrt(N))? They will always correspond to values 0 ≤ x < ceil(sqrt(N)). So, again start storing remainders from N / (ceil(sqrt(N)) – 1 to 0 and return the final answer with all the possible remainders.
Below is the implementation of the above approach:
Please Login to comment...