辗转相除法(数学推理)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Let_life_stop/article/details/83153372

题目链接:https://vjudge.net/contest/262544#problem/F

具体思路:因为给定的 n,m是两个常数(n<m)。所以一定能写成m=k*n+b,这里k的指数是多少,就意味着这一轮m能用n通过 i*n+b的形式表示出来多少种,所以直接不断地递归找规律就行了。

AC代码:

#include<iostream>
#include<string>
#include<cstring>
#include<iomanip>
#include<cmath>
#include<stdio.h>
#include<algorithm>
#include<queue>
using namespace std;
# define ll long long
# define maxn
# define inf 0x3f3f3f3f
ll cal(ll n,ll m)
{
    ll ans=0;
    while(m)
    {
        ans+=(n/m);
        ll temp=n;
        n=m;
        m=temp%m;
    }
    return ans;
}
int main()
{
    int T;
    scanf("%d",&T);
    int num=0;
    while(T--)
    {
       ll n,m;
        scanf("%lld%lld",&n,&m);
        ll temp;
        if(n>m)
        {
            temp=n;
            n=m;
            m=temp;
        }
        printf("Case #%d: ",++num);
        if(n==0&&m==0)printf("1\n");
        else if(n==0||m==0)printf("2\n");
        else printf("%lld\n",cal(n,m)+1);
    }
}

猜你喜欢

转载自blog.csdn.net/Let_life_stop/article/details/83153372