Find if it is possible to get a ratio from given ranges of costs and quantities in C++

C++Server Side ProgrammingProgramming

Concept

With respect of the given range of cost from lowCost to upCost and range of quantity from lowQuant to upQuant, determine if it is possible to obtain a given ratio r where r=cost/quantity, and lowCost <= cost <= upCost and lowQuant <= quantity <= upQuant.

Input

lowCost = 2, upCost = 10,
lowQuant = 3, upQuant = 9
r = 3

Output

Yes

Explanation

Here, cost = r * quantity = 3 * 3 = 9 where cost is in [1, 10] and quantity is in [2, 8]

Input

lowCost = 15, upCost = 31,
lowQuant = 6, upQuant = 13
r = 8

Output

No

Explanation

Here, cost = r * quantity = 8 * 6 = 48 where cost is not in [15, 31] and though quantity is in [6, 13]

Method

With respect of the given formula, following equation can be easily deduced −

cost=quantity * r. Where, r is indicated as ratio between cost and quantity.

With respect of above equation, logic can be easily deduced. Verify the product of every value of quantity with r and it should be noted that if any value of the product lies between lowCost and upCost, then answer is Yes otherwise it is No.

Example

 Live Demo

// C++ program to find if it is
// possible to get the ratio r
#include <bits/stdc++.h>
using namespace std;
// Here, returns true if it is
// possible to obtain ratio r
// from given cost and
// quantity ranges.
bool isRatioPossible1(int lowCost1, int upCost1,
int lowQuant1, int upQuant1,
int r1){
   for (int i = lowQuant1; i <= upQuant1; i++){
      // Used to calculate cost corresponding
      // to value of i
      int ans1 = i * r1;
      if (lowCost1 <= ans1 && ans1 <= upCost1)
      return true;
   }
   return false;
}
// Driver Code
int main(){
   int lowCost1 = 2, upCost1 = 10,
   lowQuant1 = 3, upQuant1 = 9,
   r1 = 3;
   if (isRatioPossible1(lowCost1, upCost1,
      lowQuant1, upQuant1, r1))
      cout << "Yes";
   else
      cout << "No";
   return 0;
}

Output

Yes
raja
Published on 24-Jul-2020 11:20:56
Advertisements