Pair with min absolute difference and whose product is N+1 or N+2
Last Updated :
18 Mar, 2021
Given an integer N, the task is to find a pair such that whose product is N + 1 or N + 2 and absolute difference of the pair is minimum.
Examples:
Input: N = 8
Output: 3, 3
Explanation: 3 * 3 = 8 + 1
Input: N = 123
Output: 5, 25
Explanation: 5 * 25 = 123 + 2
Approach: The idea is to Iterate a loop with a loop variable i from sqrt(N+2) to 1, and check the following conditions:
- if (n + 1) % i = 0, then we will print the pair (i, (n + 1) / i).
- if (n + 2) % i = 0, then we will print the pair (i, (n + 2) / i).
- The first pair printed will be the pair with minimum absolute difference.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void closestDivisors( int n)
{
for ( int i = sqrt (n + 2);
i > 0; i--) {
if ((n + 1) % i == 0) {
cout << i << ", "
<< (n + 1) / i;
break ;
}
if ((n + 2) % i == 0) {
cout << i << ", "
<< (n + 2) / i;
break ;
}
}
}
int main()
{
int N = 123;
closestDivisors(N);
}
|
Java
import java.util.*;
class GFG{
static void closestDivisors( int n)
{
for ( int i = ( int )Math.sqrt(n + 2 ); i > 0 ; i--)
{
if ((n + 1 ) % i == 0 )
{
System.out.print(i + ", " +
(n + 1 ) / i);
break ;
}
if ((n + 2 ) % i == 0 )
{
System.out.print(i + ", " +
(n + 2 ) / i);
break ;
}
}
}
public static void main(String[] args)
{
int N = 123 ;
closestDivisors(N);
}
}
|
Python
from math import sqrt, ceil, floor
def closestDivisors(n):
for i in range (ceil(sqrt(n + 2 )), - 1 , - 1 ):
if ((n + 1 ) % i = = 0 ):
print (i, "," , (n + 1 ) / / i)
break
if ((n + 2 ) % i = = 0 ):
print (i, "," , (n + 2 ) / / i)
break
if __name__ = = '__main__' :
N = 123
closestDivisors(N)
|
C#
using System;
class GFG{
static void closestDivisors( int n)
{
for ( int i = ( int )Math.Sqrt(n + 2); i > 0; i--)
{
if ((n + 1) % i == 0)
{
Console.Write(i + ", " +
(n + 1) / i);
break ;
}
if ((n + 2) % i == 0)
{
Console.Write(i + ", " +
(n + 2) / i);
break ;
}
}
}
public static void Main( string [] args)
{
int N = 123;
closestDivisors(N);
}
}
|
Javascript
<script>
function closestDivisors(n)
{
for ( var i = parseInt(Math.sqrt(n + 2));
i > 0; i--) {
if ((n + 1) % i == 0) {
document.write(i+ ", " +parseInt((n + 1) / i));
break ;
}
if ((n + 2) % i == 0) {
document.write(i+ ", " +parseInt((n + 2) / i));
break ;
}
}
}
N = 123;
closestDivisors(N);
</script>
|
Time Complexity: O(sqrt(N))
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...