将一个正整数分解成若干个大于一的正整数之积c++
时间: 2024-09-29 13:11:35 浏览: 34
在C++中,将一个正整数分解成若干个大于一的正整数之积,通常涉及到质因数分解(Prime Factorization)。你可以使用循环和条件判断来找出每个数的最大质因子,并将其去除,直到剩余的数变成质数或1。这里是一个简单的示例:
```cpp
#include <iostream>
#include <vector>
// Function to check if a number is prime
bool is_prime(int num) {
if (num <= 1) return false;
for (int i = 2; i * i <= num; ++i) {
if (num % i == 0)
return false;
}
return true;
}
// Function to find prime factorization
std::vector<int> prime_factors(int n) {
std::vector<int> factors;
for (int i = 2; i * i <= n; ++i) { // Start from 2 and iterate up to sqrt(n)
while (n % i == 0) {
factors.push_back(i);
n /= i; // Divide n by found factor
}
}
// If n is still greater than 1 after the loop, it's a prime number
if (n > 1) {
factors.push_back(n);
}
return factors;
}
int main() {
int input_num;
std::cout << "Enter a positive integer: ";
std::cin >> input_num;
std::vector<int> factors = prime_factors(input_num);
std::cout << "Prime factorization of " << input_num << " is: ";
for (const auto &factor : factors) {
std::cout << factor << " * ";
}
std::cout << "1" << std::endl; // Adding an explicit 1 as some factors might not be mentioned multiple times
return 0;
}
```
当你运行这个程序并输入一个正整数,它会显示该数的质因数分解。
阅读全文