GCD&&LCM

A - 青蛙的约会

#include<iostream>
#include<cmath>
using namespace std;
long long ex_gcd(long long a, long long b, long long& x, long long& y) {
  if (b == 0) {
    x = 1;
    y = 0;
    return a;
  }
  long long d = ex_gcd(b, a % b, x, y);
  long long temp = x;
  x = y;
  y = temp - a / b * y;
  return d;
}
bool liEu(long long a, long long b, long long c,long long& x, long long& y){
  int d = ex_gcd(a, b, x, y);
  if (c % d != 0) return 0;
  int k = b/d;
  x = x*c/d;
  if(x >= 0)
     x = x%k;
  else
     x = x%k + k;
  return 1;
}
int main()
{
    long long i,x,y,n,m,l;
    cin>>x>>y>>m>>n>>l;
    int c=x-y;
    int a=n-m;
    if(a<0)
    {
        a = -a;
        c = -c;
    }
    if(liEu(a,l,c,x,y)==0)
        cout<<"Impossible\n";
    else
        cout<<x;
    return 0;
}

 B - Least Common Multiple

ac的猝不及防,C++报错:

0_0_33373803_13403.cpp
0_0_33373803_13403.cpp(10) : error C3861: “__gcd”:  找不到标识符

因为__gcd()是GNU里面的函数,而不是是标准库内的函数,所以编译器选用G++

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
long long Function(vector<long long> num)
{
    long long gcd=0,res=num[0];
    for(long long i=1;i<num.size();++i)
    {
        gcd=__gcd(num[i],res);
        res=res*num[i]/gcd;
    }
    return res;
}
int main()
{
    long long n,m,t;
    cin>>n;
    for(long long i=0;i<n;++i)
    {
        cin>>m;
        vector<long long> num;
        for(long long j=0;j<m;++j)
        {
            cin>>t;
            num.push_back(t);
        }
        cout<<Function(num)<<endl;
        num.clear();
    }
    return 0;
}

 C - A/B

最后一步是防止负数

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int ex_gcd(int a, int b, int& x, int& y) {
  if (b == 0) {
    x = 1;
    y = 0;
    return a;
  }
  int d = ex_gcd(b, a % b, x, y);
  int temp = x;
  x = y;
  y = temp - a / b * y;
  return d;
}
int main()
{
    int n,b,t,x,y;
    cin>>t;
    for(int i=0;i<t;++i)
    {
        cin>>n>>b;
        ex_gcd(b,9973,x,y);
        cout<<(x*n%9973+9973)%9973<<endl;
    }
    return 0;
}

 D - 又见GCD

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int main()
{
    int t,a,b,c;
    cin>>t;
    for(int i=0;i<t;++i)
    {
        cin>>a>>b;
        c=b+1;
        while(1)
        {
            if(__gcd(a,c)==b)
            {
                cout<<c<<endl;
                break;
            }
            else
            {
                c++;
            }
        }
    }
    return 0;
}

 

posted @ 2020-06-28 22:45  东坡肉肉君  阅读(94)  评论(0编辑  收藏  举报