提交时间:2026-06-17 19:46:00
运行 ID: 91858
#include <iostream> #include <vector> #include <cmath> using namespace std; // 生成素数表 vector<int> get_primes(int max_val) { vector<bool> is_prime(max_val + 1, true); vector<int> primes; // 修正点:正确初始化 0 和 1 为非素数 if (max_val >= 0) is_prime[0] = false; if (max_val >= 1) is_prime[1] = false; for (int i = 2; i <= max_val; ++i) { if (is_prime[i]) { primes.push_back(i); // 防止溢出,使用 long long for (long long j = (long long)i * i; j <= max_val; j += i) { is_prime[j] = false; } } } return primes; } int main() { // 优化IO ios::sync_with_stdio(false); cin.tie(NULL); int a, b; if (!(cin >> a >> b)) return 0; // 1. 筛选素数,只需筛到b即可 vector<int> primes = get_primes(b); // 2. 遍历区间 [a, b] for (int k = a; k <= b; ++k) { cout << k << "="; int temp = k; bool first = true; // 用于控制乘号输出 // 3. 试除分解 for (int p : primes) { // 优化:只试除到sqrt(temp),避免不必要的循环 if ((long long)p * p > temp) break; while (temp % p == 0) { if (!first) cout << "*"; cout << p; first = false; temp /= p; } } // 如果剩余部分大于1,说明它本身是一个大质数 if (temp > 1) { if (!first) cout << "*"; cout << temp; } cout << endl; } return 0; }