题目链接:Weird Subtraction Process
题意
给定两个正数 a a 和 ,每次对这两个正数做下面的操作:
- 如果 a=0 a = 0 或者 b=0 b = 0 ,结束操作。否则执行操作 2 2 。
- 如果 ,将 a a 变为 ,然后执行操作 1 1 。否则执行操作 。
- 如果 b≥2a b ≥ 2 a ,将 b b 变为 ,然后执行操作 1 1 。否则结束操作。
求操作结束后 和 b b 的值。
输入
输入包含两个整数 。
输出
输出操作结束后 a a 和 的值。
样例
输入 |
---|
12 5 |
输出 |
0 1 |
提示 |
a=12,b=5→a=2,b=5→a=2,b=1→a=0,b=1 a = 12 , b = 5 → a = 2 , b = 5 → a = 2 , b = 1 → a = 0 , b = 1 。 |
输入 |
---|
31 12 |
输出 |
7 12 |
提示 |
a=31,b=12→a=7,b=12 a = 31 , b = 12 → a = 7 , b = 12 。 |
题解
b≥2a b ≥ 2 a 时,多次执行 b−2a b − 2 a 的结果是 b%2a b % 2 a ,因此用取模运算代替减法运算,可以在 O(logn) O ( log n ) 的时间复杂度内求得答案。
过题代码
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <climits>
#include <cstring>
#include <string>
#include <vector>
#include <list>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <bitset>
#include <algorithm>
#include <functional>
#include <iomanip>
using namespace std;
#define LL long long
LL a, b;
int main() {
#ifdef LOCAL
freopen("test.txt", "r", stdin);
// freopen("out.txt", "w", stdout);
#endif // LOCAL
ios::sync_with_stdio(false);
while(scanf("%I64d%I64d", &a, &b) != EOF) {
while(a != 0 && b != 0) {
if(a >= 2 * b) {
a %= 2 * b;
continue;
}
if(b >= 2 * a) {
b %= 2 * a;
continue;
}
break;
}
printf("%I64d %I64d\n", a, b);
}
return 0;
}