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.
Examples:
Input: A = 6, B = 3, N = 15
Output: 3
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
Output: 2
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:
C++
#include <bits/stdc++.h>
using namespace std;
void countValues( int A, int B, int C)
{
if (B >= A) {
cout << 0;
return ;
}
if (B == 0) {
cout << C / A;
return ;
}
int ans = C / A;
if (ans * A + B <= C) {
ans++;
}
cout << ans;
}
int main()
{
int A = 6, B = 3, N = 15;
countValues(A, B, N);
return 0;
}
|
Java
public class MyClass
{
static void countValues( int A, int B, int C)
{
if (B >= A) {
System.out.println( 0 );
return ;
}
if (B == 0 ) {
System.out.println(C / A);
return ;
}
int ans = C / A;
if (ans * A + B <= C) {
ans++;
}
System.out.println(ans);
}
public static void main(String args[])
{
int A = 6 , B = 3 , N = 15 ;
countValues(A, B, N);
}
}
|
Python3
def countValues(A, B, C):
if (B > = A):
print ( 0 )
return
if (B = = 0 ):
print (C / / A)
return
ans = C / / A
if (ans * A + B < = C):
ans + = 1
print (ans)
if __name__ = = '__main__' :
A = 6
B = 3
N = 15
countValues(A, B, N)
|
C#
using System;
using System.Collections.Generic;
class GFG{
static void countValues( int A, int B, int C)
{
if (B >= A)
{
Console.Write(0);
return ;
}
if (B == 0)
{
Console.Write(C / A);
return ;
}
int ans = C / A;
if (ans * A + B <= C)
{
ans++;
}
Console.Write(ans);
}
public static void Main()
{
int A = 6, B = 3, N = 15;
countValues(A, B, N);
}
}
|
Javascript
<script>
function countValues(A, B, C)
{
if (B >= A) {
document.write(0);
return ;
}
if (B == 0) {
document.write(parseInt(C / A));
return ;
}
let ans = parseInt(C / A);
if (ans * A + B <= C) {
ans++;
}
document.write(ans);
}
let A = 6, B = 3, N = 15;
countValues(A, B, N);
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Last Updated :
05 Jul, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...