- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
Water and Jug Problem in C++
Suppose we have two jugs with capacities x and y liters. There is an infinite amount of water supply available to us. Now we need to determine whether it is possible to measure exactly z liters using these two jugs. If z liters of water are measurable, we must have z liters of water contained within one or both buckets by the end.
We can do these few operations −
Fill any of the jugs fully with water.
Empty any of the jugs.
Pour water from one jug into another till the other jug is completely full or the first jug itself is empty.
So if x = 2 and y = 5, and z = 4, then it will return true.
To solve this, we will follow these steps −
if x + y < z, then return false
if x = z or y = z, or x + y = z, then return true
return true z is divisible by gcd of x and y, otherwise false
Example (C++)
Let us see the following implementation to get a better understanding −
#include <bits/stdc++.h&g; using namespace std; class Solution { public: bool canMeasureWater(int x, int y, int z) { if(x + y < z) return false; if(x == z || y == z || x + y == z) return true; return z % __gcd(x, y) == 0; } }; main(){ Solution ob; cout << (ob.canMeasureWater(3,5,4)); }
Input
3 5 4
Output
1
- Related Articles
- Partition Problem in C++
- Fitting Shelves Problem in C++
- Friends Pairing Problem in C++
- If We Hold a jug filled with water with soapy hands, it tends to slip from our hands. Why?
- 0-1 Knapsack Problem in C?
- Minimum Word Break Problem in C++
- A jug contains 6000 litres of juice. If ( 20 % ) of more juice is added, what is the total quantity of juice in the jug now?
- 2-Satisfiability(2-SAT) Problem in C/C++?
- Snake and Ladder Problem
- Nuts and Bolt Problem
- A Peterson Graph Problem in C Program?
- Activity Selection Problem (Greedy Algo-1) in C++?
- C++ Program to Implement Network_Flow Problem
- C Program for Activity Selection Problem
- Solve the Sherlock and Array problem in JavaScript
