Given a positive integer N, the task is to find the count of all the numbers M such that when the number N is divided by M, the quotient is equal to its remainder i.e (⌊N/M⌋ = N mod M) where ⌊ ⌋ denotes the floor value of a given number.
Input: N = 8
Explanation: When 8 is divided by 3 and 7, it returns the same Quotient and Remainder.
8 / 3 = 8 % 3, 8 / 7 = 8 % 7. Therefore, the required answer is 2.
Input: N = 1000000000000
Naive Approach: The simplest approach is based on the fact that M can not be greater than N as for any number greater than N, the quotient would be zero. Whereas, its modulo with N will always be N. Therefore, iterate through all the numbers from 1 to N and count all such numbers satisfying the given condition.
Time Complexity: O(N)
Auxiliary Space: O(1)
Efficient Approach: The optimal idea is based on the observation stated below:
If (⌊N/M⌋ = N mod M), then M + 1 must be a divisor of N.
Proof for the observation:
If ⌊N/M⌋ = N mod M, then let N / M be equal to K.
Therefore, N must be equal to K * M + K as K is the quotient as well as the remainder.
N = K * M + K
N = K * (M + 1)
Therefore, for M to be in our answer set, it is necessary that M + 1 is a divisor of N.
Note that M + 1 must be a divisor of N is a necessary condition but not a sufficient condition for ⌊N/M⌋ = N mod M.
Follow the below steps to solve the problem:
- Find all divisors of N and store them in an array. This can be computed in O(√ N) complexity.
- Check for all divisors by iterating through the array, and if divisor minus 1 satisfy the given condition ⌊N / M⌋ = N mod M, increase the count.
Below is the implementation of the above approach:
Time Complexity: O(sqrt(N))
Auxiliary Space: O(sqrt(N))
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.