top1编程
← 返回题目
题解

【基础】分解质因数

1 条题解

  • 0
    @ 2026-7-29 0:17:41
    #include <iostream>
    #include <vector>
    #include <cmath>
    #include <cstring>
    using namespace std;
    
    const int MAX = 10001;  // 因为 b <= 10000
    
    // 筛法预处理素数表
    vector<int> primes;
    bool isPrime[MAX];
    
    void sieve() {
        memset(isPrime, true, sizeof(isPrime));
        isPrime[0] = isPrime[1] = false;
        for (int i = 2; i < MAX; ++i) {
            if (isPrime[i]) {
                primes.push_back(i);
                for (int j = i * i; j < MAX; j += i) {
                    isPrime[j] = false;
                }
            }
        }
    }
    
    // 对 n 进行质因数分解,返回分解结果字符串
    string factorize(int n) {
        string result = "";
        int temp = n;
        for (int p : primes) {
            if (p > temp) break;
            if (p * p > temp) break;  // 剩下的一定是素数
            while (temp % p == 0) {
                if (result.empty()) {
                    result += to_string(p);
                } else {
                    result += "*" + to_string(p);
                }
                temp /= p;
            }
        }
        // 如果最后 temp > 1,说明还有一个素因子
        if (temp > 1) {
            if (result.empty()) {
                result = to_string(temp);
            } else {
                result += "*" + to_string(temp);
            }
        }
        return result;
    }
    
    int main() {
        int a, b;
        cin >> a >> b;
    
        // 预处理素数
        sieve();
    
        // 逐个输出 [a, b] 中每个数的分解
        for (int k = a; k <= b; ++k) {
            cout << k << "=" << factorize(k) << endl;
        }
    
        return 0;
    }
    
    • 1