首页 > 代码库 > UVA11889 - Benefit

UVA11889 - Benefit

题目链接


题意:输入两个整数A和C,求最小的整数B使得lcm(A, B) = C,如果无解,输出“NO SULUTION”。

思路:lcm(A, B) * gcd(A, B) = A * B转化为C / A = B / gcd(A, B),所以可以枚举B的倍数。

代码:

#include <iostream>
#include <cstdio>
#include <cmath>
#include <algorithm>

using namespace std;

int a, c;

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

int main() {
    int cas;    
    scanf("%d", &cas);
    while (cas--) {
        scanf("%d%d", &a, &c); 
        if (c % a != 0) {
            printf("NO SOLUTION\n"); 
        }
        else {
            int b = c / a;  
            int flag = 0;
            for (int i = b; i <= c; i += b) {
                if (b == i / gcd(i, a)) {
                    printf("%d\n", i); 
                    break;
                }
            } 
        } 
    }
    return 0;
}


UVA11889 - Benefit