C++ program to count how many minutes we have to wait to meet at least one swimmer


Suppose we have four numbers p, a, b and c. There is a pool and three swimmers are there. They take a, b and c minutes to cross the pool and come back, respectively. So the first swimmer will be at the left side of pool after 0, a, 2a, 3a,... minutes after the start time. The second will be at 0, b, 2b, 3b,... minutes and for the third one 0, c, 2c, 3c, ... If we visit the pool after p minutes they have started swimming we have to find how much time we have to wait at minimum to get at least one of the swimmers at the left side of pool.

So, if the input is like p = 2; a = 6; b = 10; c = 9, then the output will be because at 2 we are near the pool, the first swimmer will come back at 6 so we have to wait 4 units of time.

steps

To solve this, we will follow these steps −

(decrease p by 1)
return minimum of (a - (p mod a + 1)), (b - (p mod b + 1)) and (c - (p mod c + 1))

Example

Let us see the following implementation to get better understanding −

#include <bits/stdc++.h>
using namespace std;

int solve(int p, int a, int b, int c) {
   p--;
   return min(a - (p % a + 1), min(b - (p % b + 1), c - (p % c + 1)));
}
int main() {
   int p = 2;
   int a = 6;
   int b = 10;
   int c = 9;
   cout << solve(p, a, b, c) << endl;
}

Input

2, 6, 10, 9

Output

4

Updated on: 03-Mar-2022

155 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements