ProblemK. Last Defence
Description
Given two integersA and B. Sequence S is defined as follow:
• S0 = A
• S1 = B
• Si = |Si−1 −Si−2| for i ≥ 2
Count the number ofdistinct numbers in S.
Input
The first line ofthe input gives the number of test cases, T. T test cases follow. Tis about 100000.
Each test caseconsists of one line - two space-separated integers A, B. (0 ≤ A, B≤ 1018).
Output
For each test case,output one line containing “Case #x: y”, where x is the test casenumber (starting from 1) and y is the number of distinct numbers inS.
Samples
Sample Input | Sample Output |
2 7 4 3 5 | Case #1: 6 Case #2: 5 |
题目大意:给定两个数,每次由两个数的差得到一个新的数,求一共能得到几个不同的数。
解题思路:因为最终会得到X X 0这样循环出现的数,所以不同数字个数是有限个的。因为数字太大,直接求会T,正解是辗转相除法。我的方法是观察找规律,根据两个数的差值和两个数之间的关系,可以得到后面数字的个数。
代码如下:
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#define ll long long
#define mod=1e9+7;
using namespace std;
const int maxn=10000005;
ll ans;
void getans(ll a,ll b)
{
if(a==b)
return ;
ll c=a-b; //根据a,c,b之间的关系可以得到一段长度为cur的等差数列,长度即数字个数
ll cur=a/c; //得到多段等差数列
a=a-(cur-1)*c;
ans+=cur-1;
getans(a,c);
}
int main(void)
{
int t;
ll x,y,a,b,c;
scanf("%d",&t);
for(int ca=1;ca<=t;ca++)
{
ans=0;
scanf("%I64d%I64d",&x,&y);
if(x==y) //x,y相同时特判一下
{
if(x==0)
printf("Case #%d: 1\n",ca);
else
printf("Case #%d: 2\n",ca);
continue;
}
if(x>y) //保证得到的a,b值是a>b
{
ll c=x-y;
a=x;
if(c>y)
b=c;
else
b=y;
}
else
{
ll c=y-x;
a=y;
if(c>x)
b=c;
else
b=x;
}
getans(a,b);
printf("Case #%d: %I64d\n",ca,ans+2);
}
}
正解辗转相除法:
#include <cstdio>
#include <cstring>
#define ll long long
using namespace std;
ll ans;
void get_ans(ll a,ll b)
{
if(b==0)
return;
ans+=a/b;
get_ans(b,a%b);
}
int main()
{
int t;
ll a,b;
scanf("%d",&t);
for(int ca=1;ca<=t;ca++)
{
ans=0;
scanf("%I64d%I64d",&a,&b);
if(a==0||b==0)
{
if(a==0&&b==0)
printf("Case #%d: 1\n",ca);
else
printf("Case #%d: 2\n",ca);
continue;
}
if(a>b)
get_ans(a,b);
else
get_ans(b,a);
printf("Case #%d: %I64d\n",ca,ans+1);
}
return 0;
}