UVALive7045 多少个不同的数

UVALive7045 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 ≤ 10^18).
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两个数,让
s[0]=a;
s[1]=b;
s[i]=| s[i-1] - s[i-2] |;
找出这个s序列中有多少个不同的数。
分析:这种存在绝对值,又是和前两个数有关的题肯定有规律可循,于是乎打表,为了看出来规律,我干脆让i从2达到1000,输出每一个s[i],来寻找规律,我是在a=99;b=12;和a=99;b=7;这两组数据中发现的规律。就<99,12>这组数据,发现s[i]依次有87,75,63,51,39,27,15,3(虽然不是连续的),这些数字是不相同的,并且有99/12个!,而且那个3是等于99%12的,然后又依次出现了9,6,3,0(不连续),这不就是<12,3>的情况吗,发现这就是规模从<99,12>缩小到了<12,99%12>呀,哈哈,规律找到了

打表找规律的代码:

#include<iostream>
#include<cmath>
using namespace std;
int main(){
    int s[10000];
    cin>>s[0]>>s[1];
    for(int i=2;i<=1000;i++){
        s[i]=abs(s[i-1]-s[i-2]);
        cout<<s[i]<<ends;
    }
}

AC的代码:

#include<cstdio>
#include<algorithm>
using namespace std;
int main(){
    int T;
    long long a,b,sum;
    scanf("%d",&T);
    for(int t=1;t<=T;t++){
        sum=0;
        scanf("%lld%lld",&a,&b);
        if(a<b)swap(a,b);//让a>=b方便做除法
        if(a==0)sum=0;//a=0说明b也为0
        else if(b==0)sum=1;//说明a不为0
        else do{
                sum+=a/b;//打表的时候发现出现a-b、a-2b、a-3b...直到a%b,这些都是不同的数,共有a/b个
                a%=b;//然后取a/b的余数a%b
                swap(a,b);//交换a和b(还是让a>b),这样规模就从<a,b>缩小到了<b,a%b>,然后重复上述过程
            }while(b);//直到0结束
        printf("Case #%d: %lld\n",t,sum+1);
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值