【模板】质因数分解

· · 算法·理论

e.g CF1294C Product of Three Numbers

(小学就会的模板为什么到高一竟然写不对了/kk)

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <cstdlib> 
#define MAXN 10000
using namespace std;

inline int read() {
    register int x = 0, f = 1;
    char ch = getchar();
    while (!isdigit(ch)) {
        if (ch == '-') f = -1;
        ch = getchar();
    }
    while (isdigit(ch)) {
        x = x * 10 + ch - '0';
        ch = getchar();
    }
    return x * f;
}

inline bool is_prime(int x) {
    if (x == 1) return false;
    if (x == 2) return true;
    for (int i = 2; i <= sqrt(x); i++) {
        if (x % i == 0) return false; 
    }
    return true;
}

int cnt[MAXN], yin[MAXN];

inline void Calc(int n) {
    int m = n, eid = 0;
    for (int i = 2; i <= sqrt(n); i++) { //注意:分解质因数时这里是sqrt(n) 
        if (n % i == 0 && is_prime(i)) { //注意要判断i是不是质因子 
            yin[++eid] = i;
            cnt[eid] = 0; 
            while (n % i == 0) {
                cnt[eid]++;
                n /= i;
            }
        }
    }
    if (n > 1) { //如果n是质数的话会没有小于等于√n 的因子,所以要最后处理 
        yin[++eid] = n;
        cnt[eid] = 1; 
    }
    if (eid == 1) {
        if (cnt[1] <= 5) printf("NO\n");
        else {
            printf("YES\n");
            printf("%d %d %d\n", yin[1], yin[1] * yin[1], m / (yin[1] * yin[1] * yin[1]));
        }
    }
    if (eid == 2) {
        if (cnt[1] + cnt[2] <= 3) printf("NO\n");
        else {
            printf("YES\n");
            printf("%d %d %d\n", yin[1], yin[2], m / (yin[1] * yin[2]));
        }
    }
    if (eid >= 3) {
        printf("YES\n");
        printf("%d %d %d\n", yin[1], yin[2], m / (yin[1] * yin[2]));
    }
}

int main() {
    int t = read();
    for (int i = 1; i <= t; i++) {
        int n = read();
        Calc(n);
    }
    return 0;
}