VOOZH about

URL: https://www.geeksforgeeks.org/dsa/the-modulo-task/

⇱ The Modulo Task - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

The Modulo Task

Last Updated : 7 Jun, 2026

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.

[Naive Approach] Check Every Possible k - O(n) Time O(1) Space

The idea is to iterate through all values of k from 1 to n-1 and compute n % k for each value. Keep track of the maximum remainder obtained and return the corresponding value of k.


Output
3

Time Complexity: O(n)
Auxiliary Space: O(1)

[Expected Approach] Mathematical Observation - O(1) Time O(1) Space

The idea is to observe that for any k > n / 2, the quotient of n / k is 1, so the remainder becomes n - k. Since this remainder decreases as k increases, the maximum remainder is obtained for the smallest value of k greater than n/2. Therefore, the required value of k is n/2 + 1.

Let us understand with example:
For n = 4, the function computes res = n / 2 + 1.

  • 4 / 2 = 2
  • res = 2 + 1 = 3
  • The function returns 3.

Thus, the output is 3, which is the value of k for which n % k is maximum.


Output
3

Time Complexity: O(1)
Auxiliary Space: O(1)

Comment
Article Tags:
Article Tags: