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

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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值