Light OJ 1215 Finding LCM

来源:互联网 发布:隐身侠软件下载 编辑:程序博客网 时间:2024/06/03 18:29

http://www.lightoj.com/volume_showproblem.php?problem=1215

题目大意,给出 a  b  c  三个数中的 a  和   b  ,他们的最小公倍数 L ,求出最小的   c 。

我们知道求n  个数的最小公倍数可以先求出前两个数的最小公倍数,然后和第三个数求最小公倍数。。。。。

首先求出  a  和  b 的最小公倍数   m  ,如果  c  和m  互质,那么  c  将是最小的,所以,我们可以假设   gcd(c , m ) == 1,如果能达到这个状态,那么 c 就是我们要求的值,如果达不到这个状态,因为m   是固定不变的,只能增大  c  ,这时令 c  = gcd ( c , m ) *c  , m  = m / gcd ( c , m ),直到找到gcd ( c , m  ) == 1 时 c 的值。

要注意不要忘记判断 特俗数据,当 m  >  L  , L %  m  != 0 的时候。

#include <stdio.h>#include <string.h>#include<iostream>using namespace std;typedef long long LL;LL gcd(LL a,LL b){    return b == 0?a:gcd(b,a%b);}LL lcm(LL a,LL b){    return a*b/gcd(a,b);}int main(){    int T,num = 1;    cin>>T;    LL a,b,c,m,t,g,L;    while(T--)    {        cin>>a>>b>>L;        m = lcm(a,b);        if(L % m != 0 || m > L)        cout<<"Case "<<num++<<": "<<"impossible"<<endl;        else        {            c = L/m;            t = gcd(c,m);            while(t != 1)            {                //g = gcd(c,m);                c = c*t, m = m/t;                t = gcd(c,m);            }            cout<<"Case "<<num++<<": "<<c<<endl;        }    }    return 0;}

 

0 0
原创粉丝点击