S1、S2,問是否能找出對兩字串皆合法的 L?N 代表測資數S1、S2 皆為二進位字串L?
S - L (二進位減法) 直到 S = L
p 代表第幾筆測資S - L,其實就是看 S 是不是 L 的倍數,題目有舉例:S = 11011 = 27
L = 11 = 3
bin dec
11011 = 27
11000 = 24
10101 = 21
10010 = 18
1111 = 15
1100 = 12
1001 = 9
110 = 6
11 = 3
S1、S2 都合法,代表 L 要同時為兩者的公因數,所以用 GCD 檢查兩者是否互質 (GCD = 1);先把輸入轉成十進位比較好處理N 後,用 while 迴圈重複讀入兩字串存到字元陣列裡
int N;
scanf("%d", &N);
while(N--){
char S1[31] = {0};
char S2[31] = {0};
scanf("%s%s", S1, S2);
...
}
int str_to_int(char *a, char *b){
int num1 = 0, num2 = 0;
int i;
for(i = 0; i < strlen(a); i++){
num1 = (num1 << 1) + (a[i] - '0');
}
for(i = 0; i < strlen(b); i++){
num2 = (num2 << 1) + (b[i] - '0');
}
return GCD(num1, num2);
}
int GCD(int a, int b){
return b == 0 ? a : GCD(b, a % b);
}
if(str_to_int(S1, S2) != 1){
printf("Pair #%d: All you need is love!\n", Case++);
}
else{
printf("Pair #%d: Love is not all you need!\n", Case++);
}
#include<stdio.h>
#include<string.h>
int GCD(int a, int b){
return b == 0 ? a : GCD(b, a % b);
}
int str_to_int(char *a, char *b){
int num1 = 0, num2 = 0;
int i;
for(i = 0; i < strlen(a); i++){
num1 = (num1 << 1) + (a[i] - '0');
}
for(i = 0; i < strlen(b); i++){
num2 = (num2 << 1) + (b[i] - '0');
}
return GCD(num1, num2);
}
int main(){
int N, Case = 1;
scanf("%d", &N);
while(N--){
char S1[31] = {0};
char S2[31] = {0};
scanf("%s%s", S1, S2);
if(str_to_int(S1, S2) != 1){
printf("Pair #%d: All you need is love!\n", Case++);
}
else{
printf("Pair #%d: Love is not all you need!\n", Case++);
}
}
return 0;
}
stoi()
dec、hex、oct 可用
gcd(),但 C++17 才支援
#include <bits/stdc++.h>
using namespace std;
int GCD(int a, int b){
return b == 0 ? a : GCD(b, a % b);
}
int main(){
int N, Case = 1;
cin >> N;
while(N--){
string S1, S2;
cin >> S1 >> S2;
int num1 = stoi(S1, nullptr, 2), num2 = stoi(S2, nullptr, 2);
if(GCD(num1, num2) != 1){
cout << "Pair #" << Case++ << ": All you need is love!\n";
}
else{
cout << "Pair #" << Case++ << ": Love is not all you need!\n";
}
}
return 0;
}