Given an integer n, the task is to count the number of pairs (i, j) such that ((n % i) % j) % n is maximized where 1 ≤ i, j ≤ n
Input: n = 5
(3, 3), (3, 4) and (3, 5) are the only valid pairs.
Input: n = 55
Naive Approach: To obtain the maximum remainder value, n has to be divided by (n / 2) + 1. Store max = n % ((n / 2) + 1), now check for all possible values of i and j. If ((n % i) % j) % n = max then update count = count + 1. Print the count in the end.
Time Complexity: O(n2)
Efficient Approach: Get the maximum value for remainder i.e. max = n % num where num = ((n / 2) + 1). Now i has to be chosen as num in order to obtain the maximum value and j can be chosen as any value from the range [max, n] because we don’t need to reduce the maximum value calculated and choosing j > max will not affect the previous value obtained. So the total pairs will be n – max.
This approach will not work for n = 2. This is because, for n = 2, maximum remainder will be 0 and n – max will give 2 but we know that the answer is 4. All possible pairs in this case are (1, 1), (1, 2), (2, 1) and (2, 2).
Below is the implementation of the above approach:
# Python3 implementation of the approach
# Function to return the count of required pairs
# Special case
if (n == 2):
# Number which will give the max value
# for ((n % i) % j) % n
num = ((n // 2) + 1);
# To store the maximum possible value
# of ((n % i) % j) % n
max = n % num;
# Count of possible pairs
count = n – max;
# Driver code
if __name__ ==”__main__” :
n = 5;
# This code is contributed by Code_Mech
Time Complexity: O(1)
- Count pairs with Odd XOR
- Count pairs with given sum | Set 2
- Count pairs (i,j) such that (i+j) is divisible by A and B both
- Count number of pairs (A <= N, B <= N) such that gcd (A , B) is B
- Count Pairs from two arrays with even sum
- Count pairs (a, b) whose sum of squares is N (a^2 + b^2 = N)
- Count pairs (a, b) whose sum of cubes is N (a^3 + b^3 = N)
- Count of pairs (x, y) in an array such that x < y
- Count of pairs from 1 to a and 1 to b whose sum is divisible by N
- Count ordered pairs with product less than N
- Count pairs from two arrays having sum equal to K
- Count pairs with set bits sum equal to K
- Count pairs with sum as a prime number and less than n
- Count pairs (A, B) such that A has X and B has Y number of set bits and A+B = C
- Count pairs in an array such that frequency of one is at least value of other
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.