Problem Statement (Simplified):
For a given range
q, find the highest common factor of two given numbers, i.e.
b. If no such number exists, return -1.
Input: 8 12 4 2 10 3 7 2 2 5 6 Output: 4 4 2 -1 Explanation: For 8 and 12, common divisors are [1,2,4]. In the range [2,10] we have 4 which is the maximum divisor in range. In the range [3,7] we have 4 which is the maximum divisor in range. In the range [2,2] we have 2 which is the maximum divisor in range. In the range [5,6], there lies no divisor so we print -1.
Solving Approach :
1) The Highest common factor of any both numbers will be
gcd(a,b)and there exists no factor above this.
2) So, to calculate all the factors we refer the best sites to learn coding and check all number which divide
bboth from 1 to
gcd(a,b)and save them in an array.
3) We sort the array containing all common factors so that all factors are organized and searching factors in the range are easier.
4) Highest common factor in the given range [
p,q] can be found by searching lower bound of
pand upper bound of
>* Upper Bound: Upper bound of any number
Kreturns the position of immediate next number which exists in the array and is just greater than
>* Lower Bound: Lower bound of any number
Kreturns the position of immediate previous number which exists in the array and is just smaller than
5) If the lower bound of
pand upper bound of
qis the same that means, there is no common factor in the range [
6) If they are not same, the Highest Common factor in range will be the previous element to element at upper bound of
q, as an element at the upper bound is greater than
q, and element previous to it will be smaller than
qand will be a common factor. Hence it is our answer, so we return the element.
Let given numbers be
gcd(a,b)as no factor lies beyond
gcd(a,b)which divided both numbers, hence,
We check all numbers between 1 and
gcd(a,b)which divides both of our numbers
b, we save such numbers in a array,
We also sort this array so that factors are arranged in increasing order,
For given query
q, we check
q, let’s assume two queries
lowerBound(p) = 4and
upperBound(q)=4, as both values are same that means our query is beyond the range of factors, hence we return -1.
lowerBound(p) = 2and
upperBound(q)=4, as both values are not same that means our range coincides with range of factors, hence our answer lies at factor less than upperBound(q) i.e. 3.
min(A,B)) to save all common factors.