![]() |
VOOZH | about |
Given an integer n. find an integer k for which n % k is the largest where 1 ≤ k < n.
Examples :
Input: n = 3
Output: 2
Explanation:
3 % 1 = 0
3 % 2 = 1
So, the modulo is highest for 2.
Input: n = 4
Output: 3
Explanation:
4 % 1 = 0
4 % 2 = 0
4 % 3 = 1
So, the modulo is highest for 3.
Table of Content
The idea is to iterate through all values of
kfrom1ton-1and computen % kfor each value. Keep track of the maximum remainder obtained and return the corresponding value ofk.
3
Time Complexity: O(n)
Auxiliary Space: O(1)
The idea is to observe that for any
k > n / 2, the quotient ofn / kis1, so the remainder becomesn - k. Since this remainder decreases askincreases, the maximum remainder is obtained for the smallest value ofkgreater thann/2. Therefore, the required value ofkisn/2 + 1.
Let us understand with example:
For n = 4, the function computes res = n / 2 + 1.
4 / 2 = 2res = 2 + 1 = 33. Thus, the output is 3, which is the value of k for which n % k is maximum.
3
Time Complexity: O(1)
Auxiliary Space: O(1)