HDU 4993 Revenge of ex-Euclid

Description

In arithmetic and computer programming, the extended Euclidean algorithm is an extension to the Euclidean algorithm, which computes, besides the greatest common divisor of integers a and b, the coefficients of Bézout’s identity, that is integers x and y such that ax + by = gcd(a, b).
—Wikipedia

Today, ex-Euclid takes revenge on you. You need to calculate how many distinct positive pairs of (x, y) such as ax + by = c for given a, b and c.

Input

The first line contains a single integer T, indicating the number of test cases.

Each test case only contains three integers a, b and c.

[Technical Specification]
1. 1 <= T <= 100
2. 1 <= a, b, c <= 1 000 000

Output

For each test case, output the number of valid pairs.

Sample Input

2
1 2 3
1 1 4

Sample Output

1
3

题意

给a,b,c,求满足ax+by=c的x,y的个数

题解

进行时间优化,由于x,y是一一对应关系,所以求x,y的个数就可以转化为求x或者y的个数。
提供两个代码,第一个是判断c-a*i>0时跳出循环,第二个是i>c/a-1或者i>c/a时跳出循环。

CODE1

#include <iostream>
#include <stdio.h>
#include <string.h>
#include <string>
#include <cstdio>
#include <cmath>
using namespace std;
int main()
{
    int T,a,b,c;
    cin>>T;
    while(T--)
    {
      cin>>a>>b>>c;
      int cnt=0;
      for(int i=1;c-a*i>0;i++)
      {
          if((c-a*i)%b==0)
            cnt++;
      }
      cout<<cnt<<endl;
    }
    return 0;
}

CODE2

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <iostream>
#include <algorithm>
#include <cmath>
#include <stack>
#include <deque>
#include <map>
#include <set>
#include <vector>
#include <string>
#include <queue>
#include <functional>
#include <time.h>
using namespace std;
int main()
{
    int n;
    cin >> n;
    while(n--)
    {
        int a,b,c;
        cin >> a >> b >> c;
        int ans = 0;
        for(int i=1;;i++)
        {
            if(c%a==0&&i>c/a-1)//因为x,y不能为0,所以当a|c时,要防止i==c/a
                break;
            else if(c%a!=0&&i>c/a)
                break;
            if((c-a*i)%b==0)
                ans++;
        }

        cout << ans << endl;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/AC__GO/article/details/81178020
今日推荐