在C ++中使用两个容器和无限供水量来测量一升

在这个问题上,我们给了两个容量为x和y的容器,并提供了无限量的水。我们的任务是创建一个程序,该程序将能够在一个容器中精确地计算出1升。给定x和y是互素的条件。互质也称为相对质数,互质数是具有1的唯一除数的数字2。因此,这意味着它们的gcd(最大公约数)为1。

在这里,让我们假设我们有两个容量为x的容器V1和容量为y的容器V2。为了使用这两个容器测量1升的水,我们将首先从供水系统中填充第一个容器,然后将其倒入第二个容器中。继续进行此过程,直到容器V1中装有1升水为止。

让我们举个例子来了解这个问题,

输入 -

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.

示例

用于说明解决方案的程序,

#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