Poor Pigs in C++


Suppose there are 1000 buckets, one of them is poisonous, others are filled with water. They all look similar. If a pig drinks the poison it will die within 15 minutes. What will be the minimum amount of pigs that we need to find out the poisonous bucket within one hour?

So now consider for the general case and devise an algorithm for this. So, the general case is that If there are n different buckets and a pig drinking poison will die within m minutes, how many pigs are needed to find poisonous bucket within p minutes? There is exactly one bucket with poison.

When the n = 1000, m = 15 and p = 60, then the output will be 5.

To solve this, we will follow these steps −

  • ret := 0
  • while (minutesToTest / minutesToDie + 1)^ret < buckets, do −
    • (increase ret by 1)
  • return ret

Let us see the following implementation to get better understanding −

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
   int poorPigs(int buckets, int minutesToDie, int minutesToTest) {
      int ret = 0;
      while(pow((minutesToTest / minutesToDie + 1), ret) < buckets) ret++;
      return ret;
   }
};
main(){
   Solution ob;
   cout << (ob.poorPigs(1000,15,60));
}

Input

1000
15
60

Output

5

Updated on: 01-Jun-2020

141 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements