
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Minimum Value That Divides One Number and Divisible by Other in C++
Problem statement
Given two integer p and q, the task is to find the minimum possible number x such that q % x = 0 and x % p = 0. If the conditions aren’t true for any number, then print -1.
Example
If p = 3 and q = 66 then answer is 3 as: 66 % 3 = 0 3 % 3 = 0
Algorithm
- If a number x satisfies the given condition, then it’s obvious that q will be divided by p i.e. q % p = 0 because x is a multiple of p and q is a multiple of x
- So the minimum possible value of x will be the GCD of p and q and when q is not divisible by p then no number will satisfy the given condition
Example
#include <bits/stdc++.h> using namespace std; int getMinValue(int p, int q) { if (q % p == 0) { return __gcd(p, q); } return -1; } int main() { int p = 3; int q = 66; cout << "Minimum value = " << getMinValue(p, q) << endl; return 0; }
When you compile and execute above program. It generates following output −
Output
Minimum value = 3
Advertisements