以下是一個用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)的質數來進行質因數分解。最后將所有質因數輸出。