您的位置:首页 > Web前端

文章标题 UVALive 7045:Last Defence(辗转相除思想)

2016-09-11 20:53 465 查看

Last Defence

Given two integers A and B. Sequence S is defined as follow: • S0 = A • S1 = B • Si = |Si−1 −Si−2| for i ≥ 2 Count the number of distinct numbers in S.

Input

The first line of the input gives the number of test cases, T. T test cases follow. T is about 100000. Each test case consists 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 case number (starting from 1) and y is the number of distinct numbers in S.

Sample Input

2

7 4

3 5

Sample Output

Case #1: 6

Case #2: 5

题意:给你a,b两个数,然后从第三个开始,每个数都是前两个数的差的绝对值,问这个序列中有多少个不同的元素。

分析:一开始以为直接暴力,最后肯定会有一个数变为0。直接暴力,用set求元素个数。但a,b的范围太大,所以wa了一发。其实这有点辗转相除的思想,假设a>b,所以后面的序列就有a/b个数,最后剩下a%b这个数,然后再比较a%b,b这两个数,最后能直接除尽的话说明能刚好出现0,所以加上a/b+1个数就行了。同时,还得注意特殊情况,就是a,b为零是情况,在这里又wa了一次。。。

代码:

#include<iostream>
#include<string>
#include<cstdio>
#include<cstring>
#include<vector>
#include<math.h>
#include<map>
#include<set>
#include<queue>
#include<algorithm>
using namespace std;
const int inf = 0x3f3f3f3f;
void f(long long a,long long b,long long &ans){
//判别a,b是否为0
if (a==0&&b==0) {
ans+=1;
return;
}
if ((a==0&&b!=0)||(a!=0&&b==0)){
ans+=2;
return;
}
if (a>b){
if (a%b==0){//是否能整除
ans+=(a/b+1);
return ;
}
ans+=a/b;
f(a%b,b,ans);
}
else {
if (b%a==0){
ans+=(b/a+1);
return ;
}
ans+=(b/a);
f(b%a,a,ans);
}
}
int main ()
{
long long a,b;
int t;
int cnt=1;
scanf ("%d",&t);
while (t--){
scanf ("%lld%lld",&a,&b);
long long ans=0;
f(a,b,ans);
printf ("Case #%d: %lld\n",cnt++,ans);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: