Given two integers N and K where N, K > 0, the task is to find the total number of pairs (a, b) where 1 ≤ a, b ≤ N such that a % b = K.
Input: N = 4, K = 2
Only valid pairs are (2, 3) and (2, 4).
Input: N = 11, K = 5
Naive approach: Run two loop from 1 to n and count all the pairs (i, j) where i % j = K. The time complexity of this approach will be O(n2).
Efficient approach: Initially total count = N – K because all the numbers from the range which are > K will give K as the remainder after dividing it. After that, for all i > K there are exactly (N – K) / i numbers which will give remainder as K after getting divided by i.
Below is the implementataion of the above approach:
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.
- Find the number of pairs such that their gcd is equals to 1
- Find number of pairs in an array such that their XOR is 0
- Find number of pairs (x, y) in an Array such that x^y > y^x | Set 2
- Find the maximum cost of an array of pairs choosing at most K pairs
- Number of pairs such that path between pairs has the two vertices A and B
- Find all pairs (a, b) in an array such that a % b = k
- Find all Pairs possible from the given Array
- Find sum of a[i]%a[j] for all valid pairs
- Find the maximum possible value of a[i] % a[j] over all pairs of i and j
- Find minimum GCD of all pairs in an array
- Given two unsorted arrays, find all pairs whose sum is x
- Find all pairs (a,b) and (c,d) in array which satisfy ab = cd
- Find the sum of all possible pairs in an array of N elements
- Find all the intersecting pairs from a given array
- Find the GCD of LCM of all unique pairs in an Array
- Find the count of even odd pairs in a given Array
- Number of pairs with Bitwise OR as Odd number
- Find k pairs with smallest sums in two arrays
- Find two non-overlapping pairs having equal sum in an Array
- Find the minimum value of the given expression over all pairs of the array
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.