最大公约数gcd,最小公倍数lcm

欧几里得算法

#include<iostream>
#include<cstdio>
using namespace std;

int x,y;

int gcd(int a,int b){
    if(b==0) return a;
    return gcd(b,a%b);
}

int lcm(int a,int b){
    return a*b/gcd(a,b);
}

int main(){
    cin>>x>>y;
    cout<<gcd(x,y)<<endl;
    cout<<lcm(x,y)<<endl;
    return 0;
} 

 Luogu P1029最大公约数和最小公倍数问题

 题目

#include<iostream>
#include<cmath> 
#include<cstdio>
#include<cstdlib>
#define maxn 100010
#define ll long long
using namespace std;
template<typename T>
inline void read(T &x){
    x=0; bool flag=0; char c=getchar();
    for(;!isdigit(c);c=getchar()) if(c=='-') flag=1;
    for(;isdigit(c);c=getchar()) x=x*10+(c^48);
    if(flag) x=-x;
}

ll x,y,ans;

ll gcd(ll a,ll b){
    if(b==0) return a;
    return gcd(b,a%b);
}

int main(){
    read(x),read(y);
    for(int i=1;i<=sqrt(x*y);i++)
        if((x*y)%i==0&&gcd(i,x*y/i)==x)
            ans+=2;
    if(x==y) ans--;
    cout<<ans<<endl;
    return 0;
}

 

posted @ 2021-03-06 21:30  DReamLion  阅读(77)  评论(0编辑  收藏  举报