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
Live Demo
#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
Related Articles
- Print array elements that are divisible by at-least one other in C++
- A number is divisible by $12$. By what other numbers will that number be divisible?
- A number is divisible by both 5 and 12. By which other number will that number be always divisible?
- Minimum number of given moves required to make N divisible by 25 using C++.
- Maximum and Minimum element of a linked list which is divisible by a given number k in C++
- Find a number that divides maximum array elements in C++
- Minimum removals in a number to be divisible by 10 power raised to K in C++
- Minimum positive integer divisible by C and is not in range [A, B] in C++
- Number of substrings divisible by 8 and not by 3 in C++
- Count elements that are divisible by at-least one element in another array in C++
- Find nth number that contains the digit k or divisible by k in C++
- Which of the following statements are true?(i) If a number is divisible by 3, it must be divisible by 9.(ii) If a number is divisible by 9, it must be divisible by 3.(iii) If a number is divisible by 4, it must be divisible by 8.(iv) If a number is divisible by 8, it must be divisible by 4.(v) A number is divisible by 18, if it is divisible by both 3 and 6.(vi) If a number is divisible by both 9 and 10, it must be divisible by 90.(vii) If a number exactly divides the sum of two numbers, it must exactly divide the numbers separately.(viii) If a number divides three numbers exactly, it must divide their sum exactly.(ix) If two numbers are co-prime, at least one of them must be a prime number.(x) The sum of two consecutive odd numbers is always divisible by 4.
- Smallest number that is divisible by first n numbers in JavaScript
- Generating a random number that is divisible by n in JavaScript
- Finding a pair that is divisible by some number in JavaScript
Kickstart Your Career
Get certified by completing the course
Get Started