题目
P0609. 质因分解加强版
思路
代码
#include <iostream>
#include <vector>
#include <string>
std::string primeFactorization(int n) {
std::vector<int> factors;
std::vector<int> counts;
for (int i = 2; i * i <= n; ++i) {
if (n % i == 0) {
factors.push_back(i);
counts.push_back(0);
while (n % i == 0) {
n /= i;
counts.back()++;
}
}
}
if (n > 1) {
factors.push_back(n);
counts.push_back(1);
}
std::string result;
for (size_t i = 0; i < factors.size(); ++i) {
if (i > 0) {
result += "*";
}
if (counts[i] > 1) {
result += std::to_string(factors[i]) + "^" + std::to_string(counts[i]);
} else {
result += std::to_string(factors[i]);
}
}
return result;
}
int main() {
int n;
std::cin >> n;
std::cout << primeFactorization(n) << std::endl;
return 0;
}
标签:kedaOJ,std,string,factors,int,P0609,result,质因,counts
From: https://www.cnblogs.com/mcr130102/p/18262393