Find a distinct pair (x, y) in given range such that x divides y in C++

C++Server Side ProgrammingProgramming

Here we will see one interesting problem, we will find a pair (x, y), where x and y are in range so l <= x, y <= r, the pair will have one property, the value of x divides y. If there are multiple pairs available, then choose only one.

We can solve this problem in O(1) time, if we get the value of lower limit l and 2l. We know that the smallest value of y/x can be 2, and if some greater value is present in the range then 2 will be in range. And if we increase x, it will also increase 2x, so l and 2l will be the minimum pair to fall in given range.

Example

Live Demo

#include<iostream>
using namespace std;
void getPair(int l, int r) {
int x = l;
int y = 2 * l;
cout << "(" << x << ", " << y << ")" << endl;
}
int main() {
int l = 3, r = 6;
getPair(l, r);
}

Output

(3, 6)
Published on 24-Oct-2019 12:31:50