본문 바로가기
Algorithm/Mathmatics

[CODEFORCES] Three Swimmers

by 지면서 배우자 2021. 2. 24.

Problem

Three swimmers decided to organize a party in the swimming pool! At noon, they started to swim from the left side of the pool.

It takes the first swimmer exactly a minutes to swim across the entire pool and come back, exactly b minutes for the second swimmer and c minutes for the third. Hence, the first swimmer will be on the left side of the pool after 0, a, 2a, 3a, ... minutes after the start time, the second one will be at 0, b, 2b, 3b, ... minutes, and the third one will be on the left side of the pool after 0, c, 2c, 3c, ... minutes.

You came to the left side of the pool exactly p minutes after they started swimming. Determine how long you have to wait before one of the swimmers arrives at the left side of the pool.

 

Input

The first line of the input contains a single integer t (1 ≤ t ≤1000) — the number of test cases. Next t lines contains test case descriptions, one per line.

Each line contains four integers p, a, b and c (1 p, a, b, c 10^18), time in minutes after the start, when you came to the pool and times in minutes it take the swimmers to cross the entire pool and come back.

Output

For each test case, output one integer — how long you have to wait (in minutes) before one of the swimmers arrives at the left side of the pool.

 

Input Output
4
9 5 4 8
2 6 10 9
10 2 5 10
10 9 9 9

1
4
0
8

 

CODE

#include <bits/stdc++.h>

using namespace std;

long long solve(long long p, long long a, long long b, long long c)
{
    long long ansA = p % a ? a * ((p / a) + 1) - p : 0;
    long long ansB = p % b ? b * ((p / b) + 1) - p : 0;
    long long ansC = p % c ? c * ((p / c) + 1) - p : 0;
    return min(ansA, min(ansB, ansC));
}

int main()
{
    ios::sync_with_stdio(false);
    cin.tie(NULL);

    int t;
    cin >> t;
    while(t--)
    {
        long long p, a, b, c;
        cin >> p >> a >> b >> c;
        cout << solve(p, a, b, c) << '\n';
    }
}

 

COMMENT

실수만 조심하면 되는 간단한 수학문제이다. 시간복잡도는 O(1) 이다.

 

도움이 되셨다면 공감 꾸욱! 부탁드립니다 ~~!!😊

'Algorithm > Mathmatics' 카테고리의 다른 글

[CODEFORCES] Card Deck  (0) 2021.03.25

댓글