d306: 10193 - All You Need Is Love

  1. 1. 內容
  2. 2. 範例輸入
  3. 3. 範例輸出
  4. 4. 想法
  5. 5. 程式碼

CPE 一顆星選集 49 道必考題

題目連結:https://zerojudge.tw/ShowProblem?problemid=d306

內容

給定兩個二進制正整數,任取一數減另一數,不斷重複,判斷最後兩數是否會相等。

第一列有一個整數 N (N < 10000),代表測資數,接著為兩數 a, b (1 < a, b <= 2^30)。

範例輸入

5
11011
11000
11011
11001
111111
100
1000000000
110
1010
100

範例輸出

Pair #1: All you need is love!
Pair #2: Love is not all you need!
Pair #3: Love is not all you need!
Pair #4: All you need is love!
Pair #5: All you need is love!

想法

先將兩數轉成十進制,再取最大公因數。

程式碼

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <bits/stdc++.h>
#define fastio ios_base::sync_with_stdio(false), cin.tie(nullptr)
using namespace std;

int to_dec(string);
bool gcd(int, int);
int main(){
fastio;
int n, n1, n2;
string s1, s2;
bool suc;
cin >> n;
for(int c = 1; c <= n; ++c){
cin >> s1 >> s2;
n1 = to_dec(s1);
n2 = to_dec(s2);
suc = gcd(n1, n2);
cout << "Pair #" << c << ": ";
if(suc) cout << "All you need is love!\n";
else cout << "Love is not all you need!\n";
}
}
int to_dec(string s){
int sum = 0;
for(int i = 0; i < s.length(); ++i){
sum = sum * 2 + (s[i] - '0');
}
return sum;
}
bool gcd(int a, int b){
while(a != 0 && b != 0){
if(a > b) a = a % b;
else b = b % a;
}
if(max(a, b) == 1) return false;
return true;
}