Closest Divisors in C++


Suppose we have an integer num, we have to find the closest two integers in absolute difference whose product equals num + 1 or num + 2. We have to find the two integers in any order. So if the input is 8, then the output will be [3, 3], for num + 1, it will be 9, the closest divisors are 3 and 3, for num + 2 = 10, the closest divisors are 2 and 5, hence 3 and 3 are chosen.

To solve this, we will follow these steps −

  • Define a method called getDiv(), this will take x as input

  • diff := infinity, create an array called ret of size 2

  • for i := 1, if i^2 <= x, then increase i by 1

    • if x is divisible by i, then

      • a := i

      • b := x / i

      • newDiff := |a – b|

      • if newDiff < diff, then

        • diff := newDiff

        • ret[0] := a and ret[1] := b

  • return ret

  • From the main method find op1 := getDiv(num + 1) and op2 := getDiv(num + 2)

  • return op1 when |op1[0] – op[1]| <= |op2[0] – op2[1]|, otherwise op2

Example (C++)

Let us see the following implementation to get better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<auto> v){
   cout << "[";
   for(int i = 0; i<v.size(); i++){
      cout << v[i] << ", ";
   }
   cout << "]"<<endl;
}
class Solution {
public:
   vector <int> getDiv(int x){
      int diff = INT_MAX;
      vector <int> ret(2);
      for(int i = 1; i * i <= x; i++){
         if(x % i == 0){
            int a = i;
            int b = x / i;
            int newDiff = abs(a - b);
            if(newDiff < diff){
               diff = newDiff;
               ret[0] = a;
               ret[1] = b;
            }
         }
      }
      return ret;
   }
   vector<int> closestDivisors(int num) {
      vector <int> op1 = getDiv(num + 1);
      vector <int> op2 = getDiv(num + 2);
      return abs(op1[0] - op1[1]) <= abs(op2[0] - op2[1]) ? op1 : op2;
   }
};
main(){
   Solution ob;
   print_vector(ob.closestDivisors(8));
}

Input

8

Output

[3,3]

Updated on: 29-Apr-2020

258 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements