Minimum product modulo N possible for any pair from a given range
Last Updated :
20 Jul, 2022
Given three integers L, R, and N, the task is to find the minimum possible value of (i * j) % N, where L ? i < j ? R.
Examples:
Input: L = 2020, R = 2040, N = 2019
Output: 2
Explanation: (2020 * 2021) % 2019 = 2
Input: L = 15, R = 30, N = 15
Output: 0
Explanation: If one of the elements of the pair is 15, then the product of all such pairs will be divisible by 15. Therefore, the remainder will be 0, which is minimum possible.
Approach: The given problem can be solved by finding the difference between L and R. If the difference is at least N, then the result will be 0. Otherwise, iterate over the range [L, R] and find the minimum product.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
#define ll long long
using namespace std;
void minModulo( int L, int R, int N)
{
if (R - L < N) {
int ans = INT_MAX;
for (ll i = L; i <= R; i++)
for (ll j = L; j <= R; j++)
if (i != j)
ans = min(0ll + ans,
(i * j) % N);
cout << ans;
}
else {
cout << 0;
}
}
int main()
{
int L = 6, R = 10, N = 2019;
minModulo(L, R, N);
return 0;
}
|
Java
import java.io.*;
import java.lang.*;
import java.util.*;
public class GFG
{
static void minModulo( int L, int R, int N)
{
if (R - L < N)
{
int ans = Integer.MAX_VALUE;
for ( int i = L; i <= R; i++)
for ( int j = L; j <= R; j++)
if (i != j)
ans = Math.min(ans, (i * j) % N);
System.out.println(ans);
}
else {
System.out.println( 0 );
}
}
public static void main(String[] args)
{
int L = 6 , R = 10 , N = 2019 ;
minModulo(L, R, N);
}
}
|
Python3
def minModulo(L, R, N):
if (R - L < N):
ans = 10 * * 9
for i in range (L, R + 1 ):
for j in range (L, R + 1 ):
if (i ! = j):
ans = min (ans, (i * j) % N)
print (ans)
else :
print ( 0 )
if __name__ = = '__main__' :
L, R, N = 6 , 10 , 2019
minModulo(L, R, N)
|
C#
using System;
class GFG{
static void minModulo( int L, int R, int N)
{
if (R - L < N)
{
int ans = Int32.MaxValue;
for ( int i = L; i <= R; i++)
for ( int j = L; j <= R; j++)
if (i != j)
ans = Math.Min(ans, (i * j) % N);
Console.WriteLine(ans);
}
else
{
Console.WriteLine(0);
}
}
public static void Main( string [] args)
{
int L = 6, R = 10, N = 2019;
minModulo(L, R, N);
}
}
|
Javascript
<script>
function minModulo(L, R, N)
{
if (R - L < N)
{
let ans = Number.MAX_VALUE;
for (let i = L; i <= R; i++)
for (let j = L; j <= R; j++)
if (i != j)
ans = Math.min(ans, (i * j) % N);
document.write(ans);
}
else {
document.write(0);
}
}
let L = 6, R = 10, N = 2019;
minModulo(L, R, N);
</script>
|
Time Complexity: O((R – L)2)
Auxiliary Space: O(1), since no extra space has been taken.
Share your thoughts in the comments
Please Login to comment...