Codeforces 1328A Divisibility Problem 整除性問題

難易度 : 800

英文原文如下

You are given two positive integers a and b. In one move you can increase a by 1(replace a with a+1). Your task is to find the minimum number of moves you need to do in order to make a divisible by b. It is possible, that you have to make 0 moves, as a is already divisible by b. You have to answer t independent test cases.

中文翻譯

給予你兩個正整數 ab。在一次移動中,你可以將 a 增加 1 (用 a+1 替換掉 a)。你的任務是要找到最小的移動步數來使 a 可以被 b 整除。有可能你不需任何動作(移動 0 步),因為 a 本來就可以被 b 整除。 你需要回答 t 個獨立的測試案例。

輸入

The first line of the input contains one integer t (1≤t≤104) — the number of test cases. Then t test cases follow.

The only line of the test case contains two integers a and b (1≤a,b≤109).

第一行輸入包含了一個整數 t (1≤t≤104) — 測試案例的數量,接下來就有 t 行案例。

測試案例各自都只有一行,包含了兩個整數 ab(1≤a,b≤109)。

輸出

For each test case print the answer — the minimum number of moves you need to do in order to make a divisible by b.

每一個案例都要印出答案 — 你需要的最小移動步數來使 ab 整除。

範例

輸入5
10 4
13 9
100 13
123 456
92 46
輸出2
5
4
333
0

10+2 = 12 = 4*3

13+5 = 18 = 9*2

100+4 = 104 = 13*8

123+333 = 456 = 456*1

92+0 = 92 = 46*2


解題思路

這一題只要使用餘數就能很輕易的解決,尤其是 a 跟 b的範圍都限制為正整數且不為 0 了,不用擔心例外狀況。

用 b – a%b (也就是餘數),就會是a到達下個b的倍數所需的步數(一次加 1)

C#解決方案

方案1

int n = int.Parse(Console.ReadLine());

for(int i=0; i<n; i++){
    string[] arr = Console.ReadLine().Split(" ");
    int a = int.Parse(arr[0]);
    int b = int.Parse(arr[1]);
    
    int left = a%b;
    
    Console.WriteLine(left==0 ? 0 : b-left);
}

結論

本來還擔心 109 可能會超過 int的限制,但看來是沒有的 (int32 max = 2,147,483,647 2*1010)

🧡如果文章有幫上你的忙,那是我的榮幸

🧡收藏文章或幫我點個廣告,那都是對我的支持 (幫我多多分享也大感謝!!)

✅如有任何疑問,歡迎透過留言或messenger讓我知道 !

題目連結 : Problem – 1328A – Codeforces

一些其他的Codeforces文章

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *