- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find a distinct pair (x, y) in given range such that x divides y in C++
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
#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)
Advertisements
To Continue Learning Please Login
Login with Google