- Related Questions & Answers
- Water and Jug Problem in C++
- Swap two variables in one line using C#
- What is the difference between Liter and Litre?
- Swap two variables in one line in C/C++, Python, PHP and Java
- Swap two variables in one line in using Java
- Swap two variables in one line in using Python?
- Swap two variables in one line in C/C+
- Swim in Rising Water in C++
- Container with Most Water in C++
- Measure execution time with high precision in C/C++
- Generate Infinite Stream of Integers in Java using IntStream.generate()
- Generate Infinite Stream of Double in Java using DoubleStream.iterate()
- Generate Infinite Stream of Integers in Java using Random.ints()
- How to create an infinite loop in C#?
- C# program to merge two sorted arrays into one

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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.

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; }

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

Advertisements