Count numbers less than N whose modulo with A is equal to B
Given three non-negative integers A, B, and N where A is non-zero, the task is to find the number of integers less than or equal to N whose modulo with A gives the value B.
Input: A = 6, B = 3, N = 15
Explanation: The numbers 3, 9 and 15 are less than or equal to N (= 15) and their modulo with A (= 6) is equal to B (= 3). Therefore, the count such numbers is 3.
Input: A = 4, B = 1, C = 8
Approach: The given problem can be solved by using an observation based on mathematics. Follow the steps below to solve the problem:
- If the value of B is at least A, then print 0, as there can’t be any such numbers whose modulo with A gives the value B.
- Otherwise, If the value of B is 0, then print the value of C / A as the count of such numbers whose modulo with A gives the value B.
- Otherwise, perform the following steps:
- Initialize a variable, say ans, with the floor value of C / A.
- If the value of (ans * A + B) is less than or equal to N, then increment the value of ans by 1.
- After completing the above steps, print the value of ans as the count of such numbers whose modulo with A gives the value B.
Below is the implementation of the above approach:
Time Complexity: O(1)
Auxiliary Space: O(1)
Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.