- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- 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
Measure one litre using two vessels and infinite water supplys in C++
In this problem, we are given two vessels with capacities x and y and a supply of infinite water. Our task is to create a program that will be able to calculate exactly 1 liter in one vessel. Given the condition that x and y are co-primes. Co-primes also is known as relatively prime, mutually prime are numbers two numbers that have 1 as their only common divisor. So, this implies that their gcd(greatest common divisor) is 1.
Here, let’s suppose we have two vessels V1 with capacity x and V2 with capacity y. To measure 1 liter using these two vessels we will fill first vessels from water supply and then pour it to the second one. Do this process continues until the vessel V1 contains 1 litre of water.
Let’s take an example to understand the problem,
Input −
V1 = 5, V2 = 8 V1 = 5 ; V2 = 0 -> pour water from V1 to V2 and refill it. V1 = 5 ; V2 = 5 -> pour water from V1 to V2 and refill it. V1 = 2 ; V2 = 0 -> pour water from V1 to V2. Now, V2 is filled, empty it. V1 = 5 ; V2 = 2 -> pour water from V1 to V2 and refill it. V1 = 5 ; V2 = 7 -> pour water from V1 to V2 and refill it. V1 = 4 ; V2 = 0 -> pour water from V1 to V2. Now, V2 is filled, empty it. V1 = 1 ; V2 = 0 -> pour water from V1 to V2 and refill it. Here, V1 measures 1 litre of water.
Example
Program to illustrate the solution,
#include <iostream> using namespace std; int x, y, V1, V2 = 0; int transferWater(int amt1, int amt2) { if (amt1 + amt2 < y){ V2 += V1; return V1; } int transferred = y - V2; V2 = 0; return transferred; } void measure1Litre() { while(V1 != 1){ if (V1 == 0) V1 = x; cout<<"Vessel 1: "<<V1<<" | Vessel 2: "<<V2<<endl; V1 = V1 - transferWater(V1, V2); } cout<<"Vessel 1: "<<V1<<" | Vessel 2: "<<V2<<endl; } int main() { x= 5, y = 8; measure1Litre(); return 0; }
Output
Vessel 1: 5 | Vessel 2: 0 Vessel 1: 5 | Vessel 2: 5 Vessel 1: 2 | Vessel 2: 0 Vessel 1: 5 | Vessel 2: 2 Vessel 1: 5 | Vessel 2: 7 Vessel 1: 4 | Vessel 2: 0 Vessel 1: 5 | Vessel 2: 4 Vessel 1: 1 | Vessel 2: 0