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.
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:
Time Complexity: O(sqrt(N))
Auxiliary Space: O(1)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.