Check if N leaves only distinct remainders on division by all values up to K
Last Updated :
02 Aug, 2022
Given a two integers N and K, the task is to check if N leaves only distinct remainders when divided by all integers in the range [1, K]. If so, print Yes. Otherwise, print No.
Examples:
Input: N = 5, K = 3
Output: Yes
Explanation:
(5 % 1) == 0
(5 % 2) == 1
(5 % 3) == 2
Since all the remainders {0, 1, 2} are distinct.
Input: N = 5, K = 4
Output: No
Explanation:
(5 % 1) == 0
(5 % 2) == 1
(5 % 3) == 2
(5 % 4) == 1, which is not distinct.
Approach:
Follow the steps given below to solve the problem:
- Initialize a set S
- Iterate over the range [1, K].
- In each iteration, check if N % i is already present in the Set S or not.
- If not present, then insert N % i into the set S
- Otherwise, print No and terminate.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
bool is_distinct( long long n, long long k)
{
unordered_set< long long > s;
for ( int i = 1; i <= k; i++) {
long long tmp = n % i;
if (s.find(tmp) != s.end()) {
return false ;
}
s.insert(tmp);
}
return true ;
}
int main()
{
long long N = 5, K = 3;
if (is_distinct(N, K))
cout << "Yes" ;
else
cout << "No" ;
return 0;
}
|
Java
import java.util.*;
class GFG{
static boolean is_distinct( long n, long k)
{
HashSet<Long> s = new HashSet<Long>();
for ( int i = 1 ; i <= k; i++)
{
long tmp = n % i;
if (s.contains(tmp))
{
return false ;
}
s.add(tmp);
}
return true ;
}
public static void main(String[] args)
{
long N = 5 , K = 3 ;
if (is_distinct(N, K))
System.out.print( "Yes" );
else
System.out.print( "No" );
}
}
|
Python3
def is_distinct(n, k):
s = set ()
for i in range ( 1 , k + 1 ):
tmp = n % i
if (tmp in s):
return False
s.add(tmp)
return True
if __name__ = = '__main__' :
N = 5
K = 3
if (is_distinct(N, K)):
print ( "Yes" )
else :
print ( "No" )
|
C#
using System;
using System.Collections.Generic;
class GFG{
static bool is_distinct( long n, long k)
{
HashSet< long > s = new HashSet< long >();
for ( int i = 1; i <= k; i++)
{
long tmp = n % i;
if (s.Contains(tmp))
{
return false ;
}
s.Add(tmp);
}
return true ;
}
public static void Main(String[] args)
{
long N = 5, K = 3;
if (is_distinct(N, K))
Console.Write( "Yes" );
else
Console.Write( "No" );
}
}
|
Javascript
<script>
function is_distinct(n, k)
{
let s = new Set();
for (let i = 1; i <= k; i++)
{
let tmp = n % i;
if (s.has(tmp))
{
return false ;
}
s.add(tmp);
}
return true ;
}
let N = 5, K = 3;
if (is_distinct(N, K))
document.write( "Yes" );
else
document.write( "No" );
</script>
|
Time complexity: O(K)
Auxiliary space: O(K)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...