暴力枚举如何优化?(60pts)

P1029 [NOIP2001 普及组] 最大公约数和最小公倍数问题

Algorithm_ZRF @ 2023-11-22 20:48:12

#include <iostream>
using namespace std;
int x,y,cnt;
inline int gcd(int a, int b) {
    while (b != 0) {
        int tmp = a;
        a = b;
        b = tmp % b;
    }
    return a;
}

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

signed main() {
    cin >> x >> y;
    for(int i = 1; i <= y; ++i) {
        for(int j = 1; j <= y; ++j) {
            if(gcd(i,j) == x && lcm(i,j,gcd(i,j)) == y) {
                cnt++;
            }
        }
    }
    cout << cnt;
    return 0;
}

6 #7 #9 #10 TLE


by Foggy_night @ 2023-11-22 20:55:56

不需要双重循环的,你内重只要枚举

j = x * y / i

即可


by Algorithm_ZRF @ 2023-11-23 19:11:09

@Foggy_night 什么意思?


by Algorithm_ZRF @ 2023-11-23 19:24:40

@Foggy_night 懂了


|