以下是一个用C++编写的分解质因数的程序示例:
#include <iostream>
#include <vector>
void primeFactors(int n) {
std::vector<int> factors;
while (n % 2 == 0) {
factors.push_back(2);
n = n / 2;
}
for (int i = 3; i <= sqrt(n); i = i + 2) {
while (n % i == 0) {
factors.push_back(i);
n = n / i;
}
}
if (n > 2) {
factors.push_back(n);
}
std::cout << "Prime factors of the number are: ";
for (int i = 0; i < factors.size(); i++) {
std::cout << factors[i] << " ";
}
}
int main() {
int num;
std::cout << "Enter a number to find its prime factors: ";
std::cin >> num;
primeFactors(num);
return 0;
}
这个程序接受用户输入的一个数,然后找出它的所有质因数并打印输出。程序首先检查这个数是否能被2整除,然后再用除数从3开始逐渐增加到sqrt(n)的质数来进行质因数分解。最后将所有质因数输出。